Compare commits

...
10 Commits
Author SHA1 Message Date
Atharv1705 bbd1e2e6f4 docs: Add root project README and repository documentation 2026-11-05 12:28:39 +05:30
Atharv1705 c460c08ed3 feat: Update elevation layout, appliance library, DXF generation, and reorganize tools and scripts 2026-11-05 12:17:57 +05:30
Atharv1705 e003fce9d8 feat: Fix v_matrix parsing and add HITL layout rendering support 2026-09-29 11:05:50 +05:30
Atharv1705 7ebae8a4a5 fix: Align YOLO to 12-class dataset, wire fixture_anchors, add best.pt weights 2026-09-03 12:47:26 +05:30
Atharv1705 d724af2b39 feat: Integrated PaddleOCR for rasterized PDF extraction, updated core processors and project analysis 2026-09-01 12:27:19 +05:30
Atharv1705 a5320267e1 feat: complete dynamic pipeline execution, fallback logic, and bug fixes 2026-07-16 12:38:14 +05:30
Atharv1705 08083ff3f4 Fix AI pipeline pricing bugs, standardise config schemas, resolve cache contract flaw, remove dead code, and clear outputs from tracking 2026-07-08 15:22:42 +05:30
Atharv1705 1074a112e8 Refactor LayoutFingerprintEngine and fix Shop Drawing Matrix formatting
- Introduce LayoutFingerprintEngine for topological hashing

- Remove KitchenLayoutClassifier overrides in pipeline

- Update MatrixBuilder to use the new FingerprintEngine

- Fix Cover Page layout (Appliance Schedule, Revision block, Finish box)

- Fix Matrix Page alignment, font hierarchy, and border widths
2026-07-01 16:44:00 +05:30
Atharv1705 ee2a024ff0 Fix shop drawing scaling and elevation rendering clipping issue 2026-07-01 14:01:18 +05:30
Atharv1705 151e3f7e17 Fix cabinet overlapping in shop drawings, update DXF styling, and fix PDF scaling 2026-06-23 15:20:57 +05:30
280 changed files with 18156 additions and 38108 deletions
+3 -35
View File
@@ -1,40 +1,8 @@
# ── Python cache ──────────────────────────────────────────────────────────
__pycache__/
*.py[cod]
*.pyo
*.pyd
.Python
*.egg-info/
dist/
build/
*.egg
# Analysis scratch
_analysis/
# ── Virtual environments ───────────────────────────────────────────────────
.venv/
venv/
env/
# ── OS files ──────────────────────────────────────────────────────────────
# OS files
.DS_Store
Thumbs.db
desktop.ini
# ── Large binary / generated output files ─────────────────────────────────
# Keep source PDFs (architectural drawings) but skip large generated outputs
OUTPUT_ARCH_ANALYSIS.pdf
EXTRACTION_OUTPUT/
# ── Temporary Excel lock files ────────────────────────────────────────────
~$*.xlsx
~$*.xls
# ── API keys / secrets ────────────────────────────────────────────────────
.env
*.env
secrets.py
config_local.py
# ── IDE ───────────────────────────────────────────────────────────────────
.vscode/
.idea/
*.code-workspace
+30
View File
@@ -0,0 +1,30 @@
name: Python CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python 3.9
uses: actions/setup-python@v4
with:
python-version: "3.9"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
pip install pytest pytest-cov
- name: Test with pytest
run: |
pytest --cov=core --cov=generators tests/
+27
View File
@@ -0,0 +1,27 @@
name: Tests
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python 3.10
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install pytest
- name: Run Pytest for Constraint and Placement Engine
run: |
pytest tests/test_placement.py
+33 -3
View File
@@ -41,6 +41,36 @@ outputs/*.log
*.bak
scratch/
# Generated outputs are currently tracked for demo artifacts.
# Uncomment this line if generated artifacts should be excluded in future.
# outputs/
# Generated pipeline outputs (PDF / DXF / XLSX / CSV / crop PNGs / JSON schedules)
# These are reproducible by running pipeline.py — do not track them.
outputs/
# Excel lock files
~$*.xlsx
~$*.xls
# Scratch / one-off inspection scripts (kept on disk, not tracked)
debug.py
debug_*.py
pipeline_debug.py
analyze_config.py
check_vanity.py
update_k4.py
debug.html
temp_*.py
temp_*.pdf
deep_inspect_*.py
inspect_*.py
# Scratch binary artifacts
*.png
test*.pdf
test_merge*.pdf
test_dim.dxf
OUTPUT_ARCH_ANALYSIS.pdf
EXTRACTION_OUTPUT/
shop_review/
# Datasets
data/
datasets/floor_plan_full/
File diff suppressed because it is too large Load Diff
Binary file not shown.

Before

Width:  |  Height:  |  Size: 775 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 482 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 558 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 652 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 670 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 725 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 310 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 886 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 580 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 872 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 581 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 708 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 600 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 620 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 440 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.1 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 663 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 654 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 MiB

File diff suppressed because it is too large Load Diff
File diff suppressed because one or more lines are too long
+122 -58
View File
@@ -1,44 +1,99 @@
# AI Cabinet Estimation & Shop Drawing Automation
An AI-powered pipeline that reads architectural PDF drawings and automatically generates:
- Cabinet shop drawings (ItalianKB-style PDF)
- Project cabinet matrix (Excel)
- Material cost report (Excel)
- Final job costing & selling price quote (Excel)
An AI-assisted pipeline that reads architectural PDF drawings and automatically produces:
- **Cabinet shop drawings** — ItalianKB-style 17"×11" PDF + AutoCAD DXF
- **Cabinet estimation workbook** — multi-sheet Excel (matrix, library, job costing)
- **Material BOM takeoff** — CSV of sheet goods + hardware
- **Deliverable JSON schemas** — unit matrix, shop drawing, cost estimation
## Project: Casa Familia & Heritage Village
Client: Kitchen & bathroom cabinet supplier for large-scale US residential construction (FHA/ADA housing).
Client: Italian Kitchen & Bath — a kitchen/bath cabinet supplier for large-scale US
residential construction (FHA / ADA housing). Manual estimation + drafting takes days
per project; this system targets under 24 hours.
| Project | ID | Units | Status |
|---------|-----|-------|--------|
| Casa Familia | 23-033 | 25 units (A1, A2-ADA, A3, B1, B2-ADA) | Files in hand, pipeline runs |
| Heritage Village | 23-045 | ~14 unit types | In progress |
---
## Pipeline Overview
```
Architect PDF → PyMuPDF → Text + Geometry Extraction
↓
Region Detection (Kitchen / Bath / Elevation)
↓
400 DPI Crop → Claude Vision API
↓
Cabinet Schedule JSON
↓
ReportLab → Shop Drawing PDF
openpyxl → Matrix + Pricing Excel
Architect PDF
│ PyMuPDF — text spans + vector rects + rendered crops
▼
Stage-0 page classifier (UNIT PLAN / ELEVATION / RCP / DETAIL)
│
Region detection (KITCHEN / BATH / VANITY / ELEVATION)
│ 400 DPI crop
▼
AI Vision (Gemini 2.5 Flash → 2.5 Pro fallback, via OpenRouter)
│ CabinetItem[] + architectural-intent (walls, openings, fixtures)
▼
Validation + Confidence QA (catalog widths, ADA, confidence ≥ 0.70)
│
BIM-Lite model → Constraint Solver → Placement Engine → Layout Fingerprint (K#/V# typing)
│
Price match (EUR list → USD) → Job costing (freight/install/tax/GP%)
▼
Outputs: Shop Drawing PDF + DXF, Estimation Excel, BOM CSV, JSON schemas
```
---
## Scripts
## Running the Pipeline
| File | Description |
|------|-------------|
| `step1_crop_elevations.py` | Reads architect PDF → detects regions → crops at 400 DPI → outputs JSON |
| `read_arch_drawing_pymupdf.py` | Full PyMuPDF extraction demo — 4-page visual output PDF |
| `show_pymupdf_output_formats.py` | Shows exact data types returned by each PyMuPDF method |
| `generate_italiankb_shop_drawings.py` | Generates Casa Familia shop drawing PDF (ItalianKB style) |
| `generate_heritage_shop_drawings.py` | Generates Heritage Village shop drawing PDF |
| `generate_heritage_excel.py` | Generates Heritage Village cabinet matrix + pricing Excel |
| `run_cabinet_estimation.py` | Master runner script |
```bash
pip install -r requirements.txt
# Full run (calls the Vision API — requires OPENROUTER_API_KEY in .env)
python pipeline.py --project projects/casa_familia/project_config.json
# Reuse cached cabinet schedules instead of calling the Vision API
python pipeline.py --project projects/casa_familia/project_config.json --skip-ai
# Process a single unit type
python pipeline.py --project projects/casa_familia/project_config.json --unit A1
# Low-token demo mode (150 DPI, compact prompt) — ~85% cheaper Vision calls
python pipeline.py --project projects/casa_familia/project_config.json --demo
# Validate config only, no execution
python pipeline.py --project projects/casa_familia/project_config.json --dry-run
```
### Web app (dashboard)
```bash
uvicorn web_app.app:app --reload
# then open http://127.0.0.1:8000
```
FastAPI + single-page dashboard: create/manage projects, upload unit PDFs and price
lists, stream a live pipeline run (SSE), review cabinet schedules & job costing, and
download the generated PDF/Excel.
---
## Configuration
Each project is a folder under `projects/<slug>/` with a `project_config.json` that drives
everything (no hardcoded project data). Key fields:
| Field | Purpose |
|-------|---------|
| `project_id`, `project_name`, title-block metadata | Identity / drawing headers |
| `unit_plan_pdfs` | Map of unit code → architect PDF path |
| `floor_plan_pdfs`, `unit_counts` | Unit quantities across the building |
| `ada_units` | Which unit types are ADA |
| `price_list_path`, `price_list_tier`, `eur_usd_rate` | Vendor pricing inputs |
| `gp_target_pct`, `commission_pct`, `bond_pct` | Job-costing margins |
| `appliances_regular`, `appliances_ada` | Appliance schedule |
Global defaults and API keys load from `.env` via `core/config.py` — copy `.env.example`
to `.env` and set `OPENROUTER_API_KEY`.
---
@@ -46,48 +101,57 @@ Architect PDF → PyMuPDF → Text + Geometry Extraction
| Layer | Tool | Purpose |
|-------|------|---------|
| PDF Reading | PyMuPDF (fitz) | Extract text, geometry, render images |
| PDF Writing | ReportLab | Generate shop drawing PDFs |
| Excel Output | openpyxl | Generate matrix + pricing spreadsheets |
| AI Vision | Claude 3.5 Sonnet / GPT-4o | Classify cabinets from elevation images |
| Orchestration | Python | Pipeline runner |
| PDF reading | PyMuPDF (fitz) | Extract text, geometry, render crops |
| AI vision | Gemini 2.5 Flash / Pro via OpenRouter | Classify cabinets & extract intent |
| PDF writing | ReportLab | 17"×11" LEDGER shop-drawing PDF |
| CAD | ezdxf (+ matplotlib) | AutoCAD DXF plan/elevation views |
| Excel | openpyxl | Estimation workbook |
| Geometry | Shapely | Placement / constraint geometry |
| Web | FastAPI + Uvicorn | Dashboard & SSE pipeline runner |
---
## Project Understanding
## Repository Layout
See `_Project_Understanding/` folder:
- `01_Client_Understanding_Detailed.md` — Full client requirements
- `02_Simple_Summary_Input_Flow_Output.md` — 5-step workflow summary
- `03_Extraction_Deep_Dive_Research.md` — Technical research on extraction pipeline
---
## 5-Step Client Workflow
1. **Read elevations** → Identify every cabinet (type, W×H×D)
2. **Generate shop drawings** → Per unit type PDF (ItalianKB style)
3. **Build project matrix** → Count units per floor × cabinet totals
4. **Price materials** → Match to vendor price list (Euros → USD, mm → inches)
5. **Job costing** → Apply tax/freight/install/GP% → Final selling price
```
Albert_Project/
├── pipeline.py # Master orchestrator (start here)
├── core/ # Extraction, AI, validation, costing
│ ├── ai_vision_classifier.py # OpenRouter Gemini vision classifier
│ ├── pdf_extractor.py # PyMuPDF primitives
│ ├── region_detector.py, drawing_classifier.py, dimension_parser.py
│ ├── cabinet_validator.py, confidence_engine.py
│ ├── price_matcher.py, job_costing.py
│ ├── bimlite/ # Lightweight BIM object model + rules
│ └── engines/ # Constraint solver, placement, fingerprint,
│ # renderers, ADA, BOM, sheet composition
├── generators/ # shop_drawing_pdf, shop_drawing_dxf, cabinet_excel
├── data/ # cabinet_library.json + layout signatures
├── projects/ # Per-project config + drawings
├── web_app/ # FastAPI backend + static dashboard
└── outputs/ # Generated deliverables (git-ignored)
```
---
## Status
- [x] PyMuPDF extraction pipeline working
- [x] Region detection (Kitchen/Bath/Elevation)
- [x] 400 DPI crop images generated
- [x] Shop drawing PDF generator (Casa Familia + Heritage)
- [x] Excel generator (Heritage Village)
- [ ] Claude Vision API integration (Step 1B)
- [ ] Automated cabinet schedule JSON → PDF pipeline
- [ ] Project matrix builder from floor plans
- [x] PyMuPDF extraction + page/region classification
- [x] OpenRouter Gemini vision classification (schedules + architectural intent)
- [x] Validation + confidence QA
- [x] Price matching (EUR → USD) + job costing
- [x] Shop drawing PDF + DXF generators
- [x] Excel estimation + BOM CSV
- [x] Web dashboard with live SSE pipeline runner
- [ ] BIM-Lite placement engine integration (wired but not yet called with matching
signatures — currently a no-op in `--skip-ai` runs; see project notes)
- [ ] Kitchen layout signature store (`data/kitchen_signatures.json` still empty)
---
## Setup
## Project Understanding
```bash
pip install pymupdf reportlab openpyxl
```
See `_Project_Understanding/` for client requirements, workflow diagrams, and the
extraction research write-ups.
</content>
</invoke>
@@ -1,264 +0,0 @@
# 🏠 Albert Project — Simple Guide
### AI Cabinet Estimation & Shop Drawing Automation
---
## 🤔 What Is This Project? (In Plain English)
> **The client is a kitchen cabinet company.**
> They sell and install cabinets for apartment buildings — sometimes 50 to 100+ apartments at once.
>
> **The problem?** Figuring out which cabinets go where, how many, what they cost, and drawing the final
> design documents — all of this takes their team days to do manually.
>
> **Our job:** Build an AI system that does it **automatically in under 24 hours.**
---
## 🏗️ Real Projects We Are Working On
| Project | Location | Units | Status |
|---------|----------|-------|--------|
| **Casa Familia** | Miami, FL | 50 apartments (A1, A2-ADA, A3, B1, B2-ADA) | ✅ Files in hand |
| **Heritage Village** | (TBD) | ~70 apartments, 14 unit types | 📋 Up next |
---
## 📋 The 5 Steps — What the AI Does
```
ARCHITECT DRAWINGS ──► STEP 1 ──► STEP 2 ──► STEP 3 ──► STEP 4 ──► FINAL PDF
(PDFs) Read Count Price Cost Shop
Cabinets All Units Cabinets Calculate Drawings
```
---
### STEP 1 — Read the Drawings & List All Cabinets
**Input:** Architect's PDF drawings (floor plans + elevation views of kitchens/bathrooms)
**What it does:**
- Opens each apartment unit's drawing (e.g., Unit A1 — 1-bedroom apartment)
- Looks at the kitchen and bathroom walls (elevation views)
- Identifies every cabinet: upper wall cabinets, lower base cabinets, pantry cabinets
- Assigns each cabinet a code, size (Width × Height × Depth), and a type
**Output:** A schedule (list) of all cabinets for that unit type
```
Example for Unit A1 - Kitchen:
┌────────────────────────────────────────────────────────────┐
│ Item │ Code │ Description │ Type │ W H D │
│ 1 │ W3630 │ Wall Cabinet 36"W │ Upper │ 36" 30" 12"│
│ 2 │ B36 │ Base Cabinet 36"W │ Lower │ 36" 34" 24"│
│ 3 │ BC36 │ Corner Base Cabinet │ Lower │ 36" 34" 24"│
│ ... │ ... │ ... │ ... │ ... │
└────────────────────────────────────────────────────────────┘
```
---
### STEP 2 — Count All Units Across the Building
**Input:** Building floor plan PDFs + cabinet list from Step 1
**What it does:**
- Reads the full building plan to count how many of each unit type exist
- Multiplies cabinet counts by unit quantities
**Output:** The Project Matrix (the "big picture" table)
```
Example Matrix:
┌──────────────┬─────┬──────────────┬──────────────┬────────────┐
│ Unit Type │ Qty │ Kitchen Cabs │ Bathroom Cabs│ TOTAL Cabs │
│ A1 (1BR/FHA) │ 14 │ 8 each │ 2 each │ 140 total │
│ A2 (ADA) │ 6 │ 7 each │ 2 each │ 54 total │
│ B1 (2BR) │ 6 │ 10 each │ 4 each │ 84 total │
│ ... │ ... │ ... │ ... │ ... │
│ PROJECT TOTAL│ 50 │ --- │ --- │ 630 total │
└──────────────┴─────┴──────────────┴──────────────┴────────────┘
```
---
### STEP 3 — Price the Cabinets
**Input:** Cabinet matrix + Price list (MS PRICE LIST LEVEL 1 - 90CM.xlsx)
**What it does:**
- Matches each cabinet code to its price in the vendor catalog
- Prices are in **Euros** (we convert to USD)
- Dimensions in the price list are in **mm** (we convert from inches)
**Output:** Total material cost for all cabinets in the project
```
Example Pricing:
Base Cabinet 36"W → €142.50 per unit × 140 units = €19,950
Wall Cabinet 30"W → €98.00 per unit × 140 units = €13,720
...
TOTAL MATERIAL COST = €85,000 → ~$91,000 USD
```
---
### STEP 4 — Calculate Final Selling Price
**Input:** Total material cost + Job Costing formula
**What it adds on top of material cost:**
| Cost Item | How Calculated |
|-----------|---------------|
| 🚢 Ocean Freight | $4,500 per shipping container (~220 cabinets each) |
| 🚚 Inland Delivery | $1,200 flat fee |
| 🔧 Installation | $85 per cabinet installed |
| 📦 Warehousing | 2% of material cost |
| 🛡️ Insurance | 0.8% of material cost |
| 💰 Commission | 5% of final selling price |
| 📄 Bond | 1.5% of final selling price |
| 📈 Gross Profit | 35% of final selling price (client target) |
**Formula:**
```
Selling Price = (All Costs Above) ÷ (1 - 35% - 5% - 1.5%)
= Total Pre-Margin Costs ÷ 58.5%
```
**Output:** Final **Selling Price** with full cost breakdown
---
### STEP 5 — Generate the Shop Drawing PDF
**Input:** Cabinet data + Project info + ItalianKB template style
**What it generates:**
- A professional **17" × 11" landscape PDF** — the same format used by ItalianKB
- One page per kitchen/bathroom type
- Contains: floor plan views, elevation views (front view of each wall), dimensions
**The PDF includes:**
```
📄 Page 1: COVER SHEET
- Project name, finish selection, appliance models, general notes
📄 Page 2: MATRIX
- Table of all unit types, quantities, kitchen types, vanity types
📄 Page 3+: Per Unit Type (e.g., Kitchen Type K1 / Unit A1)
- FLOOR PLAN (top-down view with cabinet layout)
- ELEVATION A — Front view of wall A with every cabinet drawn
- ELEVATION B — Front view of wall B
- Dimensions in BOTH cm and inches
📄 Last pages: PARTS & SECTIONS
- Exploded cabinet assembly views
- Cross-sections showing inside dimensions
```
---
## 📐 The Shop Drawing — What It Looks Like
```
╔═══════════════════════════════════════════════════╦══════════════════╗
║ ║ KITCHEN TYPE K1 ║
║ ←──────────── 426.72 cm [14'] ──────────────→ ║ UNIT A1 ║
║ ←── 394.22 cm ──────────────────────────────→ ╠══════════════════╣
║ ║ ITALIAN KITCHEN ║
║ ┌──────┬──────────┬────┬───────┬─────┬──────┐ ║ AND BATH ║
║ │ X │ X │ X │ X │ X │ X │ ║ ║
║ │ UPPR │ UPPR │UPPR│ UPPR │UPPR │ UPPR│ ║─────────────────║
║ │ │ │ │ │ │ │ ║ PROJECT #: 23-033║
║ ├──────┼──────────┼────┼───────┼─────┼──────┤ ║ CASA FAMILIA ║
║ │ D/W │ BASE │BASE│ RANGE │BASE │ BASE│ ║─────────────────║
║ │ 61cm │ 90cm │30cm│ 76cm │35cm │ 90cm │ ║ DATE: 11/05/2024 ║
║ └──────┴──────────┴────┴───────┴─────┴──────┘ ║ REV: 5.0 ║
║ ↑ 228.60 cm [7'-6"] ↑ ║ DRAWN BY: A.C ║
║ ╠══════════════════╣
║ ELEVATION A SCALE 1/2"=1'-0" ║ SHEET NUMBER ║
║ CASA FAMILIA UNIT A1 / KITCHEN TYPE K1 ║ A.2 ║
╚═══════════════════════════════════════════════════╩══════════════════╝
```
---
## 📂 How the Files Are Organized
```
Albert_Project/
│
├── Casa familia/
│ ├── 01_Architectural_Drawings/ ← INPUT: PDFs from architect
│ │ ├── Floor_Plans/ ← Building layout (count units)
│ │ ├── Unit_Plans_FHA_ADA/ ← Individual unit elevations (read cabinets)
│ │ └── Sections_Details/ ← Wall sections, details
│ │
│ ├── 02_Price_List/ ← INPUT: Vendor catalog
│ │ └── MS PRICE LIST LEVEL 1 -90CM.xlsx
│ │
│ └── 03_Shop_Drawings/ ← OUTPUT (generated here)
│ ├── ITALIANKB SHOP DRAWINGS...pdf ← REFERENCE (client's example)
│ └── GENERATED_SHOP_DRAWINGS_CF.pdf← ← OUR OUTPUT
│
├── generate_italiankb_shop_drawings.py ← Main generator script
└── run_cabinet_estimation.py ← Full pipeline runner
```
---
## 🔄 How to Run It
```bash
# Run the complete pipeline (estimation + shop drawings):
python run_cabinet_estimation.py
# Run ONLY the shop drawing generator:
python generate_italiankb_shop_drawings.py
```
The output PDF appears in:
`Casa familia → 03_Shop_Drawings → GENERATED_SHOP_DRAWINGS_CF.pdf`
---
## 🎯 What Makes This Production-Grade
| Feature | Detail |
|---------|--------|
| **Exact same page size** | 17" × 11" landscape — same as ItalianKB reference |
| **Same fonts** | Helvetica (matching Arial/CenturyGothic used in original) |
| **Same scale** | 1/2" = 1'-0" → exactly 3 PDF points per real inch |
| **Dual dimensions** | Every measurement shown in **cm AND inches** (e.g., `76.20 / [2'-6"]`) |
| **Real title block** | Right-side vertical strip with company info, project info, sheet numbers |
| **Real elevation views** | Cabinets drawn to scale with door patterns and dimension lines |
| **Data-driven** | Change the input data → get a different correctly-formatted PDF |
---
## ⚠️ Important Things to Know
| Topic | What to Know |
|-------|-------------|
| **ADA Units** | ADA (wheelchair accessible) units have LOWER countertops (34" instead of 36"). The AI handles this separately |
| **Dimensions** | Price list = millimeters in Euros. Drawings = feet/inches in USD. AI converts everything automatically |
| **Finish Tiers** | Standard 1 / 2 / 3 — different price columns. Client tells us which tier per project |
| **Containers** | Cabinets ship in containers (~220 per container). Freight cost depends on container count |
| **Not included** | Appliances, countertops, plumbing, and fixtures are **NOT** in the cabinet count |
---
## ❓ Still Needed From Client
- [ ] **Cabinet library** — Their full standard catalog (codes + specs)
- [ ] **Job costing form** — Their exact Excel formula template
- [ ] **More price lists** — Other vendor catalogs (MS Level 1 is in hand)
- [ ] **Confirm output format** — PDF only? Or also Excel?
- [ ] **Review step** — Does client want to approve before final PDF is sent?
---
*Last updated: June 2026 | Project: Casa Familia (23-033) | Status: AI Pipeline Built ✅*
@@ -1,207 +0,0 @@
# Client Understanding — AI Cabinet Estimation & Shop Drawing Service
---
## 👤 Who Is the Client?
A **kitchen & bathroom cabinet supplier/manufacturer** serving large-scale **residential construction** projects:
| Project Type | Examples |
|---|---|
| High-rise buildings | Multi-floor apartment towers |
| Mid-rise buildings | 3–5 story residential |
| Housing communities | FHA/ADA affordable housing (like Casa Familia, Heritage Village) |
**Current pain point:** Estimation + shop drawing prep is slow & manual.
**Goal:** AI-powered service with **< 24-hour turnaround** for **20–30 projects/week**.
---
## 📁 Real Projects in Hand (from provided files)
### Project 1 — Casa Familia (Atlantic Pacific Communities)
```
📁 Casa familia/
├── 01_Architectural_Drawings/
│ ├── Floor_Plans/ (13 PDFs — Bldg A & B, Ground/2nd/3rd floors)
│ ├── Unit_Plans_FHA_ADA/ (7 PDFs — Unit A1, A2-ADA, A3, B1, B2-ADA with ELEVATIONS)
│ ├── Community_Center/ (5 PDFs — kitchenette, restrooms, multipurpose)
│ └── Sections_Details/ (13 PDFs — wall sections, door/wall schedules)
├── 02_Price_List/ MS PRICE LIST LEVEL 1 - 90CM.xlsx
└── 03_Shop_Drawings/ ITALIANKB reference shop drawing PDF ← TARGET OUTPUT
```
- Unit types: **A1 (1BR/FHA), A2 (1BR/ADA), A3 (1BR/FHA), B1 (2BR/FHA), B2 (2BR/ADA)**
- **Has elevation drawings** → First project for AI trial
### Project 2 — Heritage Village
```
📁 Heritage/
├── 01_Architectural_Drawings/
│ ├── Floor_Plans/ (3 PDFs — Partial C, Ground/2nd/3rd)
│ └── Unit_Plans_FHA_ADA/ (14 PDFs — Units A1, A1A-ACC, B1, B1A-ACC, C1, C2, C2a-ACC, C3, D1, D1N, D1A-ACC, ST1, ST1A-ACC)
└── 02_Price_List/ MS PRICE LIST LEVEL 1 - 90CM.xlsx
```
- Unit types: **A1, B1, C1–C3, D1 (4BR), Studio — plus ADA variants**
- More complex — 14 unit types total
---
## 🔄 The 5-Step AI Workflow (Client's Exact Process)
### STEP 1 — Read Architectural Drawings → Generate Shop Drawings
**Input:**
- Architect PDF floor plans (unit plans with kitchen & bathroom elevations)
- Client's cabinet library (standard list with codes, specs, dimensions)
- Finish tiers: **Standard 1 / Standard 2 / Standard 3**
**AI Must Do:**
- Read elevation drawings to identify each cabinet position in kitchen & bathroom
- Match each position to the correct cabinet from the standard library
- Assign cabinet code, description, W×H×D dimensions, finish tier, elevation reference
- Produce a **Shop Drawing Schedule** per unit type (like the ItalianKB PDF reference)
**Output per unit type:**
- Itemized cabinet list: Item #, Cabinet Code, Description, Type (Upper/Lower/Tall/Vanity), Width, Height, Depth, Qty, Finish Tier, Elevation Ref, Location Note
- Section subtotals: Kitchen Upper count, Lower count, Tall count → Kitchen Total
- Section subtotals: Master Bath count, Bath 2 count → Bath Total
- **Unit Grand Total** cabinet count
> **Reference:** `03_Shop_Drawings/ITALIANKB SHOP DRAWINGS - 23-033 CASA FAMILIA.pdf`
> The client will send this as the style/format example for AI to follow.
---
### STEP 2 — Build Project Matrix from Drawings
**Input:**
- All unit plan PDFs for a project
- Shop drawings (from Step 1) — cabinet counts per unit type
**AI Must Do:**
- Read building floor plans to count **how many of each unit type** exist per floor and total
- Build the **Project Cabinet Matrix**:
| Unit Type | Description | Qty in Project | Kitchen Upper | Kitchen Lower | Kitchen Tall | Kitchen Total | Bath Cabinets | Unit Total | Project Kitchen Total | Project Bath Total |
|---|---|---|---|---|---|---|---|---|---|---|
| A1 | 1BR/FHA | 14 | 3 | 5 | 0 | 8 | 2 | 10 | 112 | 28 |
| A2 | 1BR/ADA | 6 | 3 | 4 | 0 | 7 | 2 | 9 | 42 | 12 |
| ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
- Produce **PROJECT TOTALS**: Grand total kitchen cabinets + bath cabinets for the entire building
---
### STEP 3 — Price the Material (Cabinet Cost)
**Input:**
- Project Cabinet Matrix (from Step 2)
- Vendor Price List catalog (client specifies which one, e.g., "MS Level 1 - 90CM")
**Price List Structure (actual file):**
- Prices are in **Euros**, dimensions in **mm** (metric — 90CM = 900mm depth standard)
- Cabinet types in price list:
- Base Cabinet 1 Door (150mm–610mm wide)
- Base Cabinet 2 Doors (762mm–1200mm wide)
- Sink Base 1 Door / 2 Doors
- Base 1 Door 1 Drawer / 2 Door 1 Drawer / 3 Drawers
- Tall Wall Cabinet 1/2 Doors
- Medium Wall Cabinet 1/2 Doors
- Short Wall Cabinet 1/2 Doors
- Tall Pantry 1/2 Doors
- Fillers, Panels (base, pantry, wall)
**AI Must Do:**
- Match each cabinet from shop drawing to correct line in price list (by type + width)
- Calculate unit material cost per cabinet type
- Multiply by quantities from the matrix
- Produce **Total Material Cost** for the entire project
---
### STEP 4 — Job Costing → Selling Price
**Input:**
- Total Material Cost (from Step 3)
- Job Costing Form (client will provide — formula-based)
- Desired Gross Profit % (client sets this)
**Cost Build-Up (from actual job costing file):**
| # | Cost Item | Basis | Rate |
|---|---|---|---|
| 1 | Material Cost | From price list | Input |
| 2 | Local Use Tax | % of Material | 7.5% |
| 3 | Ocean Freight / Shipping | Per container | $4,500/container |
| 4 | Inland Delivery | Fixed per project | $1,200 |
| 5 | Installation | Per cabinet installed | $85/cabinet |
| 6 | Warehousing | % of Material | 2% |
| 7 | Material Protection | % of Material | 0.5% |
| 8 | Insurance | % of Material | 0.8% |
| 9 | Miscellaneous Allowance | Fixed | $500 |
| 10 | Commission | % of Selling Price | 5% |
| 11 | Bond | % of Selling Price | 1.5% |
| 12 | Gross Profit | % of Selling Price | 35% (target) |
> **Container sizing:** ~220 cabinets per container
> **Selling Price** is auto-calculated: `Pre-Margin Cost ÷ (1 − GP% − Commission% − Bond%)`
**Output:** Final **Selling Price** for the entire project, with full cost breakdown verification
---
### STEP 5 — Repeat (Same Pattern, Different Projects)
- Same workflow applied to every new project
- Only variables that change: **architectural drawings**, **cabinet price list**, **GP% target**
- AI learns the client's style after the trial projects
---
## 📚 Reference Files Mapping
| What Client Sends | File Reference in Folder |
|---|---|
| Architectural drawings (with elevations) | `Unit_Plans_FHA_ADA/*.pdf` |
| Example shop drawing (style guide) | `Casa familia/03_Shop_Drawings/ITALIANKB...pdf` |
| Cabinet library (standard list) | To be provided by client |
| Vendor price list | `02_Price_List/MS PRICE LIST LEVEL 1 -90CM.xlsx` |
| Job costing form | To be provided by client |
---
## ⚠️ Key Technical Details Observed
| Detail | Finding |
|---|---|
| **Dimensions** | Price list uses **mm** (metric). Architectural drawings use **imperial** (inches/feet). Conversion needed. |
| **Prices** | Price list is in **Euros**. Final job costing appears to be in **USD**. Currency conversion needed. |
| **FHA/ADA** | ADA units have lower countertops (34" max instead of 36"), affects base cabinet specs |
| **Finish Tiers** | Standard 1 / 2 / 3 map to different price columns — client will specify per project |
| **Multiple unit types** | Heritage has 14 unit types; AI must handle per-type shop drawings then aggregate |
| **Trial approach** | Client starts with **elevation drawings first** (Casa Familia unit plans), before moving to plans without elevations |
---
## 🗂️ What Client Will Send (Trial Phase)
Per their message, client's 2 team members will provide:
1. ✅ **Architectural drawings** with elevations — first project (Casa Familia in hand)
2. ⬜ **Cabinet library** — their full standard catalog (to be received)
3. ⬜ **Vendor price list catalogs** — labeled (MS Level 1 already in hand, more coming)
4. ✅ **Example shop drawings** — ItalianKB PDF (already in hand as style reference)
5. ⬜ **Job costing form** — formula-based Excel (to be received)
---
## ❓ Open Questions to Clarify
1. **Output format** — Should shop drawings be delivered as Excel, PDF, or both? (ItalianKB reference is a PDF)
2. **Cabinet library** — When will this be sent? Is it the same as the MS 90CM price list or a separate spec sheet?
3. **Currency/Units** — Price list is in Euros & mm. Should final outputs be in USD & inches?
4. **Elevations vs. no elevations** — After the trial, how should AI handle floor plans WITHOUT elevations? Use standard/assumed layouts?
5. **Multiple price tiers** — Will they ever mix Standard 1 + Standard 2 in the same project?
6. **Container calc** — Is 220 cabinets/container a fixed rule or does it vary by cabinet size?
7. **Delivery timeline** — Is < 24 hours measured from when AI receives files to when output is delivered?
8. **Review step** — Does the client want to review/approve shop drawings before job costing runs?
@@ -1,232 +0,0 @@
# 🔍 How the System Analyzes Input Drawings
## Step-by-Step Technical Explanation — Using Real Unit A1 as Example
---
## 📄 What's Inside One Input PDF (Unit A1 — `A-6.00`)
This single PDF has **7 different drawings on 1 page**:
```
┌─────────────────────────────────────────────────────────────────┐
│ 1. UNIT A1 TYP. FLOOR PLAN │ 2. UNIT A1 TYP. RCP │
│ Scale: 1/4"=1'-0" │ Scale: 1/4"=1'-0" │
│ (whole apartment, top view) │ (ceiling plan) │
├─────────────────────────────────┼───────────────────────────────┤
│ 3. UNIT A1 CORNER CONDITION │ 4. UNIT A1 CORNER RCP │
│ FLOOR PLAN │ │
│ (alternate layout version) │ │
├─────────────────────────────────┼───────────────────────────────┤
│ 5. UNIT A1 KITCHEN PLAN ←KEY │ 6. UNIT A1 KITCHEN EL. A ←KEY│
│ Scale: 1/2"=1'-0" │ Scale: 1/2"=1'-0" │
│ (top-down kitchen view) │ (front view of wall A) │
│ ├───────────────────────────────┤
│ │ 7. UNIT A1 KITCHEN EL. 2 ←KEY│
│ │ (front view of wall B) │
└─────────────────────────────────┴───────────────────────────────┘
```
> ✅ **Only drawings 5, 6, and 7 matter for cabinet extraction.**
> The others (floor plan, RCP, ceiling) are NOT used for cabinet data.
---
## 🤖 The 4-Stage AI Analysis Process
---
### STAGE 1 — Open the PDF & Locate the Kitchen Views
**What the system does:**
1. Opens the PDF using `PyMuPDF` (fitz library)
2. Scans all text on the page
3. Finds labels like `"UNIT A1 KITCHEN EL."` and `"UNIT A1 KITCHEN PLAN"`
4. Records the **position** (x, y coordinates) of those labels
5. Defines a bounding box around each view
```python
# The system finds text like this in the PDF:
"UNIT A1 KITCHEN PLAN" → at position x=856, y=1523
"UNIT A1 KITCHEN EL." → at position x=1338, y=1628
"SCALE: 1/2\" = 1'-0\"" → at position x=855, y=1554
```
**Why this works:**
Every architect drawing has a label below each view. The system reads those labels to find where each view is on the page.
---
### STAGE 2 — Extract Cabinet Data from the Elevation View
This is the **most important stage** — reading the kitchen elevation drawing (the front wall view).
**What the system sees in the elevation view:**
```
←──────── 14'-0" TOTAL ────────→
┌────┬──────────┬────┬──────┬──────┐ ← UPPER CABINETS (wall cabinets)
│ 24"│ 36" │ │ 30" │ 36" │
│ │ │ │ │ │
└────┴──────────┴────┴──────┴──────┘
┌────┬──────────┬────┬──────┬──────┐ ← BASE CABINETS (lower cabinets)
│ DW │ 36" │ │RANGE │ 36" │
│ │ │ │ │ │
└────┴──────────┴────┴──────┴──────┘
24" 36" 30" 36"
[2'] [3'] [2'6"] [3']
```
**The AI extracts 3 things from this view:**
#### A) Dimension Numbers (width of each cabinet)
```
The text in the elevation drawing includes:
"2' - 0"" → 24 inches = 61 cm → Dishwasher / small base
"3' - 0"" → 36 inches = 91 cm → Standard base cabinet
"2' - 6"" → 30 inches = 76 cm → Range slot
"7' - 6"" → 90 inches = 228 cm → Total wall height
```
#### B) Labels / Annotations
```
"DW" → Dishwasher position
"RANGE" → Range/oven position
"REF." → Refrigerator position
"SINK" → Sink location
"MICROWAVE" → Microwave position
"D/W TYPE HANDLES (TYP. ALL CABINETS)" → Door style
"UPPER CABINETS" → These are wall cabinets
"BACKSPLASH W/ CERAMIC TILE FINISH"
"CABINET OVER REF. TO BE 24" DEPTH"
```
#### C) Drawing Paths (the actual lines of the cabinet boxes)
```
Each rectangle drawn in the PDF = one cabinet box
The system reads these as vector paths:
Rectangle at x:540→630, y:252→331 → Width=90pts = 76cm cabinet
Rectangle at x:630→720, y:252→331 → Width=90pts = 76cm cabinet
etc.
```
---
### STAGE 3 — Match Cabinets to Cabinet Library Codes
After extracting dimensions, the system matches each extracted cabinet to the standard catalog.
```
EXTRACTED from drawing: MATCHED to cabinet code:
Width=36", Type=Base → B36 (Base Cabinet 36"W × 34.5"H × 24"D)
Width=36", Type=Upper → W3630 (Wall Cabinet 36"W × 30"H × 12"D)
Width=24", Type=Upper → W2430 (Wall Cabinet 24"W × 30"H × 12"D)
Width=24", Dishwasher slot → [DW space — no cabinet code, appliance]
Width=30", Type=Base → B30 (Base Cabinet 30"W × 34.5"H × 24"D)
Corner cabinet → BC36 (Corner Base with lazy susan)
```
**Matching rules:**
- Width within ±0.5" tolerance (for slight variations)
- ADA units → different height specs (34" max countertop)
- Appliance spaces → no cabinet code, just marked as "appliance space"
---
### STAGE 4 — Build the Output Data Structure
After matching all cabinets, the system creates a structured record:
```
UNIT A1 — KITCHEN TYPE K1
─────────────────────────
ELEVATION A (Wall A — 14' wide)
Item 1: W3630 | Upper Cabinet 36"W | Upper | 36"×30"×12" | Elev.A | Left of range
Item 2: W3630 | Upper Cabinet 36"W | Upper | 36"×30"×12" | Elev.A | Right of range
Item 3: W2430 | Corner Wall Cab 24" | Upper | 24"×30"×12" | Elev.A | Blind corner
Item 4: B36 | Base Cabinet 36"W | Lower | 36"×34"×24" | Elev.A | Standard base
Item 5: B36 | Base Cabinet 36"W | Lower | 36"×34"×24" | Elev.A | Standard base
Item 6: BC36 | Corner Base Cab | Lower | 36"×34"×24" | Elev.A | Corner
[DW] --- | Dishwasher space | Appl | 24"wide | Elev.A | At left end
ELEVATION B (Wall B — 7'10" wide)
Item 7: W3630 | Upper Cabinet 36"W | Upper | 36"×30"×12" | Elev.B | Right of fridge
Item 8: W3618 | Over-Fridge Cabinet | Upper | 36"×18"×12" | Elev.B | Over refrigerator
Item 9: B30 | Base Cabinet 30"W | Lower | 30"×34"×24" | Elev.B | Standard base
[REF] --- | Refrigerator space | Appl | 28" wide | Elev.B | Right end
KITCHEN TOTALS FOR UNIT A1:
Upper Cabinets: 3 pieces
Base Cabinets: 5 pieces
Tall/Pantry: 0 pieces
Kitchen Total: 8 cabinets per unit
```
---
## 🔁 This Repeats for Every Unit Type
The system runs this same 4-stage process for each of the 7 input PDFs:
| PDF File | Unit | Process | Output |
| -------- | ------------- | ------------------------------- | ------------------------------------- |
| A-6.00 | Unit A1 | Read elevations → extract cabs | 8 kitchen + 2 bath = 10 cabinets/unit |
| A-6.01 | Unit A2 (ADA) | Same process, ADA heights | 7 kitchen + 2 bath = 9 cabinets/unit |
| A-6.02 | Unit A3 | Same process | ~8 cabinets/unit |
| A-6.03 | Unit B1 (2BR) | Same process + 2nd bathroom | ~14 cabinets/unit |
| A-6.04 | Unit B2 (ADA) | Same process, ADA specs | ~12 cabinets/unit |
---
## 📊 Then the Data Flows Into the Output
```
77 Unit PDFs analyzed
│
▼
Cabinet data per unit type
│
▼ Multiply by unit count (from floor plans)
│ A1: 8 cabs × 14 units = 112 kitchen cabs
│ A2: 7 cabs × 6 units = 42 kitchen cabs
│ ...
│
▼ Match to price list
│ B36 = €142.50/unit → total cost calculated
│
▼ Job costing formula → Selling Price
│
▼ PDF GENERATOR
┌──────────────────────────────────────────┐
│ Shop Drawing PDF — matching ItalianKB │
│ Page 1: Cover (finish, appliances) │
│ Page 2: Matrix (all unit types table) │
│ Page 3: Unit A1 Floor Plan │
│ Page 4: Unit A1 Elevation A + B │
│ Page 5: Unit A1 Bathroom Floor Plan │
│ Page 6: Unit A2 (ADA) Elevations │
│ ... │
└──────────────────────────────────────────┘
```
---
## ⚡ The Key Insight
> The architect's elevation drawings already have all the information.
> The AI just **reads the text labels** (dimensions + cabinet names)
> and **reads the rectangle paths** (actual cabinet box locations).
>
> It's like a human reading the same drawing —
> except the AI reads the raw data underneath (text coordinates + vector paths)
> instead of just looking at the picture.
---
*Document: How the System Analyzes Input Drawings | Casa Familia Project*
@@ -1,120 +0,0 @@
# AI Cabinet Estimation System — Simple Summary
![AI Cabinet Workflow](file:///C:/Users/prajw/.gemini/antigravity-ide/brain/ac98622d-6bdc-4220-841e-f47c9833e9be/ai_cabinet_workflow_1781689295034.png)
---
## 📥 INPUTS — What Goes In
| # | Input | Format | Example (from files) |
|---|---|---|---|
| 1 | **Architectural Floor Plans** | PDF | `A-6.00-FHA-UNIT-A1-FLOOR-PLAN.pdf` — shows kitchen layout + elevations |
| 2 | **Cabinet Library** | Excel/PDF | Standard list: cabinet codes, sizes (W×H×D), door style, finish tier |
| 3 | **Vendor Price List** | Excel | `MS PRICE LIST LEVEL 1 - 90CM.xlsx` — 107 cabinet types, price in Euros, dims in mm |
| 4 | **Job Costing Form** | Excel | Formula-based form with tax, freight, install, GP% |
> **First trial input:** Casa Familia — Unit plans A1, A2(ADA), A3, B1, B2(ADA) — all have elevation drawings ✅
---
## 🔄 FLOW — What AI Does (5 Steps)
```
STEP 1 STEP 2 STEP 3 STEP 4 STEP 5
───────────── ────────────── ───────────── ────────────── ────────────
Read the PDF → Make Shop → Count How → Match Cabinets → Calculate
floor plan + Drawing for Many Units to Price List Full Job
elevations each unit type in building → Material Cost Cost + Quote
───────────── ────────────── ───────────── ────────────── ────────────
```
### Step 1 — Read Elevations → Identify Every Cabinet
- AI reads each unit's kitchen & bathroom elevation drawings
- Identifies position, size, and type of every cabinet
- Matches to standard cabinet library (Upper / Lower / Tall / Vanity)
- Real example from ItalianKB PDF:
- Kitchen Elevation A: REF panel + 3 upper wall cabs + base cabs
- Kitchen Elevation B: Sink base + DW adjacent + upper run
- Vanity: 45cm + 45cm double vanity + 110cm mirror
### Step 2 — Generate Shop Drawings (per unit type)
- AI creates a shop drawing for each unit (A1, A2-ADA, B1, etc.)
- Each shop drawing contains:
- **Floor plan view** — cabinet layout at scale
- **Elevation views** — A, B (wall-by-wall cabinet positions with dimensions in cm & inches)
- **Cabinet schedule table** — Item #, Code, Description, W×H×D, Qty, Finish
- Output format: matches the **ItalianKB PDF style** (23 pages for Casa Familia)
- Real dimensions from ItalianKB: shown in both **mm/cm AND inches** side by side
### Step 3 — Build Project Matrix
- AI reads building floor plans to count units per type
- Builds summary table:
| Unit | Count | Kitchen Cabs | Bath Cabs | Unit Total | Project Total |
|------|-------|-------------|-----------|------------|---------------|
| A1 (1BR) | 14 | 8 | 2 | 10 | 140 |
| A2-ADA (1BR) | 6 | 7 | 2 | 9 | 54 |
| B1 (2BR) | 12 | 10 | 3 | 13 | 156 |
| ... | ... | ... | ... | ... | ... |
| **TOTAL** | **50** | | | | **~500 cabs** |
### Step 4 — Price Match → Material Cost
- Each cabinet from matrix → matched to vendor price list by type + width
- Price list has 107 lines: Base cabs, Sink bases, Drawers, Wall cabs, Pantries, Panels, Fillers
- All priced in **Euros**, dimensions in **mm** (90cm depth standard)
- AI calculates: `Qty × Unit Price = Line Total` → **Grand Material Cost**
### Step 5 — Job Costing → Final Selling Price
Starting from Material Cost, AI applies:
| Cost Item | How Calculated |
|-----------|---------------|
| Local Use Tax | 7.5% × Material |
| Ocean Freight | $4,500 × containers (÷220 cabs per container) |
| Inland Delivery | Fixed $1,200 |
| Installation | $85 × total cabinet count |
| Warehousing | 2% × Material |
| Protection | 0.5% × Material |
| Insurance | 0.8% × Material |
| Misc Allowance | Fixed $500 |
| Commission | 5% of Selling Price |
| Bond | 1.5% of Selling Price |
| **Gross Profit** | **35% of Selling Price (client sets this)** |
**Formula:** `Selling Price = Pre-Margin Cost ÷ (1 − 35% − 5% − 1.5%)`
---
## 📤 OUTPUTS — What Comes Out
| # | Output | Format | Contents |
|---|---|---|---|
| 1 | **Shop Drawings** | PDF (like ItalianKB) | Per unit: floor plan view + elevation views + dimensions in cm & inches |
| 2 | **Project Matrix** | Excel / table | All unit types × counts × cabinet totals for whole building |
| 3 | **Material Cost Report** | Excel | Cabinet-by-cabinet pricing with vendor price list applied |
| 4 | **Final Project Quote** | Excel | Full job cost breakdown + **Selling Price with GP%** |
---
## ⏱️ Timeline Goal
**All 4 outputs delivered in < 24 hours** per project, for up to **20–30 projects/week**
---
## 🔑 Key Facts from Files
| Fact | Detail |
|------|--------|
| Shop drawing style | ItalianKB PDF — 23 pages for Casa Familia (5 unit types) |
| Dimensions shown | Both **metric (cm/mm) AND imperial (feet/inches)** on same drawing |
| Finish shown | `K019 Silver Liberty Elm` — cabinet finish label |
| ADA difference | Lower countertop, ADA dishwasher/range, accessible base cabinet |
| Price list unit | Euros + mm (AI must convert to USD + inches for US projects) |
| Trial project | Casa Familia first → 5 unit types with elevations ready |
---
## ✅ What's Still Needed from Client
- [ ] Cabinet library / standard spec list
- [ ] Job costing form (Excel template)
- [ ] More vendor price catalogs (labeled)
@@ -1,557 +0,0 @@
# Deep-Dive Research: Architectural Drawing Extraction
## How to Accurately Read Input PDFs for Cabinet Estimation AI
**Research Type:** Principal Solution Architect + Technical Research Consultant
**Scope:** Tool comparison, pipeline design, accuracy benchmarks, existing project analysis
**Based on:** Real project files (Casa Familia + Heritage Village PDFs) + Industry research
---
## 1. FIRST: Understand Your Actual PDFs
Before choosing any tool, we must understand **what type of PDFs** we are dealing with.
Analysis of the actual project files reveals:
| PDF Category | Files | Type | Characteristics |
|---|---|---|---|
| Unit elevation plans | `A-6.00` through `A-6.11` (21 files) | **Born-digital vector PDF** | CAD-exported; contains vector lines, paths, embedded text strings |
| Building floor plans | `A-2.00` through `A-2.08` (13 files) | **Born-digital vector PDF** | Large format, 900KB–1.9MB, dense linework |
| ItalianKB shop drawings | Reference PDF (23 pages) | **Born-digital vector PDF** | Dual-unit dimensions (mm+inches), elevation views, cross-sections |
| Wall sections/details | `A-4.04`, `A-4.05` etc. | **Born-digital vector PDF** | Structural detail, not needed for cabinet extraction |
**Critical Finding:** All project PDFs are **born-digital vector files** (CAD-exported), NOT scanned rasters.
This changes the entire extraction strategy — vector extraction is possible and far superior to OCR/Vision for these files.
### What "Born-Digital Vector" Means for Our Pipeline
```
Inside a vector PDF, every element is stored as:
- Text strings with exact coordinates: "36W x 30H" at position (x=234.5, y=445.2)
- Line paths: START(x1,y1) → END(x2,y2) with stroke width
- Rectangle blocks: (x, y, width, height)
- Dimension strings tied to specific line endpoints
PyMuPDF can extract ALL of this directly — no AI needed for text extraction.
AI Vision is only needed to INTERPRET the spatial relationships.
```
---
## 2. THE 5-LAYER EXTRACTION PIPELINE
Based on research, the winning approach is NOT a single tool — it is **5 layers working together**:
```
┌─────────────────────────────────────────────────────────────────┐
│ LAYER 1: PDF Rendering │
│ Tool: PyMuPDF (fitz) │
│ Action: Render each page at 300 DPI → PNG image │
│ Also: Extract all embedded text with exact (x,y) coordinates │
│ Output: High-res PNG + text coordinate map │
└──────────────────────────────┬──────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ LAYER 2: Region Detection & Segmentation │
│ Tool: PyMuPDF get_drawings() + rule-based region finder │
│ Action: Identify which parts of the page are: │
│ - Title block (bottom right — project info) │
│ - Floor plan view (top left area) │
│ - Elevation A view (labeled "ELEVATION A") │
│ - Elevation B view (labeled "ELEVATION B") │
│ - Notes/keynotes section │
│ Output: Cropped image regions per section │
└──────────────────────────────┬──────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ LAYER 3: Dimension Text Extraction (Vector-Native) │
│ Tool: PyMuPDF get_text("dict") + Shapely │
│ Action: Extract all text strings + their bounding boxes │
│ Find all dimension strings: numbers like "36", "30", "24", │
│ fractions like "3/4", imperial like "2'-6\"", metric "76.20" │
│ Associate each dimension with its nearest line/rectangle │
│ Output: Structured dimension-to-element mapping │
└──────────────────────────────┬──────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ LAYER 4: AI Vision — Spatial Reasoning & Cabinet Classification │
│ Tool: Claude 3.5 Sonnet (PRIMARY) / GPT-4o (BACKUP) │
│ Action: Feed cropped elevation image + extracted text map │
│ AI's job: NOT to read dimensions (Layer 3 did that) │
│ AI's job: Interpret spatial layout: │
│ - "This rectangle at position X is an upper cabinet" │
│ - "The rectangle next to the DW symbol is a sink base" │
│ - "This is ADA unit — countertop line is at 34\" not 36\"" │
│ Output: Structured JSON cabinet list with position + type │
└──────────────────────────────┬──────────────────────────────────┘
↓
┌─────────────────────────────────────────────────────────────────┐
│ LAYER 5: Validation & Confidence Scoring │
│ Tool: Rule-based Python validator │
│ Action: Sanity checks: │
│ - Cabinet widths must be standard sizes (±5mm tolerance) │
│ - Base cabinet height must be 720mm (or 864mm ADA) │
│ - Total run length must match room dimension in drawing │
│ - Cabinet count must match elevation label count │
│ Output: Confidence score per extraction + flagged anomalies │
└──────────────────────────────┬──────────────────────────────────┘
↓
Human Review (flagged items only)
```
---
## 3. TOOL-BY-TOOL COMPARISON
### Layer 1–2: PDF Processing
| Tool | Accuracy on Vector PDF | Speed | Cost | Verdict |
|------|----------------------|-------|------|---------|
| **PyMuPDF (fitz)** | ✅ 99.9% — exact coordinate extraction | ~0.1 sec/page | Free/Open Source | **WINNER** |
| pdf2image (Poppler) | ✅ Same accuracy, image only | ~0.5 sec/page | Free | Good backup |
| Adobe PDF API | ✅ Enterprise grade | ~2 sec/page | $0.05/page | Overkill |
| pdfplumber | ✅ 95% (good for tables) | ~0.3 sec/page | Free | Use for table extraction |
**Winner: PyMuPDF** — fastest, handles vector geometry natively, extracts both text and drawings.
---
### Layer 3: Dimension Extraction from Vector PDF
| Approach | Accuracy | Method |
|----------|---------|--------|
| **PyMuPDF `get_text("dict")`** | ✅ ~99% on digital PDFs | Returns every text character with (x,y) bounding box |
| **PyMuPDF `get_drawings()`** | ✅ ~99% on digital PDFs | Returns every line/rect as mathematical coordinates |
| **Azure Document Intelligence** | ⚠️ ~85% | Good for tables/forms, poor spatial association |
| **AWS Textract** | ⚠️ ~80% | Same limitation — no spatial reasoning |
| **Tesseract OCR** | ❌ ~60–70% on drawings | Raster only; struggles with rotated/small text |
| **GPT-4o Vision** | ⚠️ ~75% (hallucination risk) | Good at reading text but may miss or confuse dimensions |
**Winner: PyMuPDF native extraction** — no AI needed here. AI is expensive and error-prone for what Python can do exactly.
> **Key Insight from Research:** Azure/AWS are built for business documents (invoices, forms). They have NO special understanding of dimension lines, elevation labels, or architectural symbols. Using them adds cost + errors for zero benefit on vector PDFs.
---
### Layer 4: Spatial Reasoning — AI Vision Model Comparison
This is where AI is truly needed. Comparison based on research + technical drawing benchmarks:
| Model | Spatial Reasoning | Structured JSON Output | Hallucination Rate | Cost/1K tokens | Verdict |
|-------|-----------------|----------------------|-------------------|---------------|---------|
| **Claude 3.5 Sonnet** | ✅ Best | ✅ Excellent | 🟢 Lowest | $3/$15 | **PRIMARY CHOICE** |
| **GPT-4o** | ✅ Very Good | ✅ Very Good | 🟡 Moderate | $5/$15 | **BACKUP / VALIDATOR** |
| **Gemini 1.5 Pro** | ✅ Good | ✅ Good | 🟡 Moderate | $3.5/$10.5 | Good alt, long context |
| **LLaVA / Qwen-VL** | ⚠️ Fair | ⚠️ Fair | 🔴 Higher | Free (self-host) | Phase 3 only |
| **Azure Document Intelligence** | ❌ Poor | ❌ N/A | — | $0.01/page | Wrong tool |
| **YOLO (custom trained)** | ✅ Best (for detection only) | ⚠️ No context | 🟢 None | Free | For Phase 2 |
#### Why Claude 3.5 Sonnet Wins for This Task
1. **Instruction Following:** Claude follows complex structured prompts better — critical for getting consistent JSON output matching our cabinet schema
2. **Spatial Reasoning:** Better at understanding "this cabinet is LEFT of the range" vs "RIGHT of the sink"
3. **Hallucination Rate:** Claude is less likely to invent cabinet counts or swap dimensions
4. **Code Generation:** If we need Claude to help generate the drawing code, it's strongest there too
#### Why We Also Use GPT-4o
- Use as **validator**: Feed same elevation to both → compare outputs → flag discrepancies
- Cross-model validation catches ~90% of hallucinations
- Cost justified for construction-grade accuracy requirements
---
### Specialized Construction Tools vs. Custom Pipeline
| Tool | What It Does | Fit for Our Use Case | Cost | Decision |
|------|-------------|---------------------|------|---------|
| **Togal.AI** | Automated takeoff — counts areas, elements from floor plans | ⚠️ Partial — counts rooms/elements, NOT cabinet-specific | $299–999/mo | Not custom enough |
| **Stru.AI** | Cross-discipline drawing review | ❌ Wrong domain — structural/MEP focus | Custom pricing | No |
| **Nomic.AI** | Drawing compliance review | ❌ Compliance-focused, not estimation | Custom pricing | No |
| **Blueprints.ai** | Architectural AI extraction | ⚠️ Generic — needs cabinet-specific training | Unknown | Evaluate |
| **Custom Pipeline** | Built exactly for our needs | ✅ Perfect fit, full control | Dev cost only | **YES** |
**Conclusion:** No off-the-shelf tool handles the specific task of reading kitchen/bathroom elevation drawings and outputting a cabinet schedule. **Custom pipeline is the right call.**
---
## 4. HOW THE EXTRACTION WORKS IN PRACTICE
### Step-by-Step on a Real Drawing (Casa Familia Unit A1, Elevation A)
**What the PDF contains (extracted by PyMuPDF):**
```
Text strings found at coordinates:
"ELEVATION A" at (x=120, y=45)
"76.20" at (x=230, y=82) ← dimension in cm (= 30")
"[2'-6\"]" at (x=230, y=96) ← same dim in imperial
"90.00" at (x=340, y=82) ← 90cm = 35.4"
"DISHWASHER" at (x=410, y=200)
"228.60" at (x=520, y=82) ← 228.6cm = 7'-6"
"COUNTERTOP BY OTHERS" at (x=300, y=310)
Rectangle paths found:
Rect(x=229, y=105, w=76.2, h=72.0) ← base cabinet 76cm wide
Rect(x=229, y=33, w=76.2, h=30.0) ← upper cabinet 76cm wide
Rect(x=305, y=105, w=90.0, h=72.0) ← base cabinet 90cm wide
Rect(x=395, y=33, w=30.0, h=18.0) ← microwave shelf 30cm
Rect(x=395, y=105, w=30.0, h=72.0) ← DW-adjacent base
```
**Layer 3 output (dimension mapping):**
```json
{
"elevation": "A",
"total_run_cm": 426.72,
"total_run_imperial": "14'",
"elements": [
{"rect_id": 1, "type": "inferred_upper", "x": 229, "width_cm": 76.2, "label_above": "2'-6\""},
{"rect_id": 2, "type": "inferred_upper", "x": 305, "width_cm": 90.0, "label_above": "2'-11 7/16\""},
{"rect_id": 3, "type": "inferred_upper", "x": 395, "width_cm": 30.0, "label": "MICROWAVE"},
{"rect_id": 4, "type": "inferred_base", "x": 229, "width_cm": 76.2, "height_cm": 72.0},
{"rect_id": 5, "type": "inferred_base", "x": 305, "width_cm": 90.0, "near_label": "DISHWASHER"},
{"rect_id": 6, "type": "inferred_base", "x": 395, "width_cm": 30.0}
]
}
```
**Layer 4 prompt to Claude (with cropped elevation image + above JSON):**
```
You are an expert cabinet estimator.
I have extracted the following geometry from a kitchen elevation drawing.
The drawing shows ELEVATION A of Unit A1, Casa Familia project.
Pre-extracted dimensions are in cm (metric system, 90cm depth standard).
Here is what PyMuPDF found: [JSON above]
Here is the cropped elevation image: [PNG]
For each element, identify:
1. Cabinet type: upper_wall | base | sink_base | dw_adjacent | microwave_shelf | pantry | vanity
2. Exact width in mm (convert from cm × 10)
3. Standard cabinet code from library (match to nearest standard size)
4. Special notes (ADA, sink, appliance, corner)
5. Your confidence (0.0–1.0)
Return valid JSON array only.
```
**Claude's output:**
```json
[
{"item": 1, "type": "upper_wall", "width_mm": 762, "height_mm": 300, "depth_mm": 330,
"code": "W-762x300", "location": "Left of range, Elevation A", "confidence": 0.95},
{"item": 2, "type": "upper_wall", "width_mm": 900, "height_mm": 300, "depth_mm": 330,
"code": "W-900x300", "location": "Center upper run", "confidence": 0.93},
{"item": 3, "type": "microwave_shelf", "width_mm": 300, "height_mm": 180, "depth_mm": 330,
"code": "W-MWO", "location": "Above range, microwave housing", "confidence": 0.88},
{"item": 4, "type": "base", "width_mm": 762, "height_mm": 720, "depth_mm": 610,
"code": "B-762", "location": "Left base run", "confidence": 0.96},
{"item": 5, "type": "dw_adjacent", "width_mm": 900, "height_mm": 720, "depth_mm": 610,
"code": "B-900-DW", "location": "DW adjacent base", "confidence": 0.91},
{"item": 6, "type": "base", "width_mm": 300, "height_mm": 720, "depth_mm": 610,
"code": "B-300", "location": "End base", "confidence": 0.87}
]
```
**Layer 5 validation:**
```python
# Sanity check 1: Total width matches
total_extracted = 762 + 900 + 300 = 1962mm = 196.2cm ≈ close to 205.62cm partial run ✓
# Sanity check 2: Standard base height 720mm ✓
# Sanity check 3: All widths are standard catalog sizes ✓
# → CONFIDENCE: HIGH → Auto-proceed, no human review needed
```
---
## 5. HANDLING THE DUAL UNIT SYSTEM
A critical challenge: the PDFs show **both metric (cm/mm) AND imperial (inches/feet)** simultaneously.
```
Example from ItalianKB drawing:
"76.20" (cm) with "[2'-6\"]" (feet-inches) — same dimension, two labels
"228.60" (cm) with "[7'-6\"]" (feet-inches)
"90.00" (cm) with "[2'-11 7/16\"]" (feet-inches)
```
**Solution — Dual-Parse Strategy:**
```python
def parse_dimension_pair(text_block):
"""Extract both metric and imperial, use metric as source of truth"""
import re
# Match metric: "76.20" or "76,20"
metric = re.findall(r'\b(\d+\.?\d*)\b(?=\s*\n.*\[)', text_block)
# Match imperial: [2'-6"] or [14']
imperial = re.findall(r'\[(\d+\'(?:-?\d+\s?\d*/?\d*\")?)\]', text_block)
# Cross-validate: convert imperial to cm, compare
if metric and imperial:
metric_val = float(metric[0])
imperial_cm = imperial_to_cm(imperial[0])
if abs(metric_val - imperial_cm) < 0.5: # 5mm tolerance
return {"value_mm": metric_val * 10, "confidence": "HIGH"}
else:
return {"value_mm": metric_val * 10, "confidence": "MISMATCH_FLAG"}
return {"value_mm": None, "confidence": "LOW"}
```
This cross-validation between metric and imperial values **catches PDF errors** and gives us high confidence when both agree.
---
## 6. EXISTING SIMILAR PROJECTS — WHAT WE LEARN
### Togal.AI (Most Relevant Commercial Equivalent)
- **What they do:** AI automated takeoff from architectural floor plans
- **Accuracy:** 97–98% on standard floor plan elements
- **Key technique:**
1. User sets scale → system knows real-world mm per PDF unit
2. Deep learning (YOLO-based) detects rooms, doors, windows, fixtures
3. **"Repeating Groups" feature**: Process one master unit type → apply to all identical units
4. Human reviews in visual editor before export
- **What we borrow:** The "Repeating Groups" concept is **directly applicable** — process Unit A1 once, apply to all 14 Unit A1s in the building
### CubiCasa5k Research Dataset
- 5,000 annotated floor plans with room segmentation
- Shows that YOLOv8 can achieve 95%+ mAP on standard floor plan elements
- **Lesson:** Standard elements (rooms, walls) are solvable. Cabinet-specific detection needs custom training data.
### Floor Plan Object Detection (GitHub: sanatladkat/floor-plan-object-detection)
- Uses YOLOv8 on architectural floor plans
- Achieves good results for doors/windows/rooms
- **Gap:** Does not handle elevation views or cabinet-specific detection
### Kitchen Design AI (IKEA, Roomify)
- IKEA uses computer vision to detect furniture in photos (not drawings)
- Roomify converts floor plans to 3D renders
- **Gap:** Consumer-facing, not construction-grade, not elevation-view capable
### Blueprint.ai / Blueprints-AI
- Emerging tool for construction document AI
- Human-in-loop approach matches our recommended design
- **Lesson:** Even purpose-built tools recommend human review for critical dimensions
---
## 7. WHY WE DON'T JUST USE A SINGLE AI API
Many might ask: "Why not just upload the PDF to GPT-4o and ask it to list all cabinets?"
**Here's why that fails for production:**
| Problem | Impact | Our Solution |
|---------|--------|-------------|
| GPT-4o can't see PDF natively — it sees an image | Loses vector precision, sees compressed image | PyMuPDF renders at exact 300 DPI |
| Hallucination: AI invents cabinet that doesn't exist | Wrong order = money loss | Layer 5 rule-based validation |
| Scaling: AI can't determine real-world size from image alone | Completely wrong dimensions | PyMuPDF extracts exact text dimensions |
| Context window: 23-page shop drawing = too large for one call | Missed or confused items | Process one elevation region at a time |
| Cost: Processing 20+ PDFs with Vision = expensive | Unsustainable at scale | Use Vision only for Layer 4 (spatial reasoning); everything else is code |
| No audit trail | Can't verify AI output source | Every extraction tagged with source coordinates |
---
## 8. FINAL RECOMMENDED TOOL STACK — RANKED
### Tier 1 — Core Pipeline (Must Have)
| Tool | Role | Accuracy | Cost/Month | Why |
|------|------|---------|-----------|-----|
| **PyMuPDF** | PDF rendering + vector extraction | 99.9% | Free | The foundation — extracts exact text/geometry from vector PDFs |
| **Claude 3.5 Sonnet** | Spatial reasoning + cabinet classification | ~90% | ~$50–150 | Best structured output, lowest hallucination, best instruction following |
| **Shapely** | Geometry processing (rect association) | 99% | Free | Associates dimension text with visual elements by proximity |
| **Python rule engine** | Validation + confidence scoring | 99% | Free | Sanity checks against standard cabinet sizes |
### Tier 2 — Quality Assurance (Highly Recommended)
| Tool | Role | Accuracy Boost | Cost | Why |
|------|------|--------------|------|-----|
| **GPT-4o** | Cross-validation of Claude output | +5–8% accuracy | ~$30–80 | Second opinion eliminates most hallucinations |
| **OpenCV** | Image preprocessing (deskew, contrast) | +3–5% | Free | Improves AI Vision accuracy on complex drawings |
| **Pillow + image tiling** | Region cropping before Vision AI | +10–15% | Free | Feeding a cropped elevation (not full page) dramatically improves AI accuracy |
### Tier 3 — Phase 2 (Future Enhancement)
| Tool | Role | When | Why |
|------|------|------|-----|
| **YOLOv8 (custom trained)** | Cabinet type detection | Phase 2 (after 50+ labeled drawings) | Can achieve 95%+ on detection once trained on our specific elevation drawing style |
| **Docling / Unstructured** | Pipeline orchestration | Phase 2 | Industry standard for document → AI pipelines |
| **LayoutLMv3** | Document layout understanding | Phase 3 | Microsoft's model fine-tuned for document understanding |
---
## 9. ACCURACY EXPECTATION PER STAGE
| Stage | Tool Used | Expected Accuracy | Error Type if Wrong |
|-------|-----------|------------------|-------------------|
| PDF text extraction | PyMuPDF | **99.9%** | Essentially none on vector PDFs |
| Dimension value extraction | PyMuPDF + regex | **98%** | Misparse of fraction text (e.g., "3/4") |
| Region segmentation | Rule-based | **95%** | Misidentify elevation A vs B region |
| Cabinet type classification | Claude 3.5 | **88–92%** | Corner cabs, specialty items most likely to be wrong |
| Dual-unit cross-validation | Python math | **99%** | None — if both match, it's correct |
| Cabinet count per elevation | Claude + rules | **90–95%** | May miss partially visible cab at page edge |
| **End-to-end (with human review)** | Full pipeline | **99%+** | Human catches remaining ~5% |
| **End-to-end (auto-approve >0.9)** | Auto-route | **94–96%** | ~4–6% of items go to human review |
---
## 10. PREPROCESSING STRATEGY FOR OUR SPECIFIC PDFS
Based on the actual files analyzed:
```python
import fitz # PyMuPDF
from PIL import Image
import io
def preprocess_architectural_pdf(pdf_path, unit_type):
"""
Optimal preprocessing for Casa Familia / Heritage Village style PDFs
- Born-digital vector PDFs, ~900KB–1.9MB, single page
- Dual unit dimensions (cm + imperial)
- Standard: 1/2" = 1'-0" scale notation
"""
doc = fitz.open(pdf_path)
page = doc[0] # All our PDFs are single-page
# Step 1: Extract ALL text with coordinates (vector extraction)
text_dict = page.get_text("dict")
# Step 2: Extract all geometric paths (lines, rectangles)
drawings = page.get_drawings()
# Step 3: Render at 300 DPI for Vision AI
mat = fitz.Matrix(300/72, 300/72) # 300 DPI
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
img = Image.open(io.BytesIO(pix.tobytes("png")))
# Step 4: Detect scale from title block
# "SCALE 1/2\"=1'-0\"" → 1 PDF unit = X real-world mm
scale_factor = detect_scale_from_text(text_dict)
# Step 5: Identify page regions
regions = identify_regions(text_dict, drawings)
# regions = {
# "title_block": Rect(...),
# "floor_plan": Rect(...),
# "elevation_a": Rect(...),
# "elevation_b": Rect(...)
# }
# Step 6: Crop individual elevations at 400 DPI for best AI Vision clarity
elevation_crops = {}
for region_name, rect in regions.items():
if "elevation" in region_name:
clip_mat = fitz.Matrix(400/72, 400/72)
clip_pix = page.get_pixmap(matrix=clip_mat, clip=rect)
elevation_crops[region_name] = clip_pix.tobytes("png")
return {
"text_map": text_dict,
"drawings": drawings,
"scale_factor": scale_factor,
"full_page_image": img,
"elevation_crops": elevation_crops,
"unit_type": unit_type
}
```
---
## 11. DECISION: What To Build vs. What To Buy
| Component | Build or Buy | Tool | Reasoning |
|-----------|-------------|------|-----------|
| PDF parsing | **Build** with PyMuPDF | Free | Complete control, exact accuracy |
| Region detection | **Build** rule-based | Free | PDFs follow consistent CAD layout |
| Dimension extraction | **Build** regex + math | Free | Handles dual-unit exactly |
| Spatial reasoning | **Buy** Claude API | $50–150/mo | Best-in-class, cost-justified |
| Cross-validation | **Buy** GPT-4o API | $30–80/mo | Second opinion worth the cost |
| Cabinet library RAG | **Build** with FAISS | Free | Simple embedding search |
| Drawing output | **Build** with ReportLab | Free | Exact format control |
| Takeoff software | **Skip** Togal.AI | Save $300–999/mo | Our pipeline is more specific |
| Azure Document Intelligence | **Skip** | Save $50+/mo | Wrong tool for vector PDFs |
**Total AI API cost for extraction: ~$80–230/month at 30 projects/week**
---
## 12. THE MOST ACCURATE PIPELINE — FINAL ARCHITECTURE
```
INPUT: Architectural PDF (vector, CAD-exported)
│
┌───────────────▼───────────────┐
│ PyMuPDF — 3 extractions: │ ← EXACT: no AI, no errors
│ 1. get_text("dict") │ Text + coordinates
│ 2. get_drawings() │ Lines + rectangles
│ 3. get_pixmap(300 DPI) │ Visual image
└───────────────┬───────────────┘
│
┌───────────────▼───────────────┐
│ Region Detector │ ← RULE-BASED: find elevation areas
│ "ELEVATION A" text → crop │ by text labels in coordinate space
│ "ELEVATION B" text → crop │
└───────────────┬───────────────┘
│
┌───────────────▼───────────────┐
│ Dimension Parser │ ← EXACT MATH: parse all numbers
│ Metric: regex for XX.XX │ Cross-validate metric vs imperial
│ Imperial: regex for X'-X X/" │ Flag mismatches
│ Association: nearest rect │
└───────────────┬───────────────┘
│
┌──────────▼──────────┐
│ │
┌────▼─────┐ ┌────▼─────┐
│ Claude │ │ GPT-4o │ ← TWO MODELS for validation
│ 3.5 Son. │ │ Vision │ Same cropped image + text map
│ Primary │ │ Backup │ Compare outputs
└────┬─────┘ └────┬─────┘
│ │
┌────▼─────────────────────▼─────┐
│ Output Comparator │ ← CATCH HALLUCINATIONS
│ Merge agreements → HIGH conf │ Conflicts → human review
│ Flag discrepancies → review │
└────────────────┬───────────────┘
│
┌────────────────▼───────────────┐
│ Rule Validator │ ← SANITY CHECKS
│ Standard sizes ±5mm │ Construction-grade verification
│ Total run = room width │
│ ADA height rules │
└────────────────┬───────────────┘
│
CONFIDENCE SCORE
≥ 0.90 → Auto
< 0.90 → Human Review
│
┌────────────────▼───────────────┐
│ Structured JSON Output │
│ Cabinet schedule per unit type │
│ Ready for shop drawing gen │
└────────────────────────────────┘
EXPECTED ACCURACY: 94–97% auto-approve | 99%+ with human review
PROCESSING TIME: 2–4 min per unit type
COST PER PROJECT: ~$0.80–1.50 in API calls
```
---
## Summary: Best Possible Answer
For **maximum accuracy** on these specific architectural PDFs:
1. **Do NOT use Azure/AWS/OCR** — all PDFs are vector; native extraction is 10× more accurate
2. **Do NOT send raw PDFs to Vision AI** — crop to individual elevations first
3. **Use Claude 3.5 Sonnet** as primary spatial reasoner (not GPT-4o, which is backup)
4. **Use dual-model cross-validation** — eliminates hallucinations at low cost
5. **Rule-based validation is non-negotiable** — standard cabinet sizes are known; validate always
6. **Dual-unit cross-validation** (metric vs imperial) is free accuracy boost unique to these drawings
7. **Process one elevation region at a time**, not full pages
8. **Togal.AI-style "repeating groups"** — process each unit type ONCE, multiply by count
**Confidence in this pipeline: 92%** — only unknown is whether elevation drawings in future projects maintain consistent CAD export quality. First trial with Casa Familia Unit A1 will validate.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 650 KiB

@@ -1,50 +0,0 @@
# Walkthrough — Casa Familia Cabinet Estimation & Shop Drawings
We have successfully executed the **5-Layer Architectural Drawing Extraction Pipeline** and populated all project deliverables for the **Casa Familia** cabinet trial.
---
## 🛠️ Accomplishments & Milestones
1. **Extraction Pipeline Verification & Fixes**:
- Resolved PyMuPDF coordinate scanning bugs and Unicode console encoding errors on Windows.
- Identified that the architectural PDFs use **born-digital vector graphics** (not raster scans), achieving 99.9% geometric extraction accuracy.
- Grounded the spatial coordinate mapping in drawing scale: `points = real_inches * 3.0` for a `1/2" = 1'-0"` drawing scale (exactly **3 points per real inch**).
2. **Keynote & Legend Parsing**:
- Programmatically extracted the unit keynote legend (x > 1800) mapping `U1` through `U40` to descriptions (e.g., `U1` = Refrigerator, `U9` = 12" Pantry, `U20` = Vanity Cabinet).
- Associated U-tag callouts spatially to coordinate boxes in floor plans and elevations to identify exact cabinet locations.
3. **Shop Drawings Reconstructed**:
- Reconstructed the cabinet lists for all 6 Unit Types: **A1**, **A2-FA**, **A3**, **B1**, **B2-FA**, and **B3** using exact dimension-to-scale mapping.
- Created individual sheets detailing upper/lower/tall/vanity/linen counts, dimensions, quantities, finish tiers, elevations, and location notes.
4. **Completed Excel Deliverables Generated**:
- Saved a unified, fully-styled workbook containing Project Info, Cabinet Matrix, individual Shop Drawing Schedules, and a dynamically calculated Job Costing sheet:
- [05_Cabinet_Estimation_Shop_Drawings_Casa_Familia.xlsx](file:///C:/Users/prajw/OneDrive/Desktop/Albert/Albert_Project/Casa%20familia/03_Shop_Drawings/05_Cabinet_Estimation_Shop_Drawings_Casa_Familia.xlsx)
- Created separate modular deliverables matching template structures:
- [Cabinet_Matrix_Casa_Familia.xlsx](file:///C:/Users/prajw/OneDrive/Desktop/Albert/Albert_Project/Casa%20familia/02_Price_List/Cabinet_Matrix_Casa_Familia.xlsx)
- [Job_Costing_Calculator_Casa_Familia.xlsx](file:///C:/Users/prajw/OneDrive/Desktop/Albert/Albert_Project/Casa%20familia/02_Price_List/Job_Costing_Calculator_Casa_Familia.xlsx)
---
## 📊 Summary of Final Project Estimate
- **Total Units**: 50
- **Total Cabinets**: 630 (512 Kitchen + 118 Bath)
- **Estimated Containers**: 3 (220 cabinets per container limit)
- **Total Material Cost**: $88,730.00 ($64,768.00 Kitchen + $23,962.00 Bath)
- **Pre-Margin Cost**: $124,196.25 (includes shipping, use tax, inland delivery, installation, warehousing, protection, and insurance)
- **GP Target**: 35%
- **Total Project Selling Price**: **$212,301.28**
- **Average Cost per Cabinet**: $336.99 (calculated)
- **Average Selling Price per Cabinet**: $336.99 (calculated cost-plus)
---
## 🔍 Validation Results
All Excel workbooks have been verified programmatically for:
- Correct formula strings for sub-totals, container count, pre-margin costs, margins, and selling price.
- Grid lines enabled, custom color keys (navy title headers, light gray summaries, blue inputs, green outputs).
- Standardized cabinet code mapping (`W3630`, `B36`, `WC2430`, `VAN36`, etc.) aligned with the Vendor Price List and Cabinet Library.
@@ -1,156 +0,0 @@
# End-to-End Walkthrough: AI Cabinet Estimation & Shop Drawing Automation
## Complete Process Documentation: Start to End
This document provides a clear, step-by-step explanation of the entire automated workflow implemented for the **Casa Familia** project. It details how the system takes raw architectural drawings, reads them, matches them to a pricing catalog, and outputs a complete financial estimate.
---
## 🗺️ Process Map: The Big Picture
The automation pipeline consists of **5 Core Phases**:
```mermaid
graph TD
A[Phase 1: PDF Drawing Ingestion] --> B[Phase 2: Spatial Parsing & Scale Mapping]
B --> C[Phase 3: Keynote & Cabinet Identification]
C --> D[Phase 4: Matrix Consolidation & Quantities]
D --> E[Phase 5: Pricing Catalog & Job Costing]
E --> F[Phase 6: Excel Deliverables Generation]
```
---
## 🔍 Phase 1: PDF Ingestion & Layout Identification
*How we read and categorize the input drawings.*
1. **Digital Vector Scan**:
- The architectural drawings (e.g., [Unit_Plans_FHA_ADA/A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf](file:///C:/Users/prajw/OneDrive/Desktop/Albert/Albert_Project/Casa%20familia/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf)) are not scanned images. They are **born-digital CAD exports**.
- This allows PyMuPDF to extract exact vector text spans and drawing lines directly from the PDF without requiring slow and error-prone optical character recognition (OCR).
2. **Viewport Bounding Box Grouping**:
- The drawing sheet contains multiple views on a single page (Floor Plan, RCP, Kitchen Plan, Elevations).
- The script scans for view titles (like `UNIT A1 KITCHEN PLAN` or `UNIT A1 KITCHEN EL.`) in large font sizes.
- It then creates coordinate bounding boxes (crops) for each view. For example:
- **Kitchen Plan View**: x in $(750, 1300)$, y in $(1220, 1520)$
- **Kitchen Elevation View**: x in $(1250, 1800)$, y in $(1220, 1627)$
---
## 📏 Phase 2: Spatial Parsing & Scale Mapping
*How we convert drawing coordinates into real physical dimensions.*
1. **Drawing Scale Heuristics**:
- The drawing sheet notes a scale of **`1/2" = 1'-0"`**.
- In standard PDF coordinate layout, **1 inch = 72 points**.
- Therefore, $1/2$ inch on the page represents $12$ inches in real life:
$$\text{Scale Ratio} = \frac{36 \text{ points}}{12 \text{ inches}} = 3 \text{ points per real inch}$$
- Any rectangle drawn on the PDF can be measured in points and divided by $3.0$ to find its exact size in real inches! For example:
- A rectangle with width of **$108.0 \text{ points}$** represents a **$36\text{-inch}$ base cabinet**.
- A rectangle with height of **$72.6 \text{ points}$** represents a **$24\text{-inch}$ wall cabinet**.
---
## 🏷️ Phase 3: Keynote & Cabinet Identification
*How we map annotations to actual cabinet types.*
1. **Legend Extraction**:
- The right side of the sheet ($x > 1800$) contains the keynote legend. The script parses this list to extract descriptions:
- `U1` = Refrigerator (90 cm / 36" wide)
- `U2` = Sink
- `U3` = Dishwasher
- `U9` = 12" Width x 24" Depth Pantry
- `U20` = Vanity Cabinet
2. **Cabinet Code Matching**:
- The script looks at the drawing elevations, finds the rectangles (cabinets) and their nearest text tags (like `U2`, `U9`, or dimensions like `2' - 6"`).
- It matches these specifications to the standard cabinet codes in the **Cabinet Library**:
- A 36" wide Wall Cabinet maps to code **`W3630`**.
- A 36" wide Sink Base maps to code **`B36`** (under Sink base description).
- A 60" wide Bathroom double vanity maps to code **`VAN60`**.
---
## 📊 Phase 4: Matrix Consolidation & Quantities
*How we aggregate unit cabinet counts to find the project total.*
1. **Cabinet Matrix Generation**:
- We extract the cabinet counts for each unit type (A1, A2-FA, A3, B1, B2-FA, B3).
- We look up how many of each unit type are in the project (from building floor plans):
- **A1**: 14 units
- **A2-FA**: 6 units
- **A3**: 6 units
- **B1**: 12 units
- **B2-FA**: 6 units
- **B3**: 6 units
- **Total Units**: **50**
2. **Project Cabinet Totals**:
- The script computes the total count of each cabinet type across all units:
- **Total Kitchen Cabinets**: **512 units**
- **Total Bath Cabinets**: **118 units**
- **Grand Total Cabinets**: **630 units**
---
## 💰 Phase 5: Pricing Catalog & Job Costing
*How we calculate the project costs and selling price.*
1. **Wholesale Pricing Lookups**:
- For kitchen cabinets, we look up their sizes in the wholesale Euro price list ([MS PRICE LIST LEVEL 1 -90CM.xlsx](file:///C:/Users/prajw/OneDrive/Desktop/Albert/Albert_Project/Casa%20familia/02_Price_List/MS%20PRICE LIST LEVEL%201%20-90CM.xlsx)).
- For bathroom vanities, mirrors, and linen cabinets (which are not in the Euro price list), we look up their prices in the USD price list catalog ([03_Vendor_Price_List_Template.xlsx](file:///C:/Users/prajw/OneDrive/Desktop/Albert/Architecture_new/01_Templates/03_Vendor_Price_List_Template.xlsx)).
- We calculate the total wholesale material cost for all 630 cabinets:
- **Total Kitchen Material Cost**: **$64,768.00**
- **Total Bath Material Cost**: **$23,962.00**
- **Material Subtotal**: **$88,730.00**
2. **Project Cost Build-Up**:
We add all additional logistics, labor, and local taxes to find the total **Pre-Margin Cost**:
- **Local Use Tax (7.5%)**: $\$88,730.00 \times 0.075 = \mathbf{\$6,654.75}$
- **Ocean Freight**: $3 \text{ containers} \times \$4,500 = \mathbf{\$13,500.00}$ (calculated based on 220 cabinets per container limit).
- **Inland Delivery**: **$1,200.00** (Fixed delivery fee)
- **Installation**: $630 \text{ cabinets} \times \$85 = \mathbf{\$53,550.00}$ (Labor cost)
- **Warehousing (2.0%)**: $\$88,730.00 \times 0.02 = \mathbf{\$1,774.60}$
- **Material Protection (0.5%)**: $\$88,730.00 \times 0.005 = \mathbf{\$443.65}$
- **Insurance (0.8%)**: $\$88,730.00 \times 0.008 = \mathbf{\$709.84}$
- **Misc. Allowance**: **$500.00** (Fixed safety buffer)
- **PRE-MARGIN SUBTOTAL**: **$167,062.84** (Sum of all costs above)
3. **Selling Price Formula**:
The final Selling Price is calculated to achieve a target **35% Gross Profit (GP)** margin, while accounting for **5% sales commission** and **1.5% payment bond**:
$$\text{Selling Price} = \frac{\text{Pre-Margin Subtotal}}{1 - \text{GP\%} - \text{Commission\%} - \text{Bond\%}}$$
$$\text{Selling Price} = \frac{\$167,062.84}{1 - 0.35 - 0.05 - 0.015} = \frac{\$167,062.84}{0.585} = \mathbf{\$285,577.50}$$
---
## 🗄️ Phase 6: Deliverables & Directory Layout
*Where your final files are stored.*
All calculated sheets have been structured and saved to your project directory.
```
📁 Albert/
└── 📁 Albert_Project/
├── 📁 Casa familia/
│ ├── 📁 02_Price_List/
│ │ └── 📄 Cabinet_Matrix_Casa_Familia.xlsx (Aggregated quantities)
│ │ └── 📄 Job_Costing_Calculator_Casa_Familia.xlsx (Financial costing sheet)
│ └── 📁 03_Shop_Drawings/
│ └── 📄 05_Cabinet_Estimation_Shop_Drawings_Casa_Familia.xlsx (All-In-One sheets)
├── 📁 _Project_Understanding/
│ └── 📄 04_Walkthrough_Casa_Familia_Completed.md (Text summary walkthrough)
│ └── 📄 05_Complete_Process_Walkthrough.md (This master documentation)
└── 📄 run_cabinet_estimation.py (Python CLI runner tool)
```
You can open any of these files directly to review the formatted sheets and tables.
---
## 🚀 How to Run Automated Estimations in the Future
*Running the pipeline for Heritage Village or future projects.*
To run the estimation pipeline on a new set of PDF drawings, you can run the command-line script in your terminal:
```powershell
python run_cabinet_estimation.py --pdf "path_to_drawings.pdf" --prices "path_to_price_list.xlsx" --gp 0.35 --output "Final_Estimate.xlsx"
```
This ensures that your estimation department has a fully functional, repeatable, and automated pipeline that will turn around project bids in minutes, easily meeting the **< 24-hour turnaround** business goal.
@@ -1,106 +0,0 @@
# Implementation Plan: Automated Shop Drawing PDF Generation System
## Goal Description
Build a production-grade programmatic PDF generation engine that creates professional 17" x 11" Tabloid landscape shop drawings, matching the style and visual quality of the [ItalianKB Reference Drawings](file:///c:/Users/prajw/OneDrive/Desktop/Albert/Albert_Project/Casa%20familia/03_Shop_Drawings/ITALIANKB%20SHOP%20DRAWINGS%20-%2023-033%20CASA%20FAMILIA%20-%2003.04.2025%20hatch%20corregido.pdf).
---
## 🔬 Deep Dive: ItalianKB PDF Structure & Characteristics
Our forensic analysis of `ITALIANKB SHOP DRAWINGS - 23-033 CASA FAMILIA.pdf` reveals:
- **Page Size**: Exactly `1224.0 x 792.0` points, which is **17.00" x 11.00" (ANSI B / Tabloid landscape)**.
- **Graphics Type**: Pixel-perfect vector paths (`1,232` vector paths per page) plotted from AutoCAD LT 2025.
- **Fonts**: Labeled with clean sans-serif typefaces (`ArialMT`, `CenturyGothic`, `CenturyGothic-Bold`, `Arial-BoldMT`).
- **Layout Grid**:
- **Left Area (80% width)**: Contains CAD floor plan layout and elevation frontages with metric/imperial annotations (e.g. `90.00 [2'-11 7/16"]`).
- **Right Area (20% width)**: Contains the standardized title block, notes legend, revision tables, and page identifiers (e.g. `A.1`).
---
## 🔄 Proposed PDF Generation Options
We evaluate three technical approaches for programmatic drawing generation:
| Metric | Option A: ReportLab (Canvas Vector API) | Option B: PyMuPDF Drawing Overlay | Option C: WeasyPrint (HTML + SVG) [RECOMMENDED] |
| :--- | :--- | :--- | :--- |
| **Drawing CAD details** | Hard — requires manual canvas line math | Moderate — can overlay on raw drawing | Easy — uses native vector SVG tags |
| **Schedules / Layouts** | Moderate — uses Platypus Flowables | Hard — no flow engine, manual positions | Easy — uses native CSS Grid & Flexbox |
| **Title Block & Design** | Hard — requires canvas drawing code | Moderate — template overlay | Easy — standard HTML templates + CSS |
| **Maintainability** | Low — Python canvas layout is verbose | Low — coordinate manipulation is rigid | High — clean division of SVG graphics and HTML |
> [!TIP]
> **Why Option C is Superior:**
> Combining HTML templates with vector SVGs allows us to render complex CAD vector coordinates natively inside `<svg>` tags while utilizing standard CSS for styling title blocks, page frames, and tables. WeasyPrint compiles the combined document into a vector-crisp, tabloid-scaled print PDF.
---
## 📐 End-to-End Generation Pipeline
The generation pipeline takes the extracted cabinet counts and drawing details and compiles them:
```mermaid
graph TD
A[Cabinet Data & Dimensions] --> B[HTML/CSS Template Engine]
C[Architectural vector lines] --> D[SVG Vector Graphics Generator]
B --> E[Unified HTML Document]
D --> E
E --> F[WeasyPrint Compiler]
F --> G[Tabloid 17x11 PDF Shop Drawing]
```
### 1. Drawing Processing: Extracting Plan Views
- The input architectural PDF lines (walls, appliances, doors) are cropped from the plan view viewport.
- The coordinates of these vector lines are exported as SVG elements (`<line>`, `<rect>`, `<path>`) to form the background drawing.
### 2. Parametric Cabinet Elevation Drawing
- Using the width, height, and type of each cabinet from the data schedule, the generator programmatically draws the cabinet frontages inside an SVG viewport:
- **Base Cabinets**: Draws a $4"\text{ toe-kick}$ rectangle at bottom, a door/drawer outline, and a small circle for handles.
- **Drawers**: Draws horizontal panel division lines.
- **Wall Cabinets**: Draws dashed swing lines representing the door open direction.
```mermaid
classDiagram
class CabinetSVG {
+draw_toe_kick(x, width)
+draw_door_panel(x, y, width, height, swing)
+draw_drawer_fronts(x, y, width, height, qty)
+draw_dimension_lines(x, y, width, height)
}
```
---
## 🛠️ Code Architecture
We propose a Python rendering module `pdf_generator.py` containing:
```python
class ShopDrawingGenerator:
def __init__(self, unit_data, output_path):
self.unit_data = unit_data
self.output_path = output_path
def generate_svg_elevation(self, section_type):
"""Generates parametric SVGs of cabinet elevations based on schedule data."""
pass
def render_html_page(self):
"""Assembles HTML layouts combining parametric SVGs and schedules."""
pass
def compile_pdf(self):
"""Compiles HTML using WeasyPrint to 17x11 PDF."""
pass
```
---
## 🧪 Verification Plan
### Automated Tests
- **Geometric Validation**: Check that the generated PDF dimensions match standard ratios (17" x 11").
- **Asset Integrity**: Check that all SVGs compile correctly without broken path tokens.
### Manual Verification
- **Visual Inspection**: Print the generated sheet on Tabloid paper to verify scale and alignment.
- **Client Sign-off**: Deliver a sample sheet to the client for style review.
@@ -0,0 +1,141 @@
import os
import json
import fitz
from typing import Dict, Any, List, Optional
from typing_extensions import TypedDict
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, START, END
from core.agents.config_schema import ExtractedConfigMetadata
load_dotenv()
# State definition
class ExtractionState(TypedDict):
pdf_path: str
extracted_text: str
parsed_config: Optional[ExtractedConfigMetadata]
errors: List[str]
retry_count: int
# Initialize LLM
def get_llm():
return ChatOpenAI(
model="google/gemini-2.5-flash",
api_key=os.environ.get("OPENROUTER_API_KEY"),
base_url="https://openrouter.ai/api/v1",
temperature=0.0
)
def load_document(state: ExtractionState) -> Dict:
"""Extracts text from the first few pages of the PDF, which usually contain the schedules and metadata."""
pdf_path = state["pdf_path"]
text_content = []
try:
doc = fitz.open(pdf_path)
# We only need the first 3-5 pages typically for metadata and schedules
num_pages_to_scan = min(5, len(doc))
for i in range(num_pages_to_scan):
page = doc[i]
text = page.get_text()
text_content.append(f"--- PAGE {i+1} ---\n{text}")
except Exception as e:
return {"errors": state.get("errors", []) + [f"Failed to read PDF: {str(e)}"]}
return {"extracted_text": "\n".join(text_content)}
def llm_extract_data(state: ExtractionState) -> Dict:
"""Uses LangChain with_structured_output to parse the text into our Pydantic schema."""
text = state.get("extracted_text", "")
errors = state.get("errors", [])
if not text:
return {"errors": errors + ["No text available to extract."], "retry_count": state.get("retry_count", 0) + 1}
llm = get_llm()
structured_llm = llm.with_structured_output(ExtractedConfigMetadata)
system_prompt = (
"You are an expert architectural plan parser. Your task is to extract "
"project metadata, appliance schedules, and the unit matrix from the provided raw text "
"extracted from a PDF plan set.\n\n"
"Guidelines:\n"
"- Fill out as many fields as possible based on the text.\n"
"- If a field isn't explicitly found, leave it as default or empty.\n"
"- The 'unit_matrix' contains rows of units and how many vanity/kitchen types they have.\n"
"- The 'buildings' field maps building names (e.g. 'BUILDING TYPE A') to the unit keys they contain.\n"
)
if errors:
last_error = errors[-1]
system_prompt += f"\nPrevious attempt failed with error:\n{last_error}\nPlease correct this issue."
try:
result = structured_llm.invoke([
SystemMessage(content=system_prompt),
HumanMessage(content=text)
])
return {"parsed_config": result, "retry_count": state.get("retry_count", 0) + 1}
except Exception as e:
return {"errors": errors + [f"LLM extraction failed: {str(e)}"], "retry_count": state.get("retry_count", 0) + 1}
def validate_config(state: ExtractionState) -> Dict:
"""Validates the extracted config."""
config: ExtractedConfigMetadata = state.get("parsed_config")
errors = state.get("errors", [])
if not config:
return {"errors": errors + ["Parsed config is None"]}
new_errors = []
# Check if unit_matrix has at least one row
if not config.unit_matrix:
new_errors.append("Unit matrix is empty. Expected at least one row.")
else:
# Populate auto-computed unit_counts
config.unit_counts = {row.key: row.qty for row in config.unit_matrix}
return {"errors": errors + new_errors, "parsed_config": config}
def should_continue(state: ExtractionState) -> str:
"""Routing logic after validation."""
errors = state.get("errors", [])
retry_count = state.get("retry_count", 0)
if errors and retry_count < 3:
return "retry"
return "end"
def build_extractor_graph():
"""Builds and returns the LangGraph state machine."""
builder = StateGraph(ExtractionState)
builder.add_node("load_document", load_document)
builder.add_node("llm_extract_data", llm_extract_data)
builder.add_node("validate_config", validate_config)
builder.add_edge(START, "load_document")
builder.add_edge("load_document", "llm_extract_data")
builder.add_edge("llm_extract_data", "validate_config")
builder.add_conditional_edges(
"validate_config",
should_continue,
{
"retry": "llm_extract_data",
"end": END
}
)
return builder.compile()
@@ -0,0 +1,56 @@
from typing import List, Dict, Optional, Any
from pydantic import BaseModel, Field
class CompanyInfo(BaseModel):
name: str = Field(default="ITALIAN KITCHEN AND BATH")
tagline: str = Field(default="kitchen | bath | tile | closet")
address: str = Field(default="1777 NW 72TH AVE. MIAMI FL, 33126")
phone: str = Field(default="T. 305.599.9000 F. 305.599.9870")
class RevisionInfo(BaseModel):
rev: str = Field(..., description="Revision number, e.g. '1.0'")
date: str = Field(..., description="Date of revision")
initials: str = Field(..., description="Initials of the drafter")
desc: str = Field(default="", description="Description of the revision")
class UnitMatrixRow(BaseModel):
unit: str = Field(..., description="Full unit name, e.g. 'UNIT A1'")
qty: int = Field(..., description="Quantity of this unit")
v1: int = Field(default=0, description="Quantity of V1 vanities")
v2: int = Field(default=0, description="Quantity of V2 vanities")
v3: int = Field(default=0, description="Quantity of V3 vanities")
v4: int = Field(default=0, description="Quantity of V4 vanities")
kitchen: str = Field(..., description="Kitchen type key, e.g. 'K1' or 'K2'")
is_ada: bool = Field(default=False, description="True if unit is ADA accessible")
key: str = Field(..., description="Short key identifier, e.g. 'A1' or 'A2-ADA'")
class ExtractedConfigMetadata(BaseModel):
"""
Extracted top-level metadata from an architectural PDF cover page.
"""
class Config:
extra = "allow"
project_id: str = Field(default="new_project", description="Short ID without spaces")
project_name: str = Field(default="New Project", description="Full name of the project")
project_no: str = Field(default="", description="Project number, if any")
matrix_format: str = Field(default="v_matrix")
client_name: str = Field(default="")
project_address: str = Field(default="")
date: str = Field(default="")
revision: str = Field(default="1.0")
drawn_by: str = Field(default="")
dimension: str = Field(default="CM|INCHES")
finish: str = Field(default="", description="e.g. K019 SILVER LIBERTY ELM")
door_style: str = Field(default="Slab")
company: CompanyInfo = Field(default_factory=CompanyInfo)
revisions: List[RevisionInfo] = Field(default_factory=list)
appliances_regular: List[str] = Field(default_factory=list, description="List of regular appliances")
appliances_ada: List[str] = Field(default_factory=list, description="List of ADA appliances")
general_notes: List[str] = Field(default_factory=list, description="List of general notes")
buildings: Dict[str, List[str]] = Field(default_factory=dict, description="Map of building names to a list of unit keys")
unit_matrix: List[UnitMatrixRow] = Field(default_factory=list, description="Rows of the unit matrix table")
unit_counts: Dict[str, int] = Field(default_factory=dict, description="Auto-computed: Maps unit key to quantity.")
unit_plan_pdfs: Dict[str, str] = Field(default_factory=dict, description="TODO: Needs manual intervention. Maps unit key to PDF file path.")
kitchen_types: Dict[str, Any] = Field(default_factory=dict, description="TODO: Vision extraction for V2")
vanity_types: Dict[str, Any] = Field(default_factory=dict, description="TODO: Vision extraction for V2")
+321 -288
View File
@@ -5,23 +5,23 @@
Uses OpenRouter API (Google Gemini models only) to classify cabinets
from architectural elevation drawings.
PRIMARY MODEL: google/gemini-2.5-flash
- Best for technical/architectural drawings
- Excellent spatial reasoning and OCR on dimension annotations
- $1.5/1M input tokens — fast and affordable
- 1M token context window
PRIMARY MODEL: google/gemini-2.5-pro
- Best for technical/architectural drawings
- Stronger spatial reasoning and OCR on dimension annotations
- Higher accuracy for ambiguous or dense sheets
- 1M token context window
FALLBACK MODEL: google/gemini-2.5-pro
- More powerful Gemini for complex/ambiguous drawings
- $2.5/1M input tokens
- Kicks in when Flash returns low-confidence or invalid JSON
FALLBACK MODEL: google/gemini-2.5-flash
- Faster and lower-cost fallback for simpler sheets
- Useful when Pro is unavailable or rate-limited
- Kicks in when the primary model returns low-confidence or invalid JSON
Pipeline per elevation crop:
1. Receive: PNG image bytes (400 DPI crop) + pre-extracted dims + rects
2. Build: structured prompt with dimension context
3. Call: OpenRouter API (gemini-2.5-flash) with base64 image
4. Parse: JSON response → list[CabinetItem]
5. Retry with gemini-2.5-pro if JSON parse fails or confidence < 0.7
2. Build: structured prompt with dimension context and legend mappings
3. Call: OpenRouter API (gemini-2.5-pro) with base64 image
4. Parse: JSON response → detailed dict containing cabinets, openings, relationships
5. Retry with gemini-2.5-flash if JSON parse fails or confidence < 0.7
6. Exponential backoff on API errors
Get key at: https://openrouter.ai
@@ -42,10 +42,10 @@ from core.config import AUTO_APPROVE_CONFIDENCE, OPENROUTER_API_KEY
# ── OpenRouter Configuration ─────────────────────────────────────────────────
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1/chat/completions"
# Primary: Gemini 2.5 Flash — best at technical/spatial drawings, fast & cheap
PRIMARY_MODEL = "google/gemini-2.5-flash"
# Fallback: Gemini 2.5 Pro — stronger reasoning for ambiguous/complex drawings
FALLBACK_MODEL = "google/gemini-2.5-pro"
# Primary: Gemini 2.5 Pro — strongest reasoning for technical/spatial drawings
PRIMARY_MODEL = "google/gemini-2.5-pro"
# Fallback: Gemini 2.5 Flash — faster and cheaper backup model
FALLBACK_MODEL = "google/gemini-2.5-flash"
MAX_TOKENS = 4096
# ── Demo Mode — low token usage for client demonstrations ─────────────────────
@@ -53,15 +53,64 @@ MAX_TOKENS = 4096
# Reduces cost from ~$0.0015/call → ~$0.0002/call (~85% savings)
DEMO_MODE: bool = os.getenv("DEMO_MODE", "false").lower() in ("1", "true", "yes")
DEMO_DPI = 150 # vs 400 in full mode — image tokens: ~88% smaller
DEMO_MAX_TOKENS = 800 # vs 4096 — output capped tightly
DEMO_MAX_TOKENS = 1200 # slightly larger for complex nested JSON output
DEMO_MAX_DIMS = 8 # vs 30 pre-extracted dims sent in context
DEMO_MAX_RECTS = 10 # vs 40 rectangle vectors sent in context
# ══════════════════════════════════════════════════════════════════════════
# DATA CLASSES
# DATA CLASSES — Architectural Intent (Phase 4, new)
# ══════════════════════════════════════════════════════════════════════════
# Valid cabinet types the AI can return
@dataclass
class WallIntent:
name: str
length_in: float
notes: str = ""
@dataclass
class OpeningIntent:
type: str
width_in: float
height_in: float
x_in: float
sill_height_in: float = 0.0
notes: str = ""
@dataclass
class ApplianceIntent:
type: str
width_in: float
height_in: float
x_in: float
notes: str = ""
@dataclass
class FixtureIntent:
type: str
width_in: float
x_in: float
notes: str = ""
@dataclass
class StructuralIntent:
type: str
width_in: float
depth_in: float
x_in: float
notes: str = ""
@dataclass
class ClearanceIntent:
type: str
radius_in: float
x_in: float
notes: str = ""
# ══════════════════════════════════════════════════════════════════════════
# DATA CLASSES — Legacy compatibility (used by pipeline, validators, tests)
# ══════════════════════════════════════════════════════════════════════════
# Valid cabinet types the AI can return (legacy — placement engine will generate these)
VALID_CABINET_TYPES = {
"upper_wall", # Standard wall cabinet (upper)
"base", # Standard base cabinet
@@ -80,27 +129,35 @@ VALID_CABINET_TYPES = {
}
from core.units import Length
@dataclass
class CabinetItem:
"""One cabinet identified in an elevation drawing."""
"""One cabinet identified in an elevation drawing.
LEGACY: This class is retained for backward compatibility with the existing
pipeline, validators, test suite, and cache deserialization. In Phase 4,
cabinet items are generated by the Placement Engine — not by AI extraction.
"""
item_num: int
cabinet_type: str # from VALID_CABINET_TYPES
width_mm: float
height_mm: float
depth_mm: float
width_in: float | Length
height_in: float | Length
depth_in: float | Length
location: str # human-readable position note
elevation_ref: str # "ELEVATION A", "ELEVATION B", etc.
confidence: float # 0.0–1.0
quantity: int = 1
is_ada: bool = False
notes: str = ""
source: str = "gemini" # "gemini" | "manual" | "fallback"
source: str = "gemini" # "gemini" | "manual" | "fallback" | "placement_engine"
cabinet_id: str = "" # keynote ID (e.g. U10, U3)
@property
def code(self) -> str:
"""Generate a standard cabinet code from type and dimensions."""
w_in = round(self.width_mm / 25.4)
h_in = round(self.height_mm / 25.4)
w_in = round(self.width_in)
h_in = round(self.height_in)
type_prefix = {
# Width-only codes
"base": f"B{w_in}",
@@ -127,18 +184,61 @@ class CabinetItem:
return asdict(self)
# ══════════════════════════════════════════════════════════════════════════
# ELEVATION RESULT
# ══════════════════════════════════════════════════════════════════════════
@dataclass
class ElevationResult:
"""Result of classifying one elevation section."""
elevation_label: str # "ELEVATION A"
unit_type: str # "A1", "B1-ADA"
"""Result of classifying one elevation section.
Contains both the new architectural-intent fields (walls, openings, fixtures,
structural, clearances) and the legacy fields (cabinets, doors, windows,
fillers, panels, moldings, relationships) needed by the existing pipeline.
"""
elevation_label: str
unit_type: str
project_name: str
cabinets: list[CabinetItem] = field(default_factory=list)
total_width_mm: Optional[float] = None
is_ada: bool = False
auto_approved: bool = False
review_flags: list[str] = field(default_factory=list)
api_calls: int = 0
confidence: float = 0.0
ceiling_height_in: Optional[float] = None
soffit_present: bool = False
backsplash: str = ""
counter_material: str = ""
# Phase 4: Architectural Intent (new — populated by AI extraction)
walls: list[WallIntent] = field(default_factory=list)
openings: list[OpeningIntent] = field(default_factory=list)
fixtures: list[FixtureIntent] = field(default_factory=list)
structural: list[StructuralIntent] = field(default_factory=list)
clearances: list[ClearanceIntent] = field(default_factory=list)
# Legacy fields (populated by placement engine or cache deserialization)
cabinets: list[CabinetItem] = field(default_factory=list)
appliances: list[dict] = field(default_factory=list)
doors: list[dict] = field(default_factory=list)
windows: list[dict] = field(default_factory=list)
fillers: list[str] = field(default_factory=list)
panels: list[str] = field(default_factory=list)
moldings: list[str] = field(default_factory=list)
relationships: list[dict] = field(default_factory=list)
total_width_in: Optional[float] = None
@property
def min_confidence(self) -> float:
if self.cabinets:
return min(c.confidence for c in self.cabinets)
return self.confidence
@property
def avg_confidence(self) -> float:
if self.cabinets:
return sum(c.confidence for c in self.cabinets) / len(self.cabinets)
return self.confidence
@property
def kitchen_cabinets(self) -> list[CabinetItem]:
@@ -150,18 +250,6 @@ class ElevationResult:
return [c for c in self.cabinets
if c.cabinet_type in ("vanity", "medicine_cabinet", "linen")]
@property
def min_confidence(self) -> float:
if not self.cabinets:
return 0.0
return min(c.confidence for c in self.cabinets)
@property
def avg_confidence(self) -> float:
if not self.cabinets:
return 0.0
return sum(c.confidence for c in self.cabinets) / len(self.cabinets)
# ══════════════════════════════════════════════════════════════════════════
# PROMPT BUILDER
@@ -169,71 +257,102 @@ class ElevationResult:
def _build_system_prompt(demo: bool = False) -> str:
if demo:
# Compact prompt — ~250 tokens vs ~800 tokens
return (
"You are a cabinet estimator. Analyze this architectural elevation drawing and return "
"a JSON array of cabinets. Types: upper_wall, base, sink_base, dw_adjacent, "
"microwave_shelf, pantry, corner_upper, corner_base, vanity, medicine_cabinet, "
"linen, appliance_space, filler, unknown. "
"Each item: {item_num, cabinet_type, width_mm, height_mm, depth_mm, location, "
"elevation_ref, confidence, quantity, is_ada, notes}. "
"Std widths: 300,350,400,450,500,550,600,762,900mm. "
"Base h=720mm d=600mm. Wall h=300mm d=330mm. Pantry h=2130mm. "
"Return ONLY valid JSON array, no markdown."
"You are an architectural intent parser. Analyze this elevation drawing and return "
"a JSON object with the following schema:\n"
"{\n"
" \"ceiling_height_in\": 108,\n"
" \"soffit_present\": false,\n"
" \"backsplash\": \"4\\\" backsplash\",\n"
" \"counter_material\": \"Quartz\",\n"
" \"confidence\": 0.95,\n"
" \"walls\": [ { \"name\": \"Wall A\", \"length_in\": 120, \"notes\": \"\" } ],\n"
" \"openings\": [ { \"type\": \"window\", \"width_in\": 36, \"height_in\": 48, \"x_in\": 42, \"sill_height_in\": 36, \"notes\": \"\" } ],\n"
" \"appliances\": [ { \"type\": \"REF\", \"width_in\": 36, \"height_in\": 70, \"x_in\": 0, \"notes\": \"\" } ],\n"
" \"fixtures\": [ { \"type\": \"sink\", \"width_in\": 36, \"x_in\": 60, \"notes\": \"Center of sink\" } ],\n"
" \"structural\": [],\n"
" \"clearances\": []\n"
"}\n"
"Return ONLY valid JSON. DO NOT output cabinet IDs."
)
return """You are an expert cabinet estimator with 20+ years of experience reading architectural kitchen and bathroom elevation drawings for US residential construction projects (FHA/ADA housing).
Your job is to analyze architectural elevation drawings and extract a precise, complete cabinet schedule.
return """You are an expert architectural intent parser analyzing kitchen and bathroom elevation drawings for US residential construction.
CABINET TYPES you must classify:
- upper_wall: Wall-mounted cabinet (above countertop)
- base: Standard floor base cabinet
- sink_base: Base cabinet under sink (open back or plumbing cutout)
- dw_adjacent: Base cabinet adjacent to dishwasher slot (not the DW itself)
- microwave_shelf: Upper cabinet housing a microwave above range
- pantry: Tall floor-to-ceiling pantry cabinet (usually 84" high)
- corner_upper: Corner wall cabinet (blind corner or lazy susan)
- corner_base: Corner base cabinet
- vanity: Bathroom vanity (lower cabinet with sink)
- medicine_cabinet: Bathroom medicine cabinet / mirror cabinet
- linen: Linen closet or storage cabinet in bathroom
- appliance_space: Space reserved for appliance (DW, fridge, range) — NO CABINET, just a placeholder
- filler: Filler panel (narrow strips between cabinets or walls)
- unknown: Cannot determine type with confidence
Your job is strictly to extract raw Architectural Intent (walls, appliances, fixtures, openings, and clearances).
❌ DO NOT invent, guess, or assign cabinet IDs (e.g. do NOT output B36, SB36, W3030, etc).
Your output must purely describe the physical constraints of the room that a downstream engine will use to place cabinets deterministically.
STANDARD DIMENSIONS (metric, 90cm depth standard):
- Base cabinets: height 720mm (34.5"), depth 600mm (24")
- ADA base: height 864mm (34" countertop max), depth 600mm
- Wall/upper cabinets: height 300mm (12"), 380mm (15"), 720mm (30"), depth 330mm (13")
- Pantry: height 2130mm (84"), depth 600mm
- Vanity: height 870mm (34.5"), depth 530mm (21")
- Standard widths: 150, 300, 350, 400, 450, 500, 550, 600mm (6",12",14",16",18",20",22",24")
and 762mm (30"), 900mm (35.4"), 1050mm (41.3"), 1200mm (47.2")
You must return a single JSON object matching this schema:
{
"ceiling_height_in": 0, // Ceiling height in inches if visible (look for "AFF", "CLG", or dimension lines to ceiling). Use 0 if unknown.
"soffit_present": false, // true if a soffit (dropped ceiling bulkhead) is present
"backsplash": "", // Wall finish description, or empty string
"counter_material": "", // Countertop material description, or empty string
"confidence": 0.0, // Overall confidence in this extraction (0.0 to 1.0)
"walls": [
{
"name": "Wall A", // e.g. "Main Sink Wall", "Island"
"length_in": 0, // Total length of the wall run in inches. Use 0 if unknown.
"notes": ""
}
],
"openings": [
{
"type": "door", // "door" or "window" or "pass-through"
"width_in": 0,
"height_in": 0,
"x_in": 0, // Offset in inches from far-left wall/boundary
"sill_height_in": 0, // Sill height from floor (useful for windows)
"notes": ""
}
],
"appliances": [
{
"type": "REF", // e.g. REF, DW, RANGE, MIC, HOOD, OVEN
"width_in": 0,
"height_in": 0,
"x_in": 0, // Offset in inches from far-left wall/boundary
"notes": ""
}
],
"fixtures": [
{
"type": "sink", // e.g. sink, toilet, tub
"width_in": 0, // Width of the fixture space
"x_in": 0, // Center-line offset in inches from far-left wall/boundary
"notes": ""
}
],
"structural": [
{
"type": "column", // e.g. column, chase, pipe
"width_in": 0,
"depth_in": 0,
"x_in": 0,
"notes": ""
}
],
"clearances": [
{
"type": "ada_turning", // e.g. ada_turning, approach_clearance
"radius_in": 0,
"x_in": 0,
"notes": ""
}
]
}
RULES:
1. Count ONLY cabinets. Do NOT count appliances (dishwasher, refrigerator, range, microwave).
2. Mark appliance positions as type "appliance_space" with the appliance name in "notes".
3. If the drawing shows ADA text or 34" countertop, set is_ada: true.
4. Provide a confidence score (0.0-1.0) for EACH item. Be conservative — if unsure, score 0.7 or lower.
5. ALWAYS return valid JSON — no markdown, no explanation text around the JSON.
6. If you cannot determine a dimension precisely, use the nearest standard size and note your assumption.
OUTPUT FORMAT (JSON array, no other text):
[
{
"item_num": 1,
"cabinet_type": "upper_wall",
"width_mm": 762,
"height_mm": 300,
"depth_mm": 330,
"location": "Left of range, Elevation A",
"elevation_ref": "ELEVATION A",
"confidence": 0.92,
"quantity": 1,
"is_ada": false,
"notes": ""
}
]"""
CRITICAL RULES:
1. Extract the physical constraints of the layout (walls, appliances, openings).
2. Use the provided KEYNOTE LEGEND MAPPING to accurately identify appliances and fixtures marked by codes (e.g. U1, U2).
3. Use the provided ground-truth DIMENSIONS to determine precise `x_in` offsets and widths.
4. For fixtures like sinks and toilets, `x_in` MUST represent the exact CENTER of the fixture from the left boundary.
5. Identify ADA requirements if noted (add ADA clearances).
6. DO NOT OUTPUT CABINETS. ONLY physical features like appliances, walls, and plumbing.
7. DO NOT use `null` for numeric values. If a dimension is missing or unknown, use `0`.
8. Return ONLY valid JSON — no markdown, no explanation text around the JSON.
"""
def _build_user_prompt(
@@ -243,14 +362,13 @@ def _build_user_prompt(
pre_extracted_dims: list[dict],
pre_extracted_rects: list[dict],
is_ada: bool = False,
legend_map: Optional[dict[str, str]] = None,
demo: bool = False,
) -> str:
"""Build the user message with pre-extracted context."""
ada_note = " (ADA — base h≤864mm, countertop≤34\")" if is_ada else ""
ada_note = " (ADA — check for clearances)" if is_ada else ""
# Demo mode: send fewer context items to save tokens
max_dims = DEMO_MAX_DIMS if demo else 30
max_rects = DEMO_MAX_RECTS if demo else 40
dims_str = ""
if pre_extracted_dims:
@@ -258,34 +376,27 @@ def _build_user_prompt(
for d in pre_extracted_dims[:max_dims]:
dims_str += f" [{d.get('type','?')}] '{d.get('text','')}' x={d.get('x',0):.0f} y={d.get('y',0):.0f}\n"
rects_str = ""
if pre_extracted_rects and not demo: # skip rect context in demo (saves ~300 tokens)
rects_str = "\nRECTANGLES (potential cabinet boxes):\n"
for i, r in enumerate(pre_extracted_rects[:max_rects]):
rects_str += (f" R{i+1}: W={r.get('w',0):.0f}pt H={r.get('h',0):.0f}pt "
f"@ ({r.get('x0',0):.0f},{r.get('y0',0):.0f})\n")
legend_str = ""
if legend_map:
legend_str = "\nKEYNOTE LEGEND MAPPING:\n"
for k, v in sorted(legend_map.items(), key=lambda item: int(item[0][1:]) if item[0][1:].isdigit() else 999):
legend_str += f" - {k}: {v}\n"
if demo:
return (f"Project:{project_name} Unit:{unit_type}{ada_note} Section:{elevation_label}\n"
f"{dims_str}\nIdentify all cabinets. Return ONLY JSON array.")
f"{dims_str}\n{legend_str}\nIdentify architectural intent. Return ONLY valid JSON.")
return f"""Project: {project_name}
Unit Type: {unit_type}{ada_note}
Section: {elevation_label}
I am showing you a cropped section of an architectural elevation drawing.
{dims_str}{rects_str}
{dims_str}{legend_str}
Please identify EVERY cabinet in this elevation drawing.
For each rectangle/cabinet shape visible:
1. Determine its type (upper_wall, base, sink_base, dw_adjacent, microwave_shelf, pantry, corner_upper, corner_base, vanity, medicine_cabinet, linen, appliance_space, filler, unknown)
2. Measure/estimate its width in mm (use pre-extracted dimensions if available)
3. Determine height and depth from standard sizes
4. Note its position
5. Score your confidence
Include appliance spaces (dishwasher, range, refrigerator) as type "appliance_space".
Return ONLY the JSON array, nothing else."""
Please identify the ARCHITECTURAL INTENT of this space.
CRITICAL INSTRUCTION: Extract the exact physical properties (Walls, Appliances, Plumbing Fixtures, Openings, Structural Elements). Do NOT guess cabinets.
Measure the width and x_in offset (from the left boundary) of all features accurately using the provided dimensions.
Return ONLY the JSON object, nothing else."""
# ══════════════════════════════════════════════════════════════════════════
@@ -294,17 +405,8 @@ Return ONLY the JSON array, nothing else."""
class CabinetVisionClassifier:
"""
Classifies cabinets from architectural elevation drawing images
Classifies cabinets and layouts from architectural elevation drawing images
using Google Gemini vision models through OpenRouter.
Usage:
classifier = CabinetVisionClassifier()
result = classifier.classify_elevation(
image_bytes=png_bytes,
unit_type="A1",
elevation_label="ELEVATION A",
project_name="Casa Familia",
)
"""
def __init__(self):
@@ -330,24 +432,12 @@ class CabinetVisionClassifier:
pre_extracted_dims: Optional[list[dict]] = None,
pre_extracted_rects: Optional[list[dict]] = None,
is_ada: bool = False,
legend_map: Optional[dict[str, str]] = None,
max_retries: int = 3,
demo_mode: bool = None, # None = use global DEMO_MODE
) -> ElevationResult:
"""
Classify all cabinets in one elevation section.
Args:
image_bytes: PNG bytes of the cropped elevation (400 DPI)
unit_type: e.g. "A1", "B1-ADA"
elevation_label: e.g. "ELEVATION A", "KITCHEN EL."
project_name: e.g. "Casa Familia"
pre_extracted_dims: list of {text, type, x, y} from dimension_parser
pre_extracted_rects: list of {x0, y0, x1, y1, w, h} from pdf_extractor
is_ada: True if this unit is ADA/accessible
max_retries: number of API retry attempts on failure
Returns:
ElevationResult with list of CabinetItem
Classify all cabinets and features in one elevation section.
"""
# Resolve demo mode — argument overrides global flag
use_demo = DEMO_MODE if demo_mode is None else demo_mode
@@ -372,6 +462,7 @@ class CabinetVisionClassifier:
pre_extracted_dims = pre_extracted_dims or [],
pre_extracted_rects = pre_extracted_rects or [],
is_ada = is_ada,
legend_map = legend_map,
demo = use_demo,
)
@@ -396,26 +487,88 @@ class CabinetVisionClassifier:
return result
# Parse JSON response
cabinets = self._parse_cabinet_json(raw_json, elevation_label)
if cabinets is None and not use_demo:
data = self._parse_cabinet_json(raw_json, elevation_label)
if data is None and not use_demo:
# Full mode only: retry with fallback model (Gemini 2.5 Pro)
fix_prompt = (
f"{user_prompt}\n\nIMPORTANT: Return ONLY a valid JSON array. "
"No explanation text, no markdown fences, just the raw JSON array."
f"{user_prompt}\n\nIMPORTANT: Return ONLY a valid JSON object matching the requested schema. "
"No explanation text, no markdown fences, just the raw JSON."
)
print(f" [AI] Retrying with fallback {FALLBACK_MODEL}...")
raw_json2 = self._call_openrouter(
image_bytes, fix_prompt, model=FALLBACK_MODEL, max_retries=1
)
if raw_json2:
cabinets = self._parse_cabinet_json(raw_json2, elevation_label)
data = self._parse_cabinet_json(raw_json2, elevation_label)
if cabinets is None:
if data is None:
model_info = f"{PRIMARY_MODEL}" + ("" if use_demo else f" + {FALLBACK_MODEL}")
result.review_flags.append(f"Failed to parse AI JSON from {model_info}")
return result
result.cabinets = cabinets
# Populate result fields from parsed data
result.ceiling_height_in = data.get("ceiling_height_in")
result.soffit_present = bool(data.get("soffit_present", False))
result.backsplash = str(data.get("backsplash", ""))
result.counter_material = str(data.get("counter_material", ""))
result.confidence = float(data.get("confidence", 0.0))
# Parse walls
for w in data.get("walls", []):
result.walls.append(WallIntent(
name=w.get("name", "Wall"),
length_in=float(w.get("length_in", 0) or 0),
notes=w.get("notes", "")
))
# Parse openings
for o in data.get("openings", []):
result.openings.append(OpeningIntent(
type=o.get("type", "opening"),
width_in=float(o.get("width_in", 0) or 0),
height_in=float(o.get("height_in", 0) or 0),
x_in=float(o.get("x_in", 0) or 0),
sill_height_in=float(o.get("sill_height_in", 0) or 0),
notes=o.get("notes", "")
))
# Parse appliances
for a in data.get("appliances", []):
result.appliances.append(ApplianceIntent(
type=a.get("type", "appliance"),
width_in=float(a.get("width_in", 0) or 0),
height_in=float(a.get("height_in", 0) or 0),
x_in=float(a.get("x_in", 0) or 0),
notes=a.get("notes", "")
))
# Parse fixtures
for f in data.get("fixtures", []):
result.fixtures.append(FixtureIntent(
type=f.get("type", "fixture"),
width_in=float(f.get("width_in", 0) or 0),
x_in=float(f.get("x_in", 0) or 0),
notes=f.get("notes", "")
))
# Parse structural
for s in data.get("structural", []):
result.structural.append(StructuralIntent(
type=s.get("type", "structural"),
width_in=float(s.get("width_in", 0) or 0),
depth_in=float(s.get("depth_in", 0) or 0),
x_in=float(s.get("x_in", 0) or 0),
notes=s.get("notes", "")
))
# Parse clearances
for c in data.get("clearances", []):
result.clearances.append(ClearanceIntent(
type=c.get("type", "clearance"),
radius_in=float(c.get("radius_in", 0) or 0),
x_in=float(c.get("x_in", 0) or 0),
notes=c.get("notes", "")
))
# Set auto-approve flag
result.auto_approved = (
@@ -438,12 +591,7 @@ class CabinetVisionClassifier:
max_retries: int = 3,
max_tokens: int = MAX_TOKENS,
) -> Optional[str]:
"""
Call OpenRouter vision API with any supported model.
Returns raw text response or None on failure.
"""
image_b64 = base64.standard_b64encode(image_bytes).decode("utf-8")
# Use compact system prompt if max_tokens budget is tight (demo mode)
use_demo_prompt = max_tokens <= DEMO_MAX_TOKENS
system_prompt = _build_system_prompt(demo=use_demo_prompt)
img_kb = len(image_bytes) / 1024
@@ -513,84 +661,38 @@ class CabinetVisionClassifier:
self,
raw_text: str,
elevation_label: str,
) -> Optional[list[CabinetItem]]:
) -> Optional[dict]:
"""
Parse JSON array from AI response.
Parse JSON object from AI response.
Handles: extra markdown fences, trailing commas, partial JSON.
"""
# Strip markdown code fences
text = raw_text.strip()
text = re.sub(r'^```(?:json)?\s*', '', text, flags=re.MULTILINE)
text = re.sub(r'\s*```\s*$', '', text, flags=re.MULTILINE)
text = text.strip()
# Find JSON array
start = text.find('[')
end = text.rfind(']')
# Find JSON object or array
start_obj = text.find('{')
start_arr = text.find('[')
# Find JSON object
start = text.find('{')
end = text.rfind('}')
if start == -1 or end == -1:
# Try to find a JSON object
print(f" ⚠️ No JSON array found in response. Raw: {text[:200]}")
print(f" [WARN] No JSON object/array found in response. Raw text snippet: {text[:200]}")
return None
json_str = text[start:end+1]
# Fix common AI JSON mistakes
json_str = re.sub(r',\s*([}\]])', r'\1', json_str) # trailing commas
try:
data = json.loads(json_str)
return data
except json.JSONDecodeError as e:
print(f" ⚠️ JSON parse error: {e}")
print(f" [WARN] JSON parse error: {e}")
print(f" Raw snippet: {json_str[:300]}")
return None
if not isinstance(data, list):
print(f" ⚠️ Expected JSON array, got {type(data)}")
return None
cabinets = []
for i, item in enumerate(data, 1):
if not isinstance(item, dict):
continue
# Validate and normalize cabinet_type
cab_type = item.get("cabinet_type", "unknown").lower().strip()
if cab_type not in VALID_CABINET_TYPES:
# Try to map common variations
cab_type = _normalize_cabinet_type(cab_type)
width_mm = float(item.get("width_mm", 0) or 0)
height_mm = float(item.get("height_mm", 0) or 0)
depth_mm = float(item.get("depth_mm", 0) or 0)
# Apply standard defaults if missing
if height_mm == 0:
height_mm = _default_height(cab_type)
if depth_mm == 0:
depth_mm = _default_depth(cab_type)
confidence = float(item.get("confidence", 0.7))
confidence = max(0.0, min(1.0, confidence))
cabinets.append(CabinetItem(
item_num = item.get("item_num", i),
cabinet_type = cab_type,
width_mm = width_mm,
height_mm = height_mm,
depth_mm = depth_mm,
location = str(item.get("location", "")),
elevation_ref = item.get("elevation_ref", elevation_label),
confidence = confidence,
quantity = int(item.get("quantity", 1)),
is_ada = bool(item.get("is_ada", False)),
notes = str(item.get("notes", "")),
source = "gemini",
))
return cabinets
# (merge_results removed — single-model pipeline with Gemini)
# ══════════════════════════════════════════════════════════════════════════
# HELPERS
@@ -683,7 +785,7 @@ def _downscale_image_if_possible(image_bytes: bytes, target_dpi: int = 150) -> b
new_w = max(1, int(orig_w * scale))
new_h = max(1, int(orig_h * scale))
img_resized = img.resize((new_w, new_h), Image.LANCZOS)
img_resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
buf = _io.BytesIO()
img_resized.save(buf, format="PNG", optimize=True)
result = buf.getvalue()
@@ -703,72 +805,3 @@ def _downscale_image_if_possible(image_bytes: bytes, target_dpi: int = 150) -> b
return image_bytes
# ══════════════════════════════════════════════════════════════════════════
# QUICK TEST (no API needed — tests JSON parsing logic)
# ══════════════════════════════════════════════════════════════════════════
if __name__ == "__main__":
print("Testing JSON parser (no API key needed)...")
sample_response = """
```json
[
{
"item_num": 1,
"cabinet_type": "upper_wall",
"width_mm": 762,
"height_mm": 300,
"depth_mm": 330,
"location": "Left of range, Elevation A",
"elevation_ref": "ELEVATION A",
"confidence": 0.92,
"quantity": 1,
"is_ada": false,
"notes": ""
},
{
"item_num": 2,
"cabinet_type": "base",
"width_mm": 900,
"height_mm": 720,
"depth_mm": 600,
"location": "Sink base, Elevation A",
"elevation_ref": "ELEVATION A",
"confidence": 0.88,
"quantity": 1,
"is_ada": false,
"notes": "sink base cabinet"
},
{
"item_num": 3,
"cabinet_type": "appliance_space",
"width_mm": 610,
"height_mm": 720,
"depth_mm": 600,
"location": "Dishwasher slot",
"elevation_ref": "ELEVATION A",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "24\" dishwasher space — no cabinet"
}
]
```
"""
# Test parsing (no API key needed for this test)
classifier = object.__new__(CabinetVisionClassifier) # skip __init__
classifier.__class__ = CabinetVisionClassifier
cabinets = classifier._parse_cabinet_json(sample_response, "ELEVATION A")
if cabinets:
print(f"[PASS] Parsed {len(cabinets)} cabinets:")
for c in cabinets:
print(f" Item {c.item_num}: {c.cabinet_type:20s} {c.width_mm:.0f}mm "
f"confidence={c.confidence:.2f} code={c.code}")
else:
print("[FAIL] Parsing failed")
# Test type normalization
print("\n=== Type Normalization ===")
for raw in ["wall cabinet", "lower", "dishwasher", "tall_cabinet", "mirror"]:
print(f" '{raw}' → '{_normalize_cabinet_type(raw)}'")
+4
View File
@@ -0,0 +1,4 @@
from .models import *
from .parser import *
from .engines import *
from .bom_engine import *
+43
View File
@@ -0,0 +1,43 @@
import pandas as pd
from typing import Dict, Any
from .models import ProjectModel
class BOMEngine:
@staticmethod
def generate_bom(project: ProjectModel) -> pd.DataFrame:
"""
Reads directly from the BIM-lite model (bypassing all Shop Drawing hashing logic)
to generate a flat Bill of Materials suitable for Excel/ERP export.
"""
rows = []
for building in project.buildings:
for floor in building.floors:
for unit in floor.units:
for room in unit.rooms:
for cab in room.cabinets:
rows.append({
"Building": building.name,
"Unit": unit.name,
"Quantity": unit.quantity,
"Room": room.name,
"Item Type": "Cabinet",
"Description": cab.node_type,
"Width": cab.width,
"Height": cab.height,
"Depth": cab.depth,
"Notes": cab.metadata.get("notes", "")
})
for ct in room.countertops:
rows.append({
"Building": building.name,
"Unit": unit.name,
"Quantity": unit.quantity,
"Room": room.name,
"Item Type": "Countertop",
"Description": "Countertop Run",
"Width": ct.width,
"Height": ct.height,
"Depth": ct.depth,
"Notes": ct.metadata.get("notes", "")
})
return pd.DataFrame(rows)
+154
View File
@@ -0,0 +1,154 @@
from typing import Dict, Any, List, Optional
import hashlib
import json
from .models import RoomModel, CabinetNode, ApplianceNode, CountertopNode
class CabinetRules:
@staticmethod
def apply(room: RoomModel):
# Example rule: Standard base cabinet height is 34.5"
for cab in room.cabinets:
if 'base' in cab.node_type.lower() and cab.height == 0.0:
cab.height = 34.5
cab.metadata['height_source'] = 'default'
class CountertopRules:
@staticmethod
def apply(room: RoomModel):
# Example rule: Standard countertop overhang is 1.5"
for ct in room.countertops:
if ct.overhang is None:
ct.overhang = 1.5
ct.metadata['overhang_source'] = 'default'
class ManufacturingRulesEngine:
@staticmethod
def apply_rules(room: RoomModel):
CabinetRules.apply(room)
CountertopRules.apply(room)
# ADARules.apply(room)
# ApplianceRules.apply(room)
return room
class DiagnosticReport:
def __init__(self):
self.diagnostics = []
self.is_valid = True
def add(self, level: str, message: str):
self.diagnostics.append({"level": level, "message": message})
if level == "ERROR":
self.is_valid = False
class ValidationEngine:
@staticmethod
def validate_intent(room: RoomModel) -> DiagnosticReport:
"""Pre-placement: checks walls/openings/appliances only."""
report = DiagnosticReport()
if not room.walls:
report.add("ERROR", "No walls found in room")
return report
@staticmethod
def validate_placement(room: RoomModel) -> DiagnosticReport:
"""Post-placement: includes the room.cabinets empty-check, sink/DW logic, etc."""
report = DiagnosticReport()
# Check 1: Empty room
if not room.cabinets:
report.add("ERROR", "No cabinets found in room")
return report
# Check 2: Sink logic
has_sink_base = any('sink' in c.node_type.lower() or 'sb' in c.node_type.lower() for c in room.cabinets)
has_dishwasher = any('dw' in a.node_type.lower() or 'dishwasher' in a.node_type.lower() for a in room.appliances)
if room.name == "Kitchen" and not has_sink_base:
report.add("ERROR", "Kitchen missing sink base")
if room.name == "Kitchen" and has_sink_base and not has_dishwasher:
report.add("WARN", "Sink base present without adjacent dishwasher")
# Check 3: Check defaults
default_cts = sum(1 for ct in room.countertops if ct.metadata.get('overhang_source') == 'default')
if default_cts > 0:
report.add("WARN", f"Countertop overhang defaulted for {default_cts} runs")
# Add basic success
if report.is_valid:
report.add("INFO", "Room passes basic validation constraints")
return report
class ReviewEngine:
@staticmethod
def review(report: DiagnosticReport) -> bool:
# In a real system, this would halt and wait for human input if report.is_valid is False or has WARNs.
# For our automated pipeline, we'll auto-approve if valid.
return report.is_valid
class FingerprintBuilder:
@staticmethod
def build_canonical(room: RoomModel) -> Dict[str, Any]:
"""Separates Canonical Geometry from Canonical Metadata"""
geometry = {
"type": room.name,
"is_ada": room.is_ada,
"cabinets": [
{"type": c.node_type, "w": c.width, "h": c.height, "d": c.depth}
for c in room.cabinets
],
"appliances": [
{"type": a.node_type, "w": a.width, "h": a.height, "d": a.depth}
for a in room.appliances
],
"relationships": [
{"type": r.rel_type, "src": r.source_id, "tgt": r.target_id}
for r in room.relationships
]
}
metadata = {
"id": room.id,
"schema_version": "2.0",
"parser_version": "1.5",
"normalizer_version": "1.2",
"cabinet_metadata": {c.id: c.metadata for c in room.cabinets}
}
return {
"canonical_geometry": geometry,
"canonical_metadata": metadata
}
class NormalizationEngine:
@staticmethod
def normalize(geometry: Dict[str, Any]) -> Dict[str, Any]:
"""Quantizes dimensions (e.g. 36.02 -> 36.0)"""
# Very simple recursive normalizer
if isinstance(geometry, dict):
return {k: NormalizationEngine.normalize(v) for k, v in geometry.items()}
elif isinstance(geometry, list):
return [NormalizationEngine.normalize(v) for v in geometry]
elif isinstance(geometry, float):
# Quantize to 0.125
return round(geometry * 8) / 8
elif isinstance(geometry, str):
return geometry.lower().strip()
else:
return geometry
class SimilarityEngine:
@staticmethod
def get_hash(normalized_geometry: Dict[str, Any]) -> str:
sig_str = json.dumps(normalized_geometry, sort_keys=True)
return hashlib.sha256(sig_str.encode()).hexdigest()
@staticmethod
def compare(hash_a: str, hash_b: str) -> Dict[str, Any]:
# For Phase 3, this is an exact match system.
# Future phases will implement actual structural diffing here.
if hash_a == hash_b:
return {"match_percent": 100, "diff": "Exact match"}
return {"match_percent": 0, "diff": "Hashes do not match"}
+149
View File
@@ -0,0 +1,149 @@
from core.units import Length
import uuid
from typing import List, Dict, Any, Optional
class PersistentObject:
def __init__(self, obj_id: Optional[str] = None):
self.id = obj_id or f"obj_{uuid.uuid4().hex[:8]}"
class Relationship(PersistentObject):
def __init__(self, rel_type: str, source_id: str, target_id: str, obj_id: Optional[str] = None):
super().__init__(obj_id)
self.rel_type = rel_type
self.source_id = source_id
self.target_id = target_id
def to_dict(self):
return {
"type": self.rel_type,
"source_id": self.source_id,
"target_id": self.target_id
}
class GeometryNode(PersistentObject):
def __init__(self, node_type: str, width: float | Length, height: float | Length, depth: float | Length, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
super().__init__(obj_id)
self.node_type = node_type
self.width = width if isinstance(width, Length) else Length.from_inches(width)
self.height = height if isinstance(height, Length) else Length.from_inches(height)
self.depth = depth if isinstance(depth, Length) else Length.from_inches(depth)
self.metadata = metadata or {}
class CabinetNode(GeometryNode):
def __init__(self, cab_type: str, width: float | Length, height: float | Length, depth: float | Length, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
super().__init__(cab_type, width, height, depth, metadata, obj_id)
class ApplianceNode(GeometryNode):
def __init__(self, app_type: str, width: float | Length, height: float | Length, depth: float | Length, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
super().__init__(app_type, width, height, depth, metadata, obj_id)
class CountertopNode(GeometryNode):
def __init__(self, width: float | Length, depth: float | Length, overhang: Optional[float | Length] = None, splash: Optional[bool] = None, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
super().__init__("Countertop", width, 0.0, depth, metadata, obj_id)
self.overhang = overhang if overhang is None or isinstance(overhang, Length) else Length.from_inches(overhang)
self.splash = splash
class OpeningNode(GeometryNode):
def __init__(self, opening_type: str, width: float | Length, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
super().__init__(opening_type, width, 0.0, 0.0, metadata, obj_id)
class PlumbingFixtureNode(GeometryNode):
def __init__(self, fixture_type: str, width: float | Length, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
super().__init__(fixture_type, width, 0.0, 0.0, metadata, obj_id)
class StructuralElementNode(GeometryNode):
def __init__(self, elem_type: str, width: float | Length, depth: float | Length, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
super().__init__(elem_type, width, 0.0, depth, metadata, obj_id)
class ClearanceZoneNode(GeometryNode):
def __init__(self, zone_type: str, radius: float | Length, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
super().__init__(zone_type, radius*2, 0.0, radius*2, metadata, obj_id)
class WallModel(PersistentObject):
def __init__(self, name: str, length: float | Length, obj_id: Optional[str] = None):
super().__init__(obj_id)
self.name = name
self.length = length if isinstance(length, Length) else Length.from_inches(length)
self.cabinets: List[CabinetNode] = []
self.appliances: List[ApplianceNode] = []
self.countertops: List[CountertopNode] = []
self.openings: List[OpeningNode] = []
self.fixtures: List[PlumbingFixtureNode] = []
self.structural: List[StructuralElementNode] = []
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"length": self.length.inches,
"cabinets": [{"id": c.id, "type": c.node_type, "width": c.width.inches, "height": c.height.inches, "depth": c.depth.inches, "metadata": c.metadata} for c in self.cabinets],
"appliances": [{"id": a.id, "type": a.node_type, "width": a.width.inches, "metadata": a.metadata} for a in self.appliances],
"countertops": [{"id": ct.id, "type": ct.node_type, "width": ct.width.inches, "depth": ct.depth.inches, "metadata": ct.metadata} for ct in self.countertops],
"openings": [{"id": o.id, "type": o.node_type, "width": o.width.inches, "metadata": o.metadata} for o in self.openings],
"fixtures": [{"id": f.id, "type": f.node_type, "width": f.width.inches, "metadata": f.metadata} for f in self.fixtures],
"structural": [{"id": s.id, "type": s.node_type, "width": s.width.inches, "depth": s.depth.inches, "metadata": s.metadata} for s in self.structural],
}
class RoomModel(PersistentObject):
def __init__(self, name: str, is_ada: bool = False, obj_id: Optional[str] = None):
super().__init__(obj_id)
self.name = name
self.is_ada = is_ada
self.walls: List[WallModel] = []
self.clearances: List[ClearanceZoneNode] = []
self.relationships: List[Relationship] = []
@property
def cabinets(self) -> List[CabinetNode]:
return [c for w in self.walls for c in w.cabinets]
@property
def appliances(self) -> List[ApplianceNode]:
return [a for w in self.walls for a in w.appliances]
@property
def countertops(self) -> List[CountertopNode]:
return [ct for w in self.walls for ct in w.countertops]
def to_dict(self):
return {
"id": self.id,
"name": self.name,
"is_ada": self.is_ada,
"walls": [w.to_dict() for w in self.walls],
"clearances": [{"id": c.id, "type": c.node_type, "width": c.width.inches, "metadata": c.metadata} for c in self.clearances],
"relationships": [r.to_dict() for r in self.relationships]
}
class KitchenModel(RoomModel):
def __init__(self, is_ada: bool = False, obj_id: Optional[str] = None):
super().__init__("Kitchen", is_ada, obj_id)
class VanityModel(RoomModel):
def __init__(self, is_ada: bool = False, obj_id: Optional[str] = None):
super().__init__("Vanity", is_ada, obj_id)
class UnitModel(PersistentObject):
def __init__(self, name: str, quantity: int = 1, obj_id: Optional[str] = None):
super().__init__(obj_id)
self.name = name
self.quantity = quantity
self.rooms: List[RoomModel] = []
class FloorModel(PersistentObject):
def __init__(self, name: str, obj_id: Optional[str] = None):
super().__init__(obj_id)
self.name = name
self.units: List[UnitModel] = []
class BuildingModel(PersistentObject):
def __init__(self, name: str, obj_id: Optional[str] = None):
super().__init__(obj_id)
self.name = name
self.floors: List[FloorModel] = []
class ProjectModel(PersistentObject):
def __init__(self, name: str, obj_id: Optional[str] = None):
super().__init__(obj_id)
self.name = name
self.buildings: List[BuildingModel] = []
+73
View File
@@ -0,0 +1,73 @@
from typing import Dict, Any, List, Optional
from .models import (
ProjectModel, BuildingModel, FloorModel, UnitModel, KitchenModel, VanityModel,
RoomModel, WallModel, OpeningNode, ApplianceNode, PlumbingFixtureNode, StructuralElementNode, ClearanceZoneNode, Relationship
)
class GeometryParser:
"""Parses raw architectural data (simulated by JSON) into generic geometry nodes."""
@staticmethod
def parse(raw_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
return raw_data
class SemanticParser:
"""Assigns meaning to geometry nodes."""
@staticmethod
def parse(geometry_data: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
return geometry_data
class ModelBuilder:
"""Constructs the full BIM-lite hierarchy from Architectural Intent data."""
@staticmethod
def build_project(project_name: str, config: Dict[str, Any], units_schedules: Dict[str, Any], unit_totals: Dict[str, int]) -> ProjectModel:
project = ProjectModel(project_name)
buildings_config = config.get('buildings', {})
if not buildings_config:
buildings_config = {"Default Building": list(units_schedules.keys())}
for bldg_name, unit_names in buildings_config.items():
bldg = BuildingModel(bldg_name)
floor = FloorModel("Ground Floor") # default floor
bldg.floors.append(floor)
for unit_name in unit_names:
if unit_name in units_schedules:
schedule = units_schedules[unit_name]
unit = UnitModel(unit_name, quantity=unit_totals.get(unit_name, 1))
# Separate elevations into Kitchen and Bathrooms
kitchen = KitchenModel(is_ada=schedule.is_ada)
bathroom = VanityModel(is_ada=schedule.is_ada)
for elevation in schedule.elevations:
is_bath = "BATH" in elevation.elevation_label.upper() or "VANITY" in elevation.elevation_label.upper()
target_room = bathroom if is_bath else kitchen
for w_intent in elevation.walls:
wall = WallModel(name=w_intent.name, length=w_intent.length_in)
for o in elevation.openings:
wall.openings.append(OpeningNode(o.type, o.width_in, metadata={"height_in": o.height_in, "x_in": o.x_in, "sill_height_in": o.sill_height_in, "notes": o.notes}))
for a in elevation.appliances:
wall.appliances.append(ApplianceNode(a.type, a.width_in, a.height_in, 24.0, metadata={"x_in": a.x_in, "notes": a.notes}))
for f in elevation.fixtures:
wall.fixtures.append(PlumbingFixtureNode(f.type, f.width_in, metadata={"x_in": f.x_in, "notes": f.notes}))
for s in elevation.structural:
wall.structural.append(StructuralElementNode(s.type, s.width_in, s.depth_in, metadata={"x_in": s.x_in, "notes": s.notes}))
target_room.walls.append(wall)
for c in elevation.clearances:
target_room.clearances.append(ClearanceZoneNode(c.type, c.radius_in, metadata={"x_in": c.x_in, "notes": c.notes}))
if len(kitchen.walls) > 0:
unit.rooms.append(kitchen)
if len(bathroom.walls) > 0:
unit.rooms.append(bathroom)
floor.units.append(unit)
project.buildings.append(bldg)
return project
@@ -0,0 +1,21 @@
from typing import Dict, List
class DishwasherBlock:
@staticmethod
def elevation(x0: float, y0: float, width: float, height: float = 34.5, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "D/W", "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [x0, y1 - 4.0 * scale_y], "end": [x1, y1 - 4.0 * scale_y], "layer": "APPLIANCES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "D/W", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def plan(x0: float, y0: float, width: float, depth: float = 24.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "D/W", "layer": "APPLIANCES", "style": "dashed"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "D/W", "size": 4.5, "layer": "TEXT"})
return geom
@@ -0,0 +1,19 @@
from typing import Dict, List
class MicrowaveBlock:
@staticmethod
def elevation(x0: float, y0: float, width: float, height: float = 18.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "MW", "layer": "APPLIANCES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "MW/HOOD", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def plan(x0: float, y0: float, width: float, depth: float = 15.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "MW", "layer": "APPLIANCES", "style": "dashed"})
return geom
@@ -0,0 +1,29 @@
from typing import Dict, List
class RangeBlock:
@staticmethod
def elevation(x0: float, y0: float, width: float, height: float = 36.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "RANGE", "layer": "APPLIANCES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "RANGE", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def plan(x0: float, y0: float, width: float, depth: float = 25.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "RANGE", "layer": "APPLIANCES", "style": "solid"})
# Draw 4 burners
r = 3.0 * scale_x
cx1, cy1 = x0 + (width * 0.25) * scale_x, y0 + (depth * 0.3) * scale_y
cx2, cy2 = x0 + (width * 0.75) * scale_x, y0 + (depth * 0.3) * scale_y
cx3, cy3 = x0 + (width * 0.25) * scale_x, y0 + (depth * 0.7) * scale_y
cx4, cy4 = x0 + (width * 0.75) * scale_x, y0 + (depth * 0.7) * scale_y
for c in [(cx1, cy1), (cx2, cy2), (cx3, cy3), (cx4, cy4)]:
geom["blocks"].append({"type": "circle", "coords": [c[0], c[1], r], "layer": "APPLIANCES", "style": "solid"})
return geom
@@ -0,0 +1,53 @@
from typing import Dict, List
class RefrigeratorBlock:
"""Modular block definition for Refrigerator geometry."""
@staticmethod
def elevation(x0: float, y0: float, width: float, height: float = 72.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
# Main body
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "REF", "layer": "APPLIANCES", "style": "solid"
})
# Doors divide
mid_x = x0 + (width / 2.0) * scale_x
geom["lines"].append({"start": [mid_x, y0], "end": [mid_x, y1], "layer": "APPLIANCES", "style": "solid"})
# Handles
h_start_y = y0 + 30.0 * scale_y
h_end_y = y0 + 48.0 * scale_y
geom["lines"].append({"start": [mid_x - 1.5 * scale_x, h_start_y], "end": [mid_x - 1.5 * scale_x, h_end_y], "layer": "FIXTURES", "style": "solid"})
geom["lines"].append({"start": [mid_x + 1.5 * scale_x, h_start_y], "end": [mid_x + 1.5 * scale_x, h_end_y], "layer": "FIXTURES", "style": "solid"})
# Text
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "REF", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def plan(x0: float, y0: float, width: float, depth: float = 30.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
# Main body
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "REF", "layer": "APPLIANCES", "style": "solid"
})
# Door thickness indication in plan
geom["lines"].append({"start": [x0, y0 + 2.0 * scale_y], "end": [x1, y0 + 2.0 * scale_y], "layer": "APPLIANCES", "style": "solid"})
# Text
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "REF", "size": 4.5, "layer": "TEXT"})
return geom
@@ -0,0 +1,42 @@
from typing import Dict, List
class CabinetBaseBlock:
@staticmethod
def elevation(x0: float, y0: float, width: float, height: float = 34.5, depth: float = 24.0, doors: int = 1, drawers: int = 1, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
# Main box
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "layer": "CABINETS_BASE", "style": "solid"})
# Toe kick
tk_h = 4.5 * scale_y
geom["lines"].append({"start": [x0, y0 + tk_h], "end": [x1, y0 + tk_h], "layer": "CABINETS_BASE", "style": "solid"})
# Drawer section
dr_h = 6.0 * scale_y
if drawers > 0:
geom["lines"].append({"start": [x0, y1 - dr_h], "end": [x1, y1 - dr_h], "layer": "CABINETS_BASE", "style": "solid"})
# Door splits
if doors > 1:
w_door = (width / doors) * scale_x
for i in range(1, doors):
dx = x0 + w_door * i
geom["lines"].append({"start": [dx, y0 + tk_h], "end": [dx, y1 - dr_h if drawers > 0 else y1], "layer": "CABINETS_BASE", "style": "solid"})
# Swing diagonals
if doors == 1:
geom["lines"].append({"start": [x0, y0 + tk_h], "end": [x1, y1 - dr_h if drawers > 0 else y1], "layer": "CABINETS_BASE", "style": "dashed"})
geom["lines"].append({"start": [x1, y0 + tk_h], "end": [x0, y1 - dr_h if drawers > 0 else y1], "layer": "CABINETS_BASE", "style": "dashed"})
return geom
@staticmethod
def plan(x0: float, y0: float, width: float, depth: float = 24.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "layer": "CABINETS_BASE", "style": "solid"})
return geom
@@ -0,0 +1,31 @@
from typing import Dict, List
class CabinetUpperBlock:
@staticmethod
def elevation(x0: float, y0: float, width: float, height: float = 30.0, doors: int = 1, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "layer": "CABINETS_UPPER", "style": "solid"})
if doors > 1:
w_door = (width / doors) * scale_x
for i in range(1, doors):
dx = x0 + w_door * i
geom["lines"].append({"start": [dx, y0], "end": [dx, y1], "layer": "CABINETS_UPPER", "style": "solid"})
# Swing diagonals (dashed)
if doors == 1:
geom["lines"].append({"start": [x0, y0], "end": [x1, y1], "layer": "CABINETS_UPPER", "style": "dashed"})
geom["lines"].append({"start": [x1, y0], "end": [x0, y1], "layer": "CABINETS_UPPER", "style": "dashed"})
return geom
@staticmethod
def plan(x0: float, y0: float, width: float, depth: float = 12.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "layer": "CABINETS_UPPER", "style": "dashed"})
return geom
@@ -0,0 +1,31 @@
from typing import Dict, List
class PantryBlock:
@staticmethod
def elevation(x0: float, y0: float, width: float, height: float = 84.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "layer": "CABINETS_TALL", "style": "solid"})
tk_h = 4.5 * scale_y
geom["lines"].append({"start": [x0, y0 + tk_h], "end": [x1, y0 + tk_h], "layer": "CABINETS_TALL", "style": "solid"})
# Split upper/lower doors at typical height
split_y = y0 + 54.0 * scale_y
if split_y < y1:
geom["lines"].append({"start": [x0, split_y], "end": [x1, split_y], "layer": "CABINETS_TALL", "style": "solid"})
return geom
@staticmethod
def plan(x0: float, y0: float, width: float, depth: float = 24.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "layer": "CABINETS_TALL", "style": "solid"})
# Crossed lines to indicate tall
geom["lines"].append({"start": [x0, y0], "end": [x1, y1], "layer": "CABINETS_TALL", "style": "solid"})
geom["lines"].append({"start": [x1, y0], "end": [x0, y1], "layer": "CABINETS_TALL", "style": "solid"})
return geom
@@ -0,0 +1,11 @@
from typing import Dict, List
class FaucetBlock:
@staticmethod
def plan(x0: float, y0: float, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
# simple circle for base
geom["blocks"].append({"type": "circle", "coords": [x0, y0, 1.0*scale_x], "layer": "FIXTURES", "style": "solid"})
# spout line
geom["lines"].append({"start": [x0, y0], "end": [x0, y0 - 4.0*scale_y], "layer": "FIXTURES", "style": "solid"})
return geom
@@ -0,0 +1,16 @@
from typing import Dict, List
class SinkBlock:
@staticmethod
def plan(x0: float, y0: float, width: float = 30.0, depth: float = 18.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "SINK", "layer": "FIXTURES", "style": "solid"})
# Inner bowl
geom["blocks"].append({"type": "rect", "coords": [x0 + 1.5*scale_x, y0 + 1.5*scale_y, (width-3)*scale_x, (depth-3)*scale_y], "layer": "FIXTURES", "style": "solid"})
# Drain
geom["blocks"].append({"type": "circle", "coords": [(x0+x1)/2, (y0+y1)/2, 1.5*scale_x], "layer": "FIXTURES", "style": "solid"})
return geom
@@ -0,0 +1,11 @@
from typing import Dict, List
class ToiletBlock:
@staticmethod
def plan(x0: float, y0: float, width: float = 20.0, depth: float = 28.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "WC", "layer": "FIXTURES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "WC", "size": 4.5, "layer": "TEXT"})
return geom
@@ -0,0 +1,11 @@
from typing import Dict, List
class TubBlock:
@staticmethod
def plan(x0: float, y0: float, width: float = 60.0, depth: float = 30.0, scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({"type": "rect", "coords": [x0, y0, x1 - x0, y1 - y0], "id": "TUB", "layer": "FIXTURES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "TUB", "size": 4.5, "layer": "TEXT"})
return geom
@@ -0,0 +1,10 @@
from typing import Dict, List
class ElevationMarkerBlock:
@staticmethod
def draw(x0: float, y0: float, label: str = "1", scale: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
r = 3.0 * scale
geom["blocks"].append({"type": "circle", "coords": [x0, y0, r], "layer": "ANNOTATIONS", "style": "solid"})
geom["texts"].append({"pos": [x0, y0], "text": label, "size": 4.0 * scale, "layer": "TEXT"})
return geom
@@ -0,0 +1,11 @@
from typing import Dict, List
class NorthArrowBlock:
@staticmethod
def draw(x0: float, y0: float, scale: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
r = 5.0 * scale
geom["blocks"].append({"type": "circle", "coords": [x0, y0, r], "layer": "ANNOTATIONS", "style": "solid"})
geom["lines"].append({"start": [x0, y0 - r], "end": [x0, y0 + r*1.5], "layer": "ANNOTATIONS", "style": "solid"})
geom["texts"].append({"pos": [x0, y0 + r*2], "text": "N", "size": 5.0 * scale, "layer": "TEXT"})
return geom
@@ -0,0 +1,19 @@
from typing import Dict, List
class SectionMarkerBlock:
@staticmethod
def draw(x0: float, y0: float, direction: str = "UP", label: str = "A", scale: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
r = 4.0 * scale
geom["blocks"].append({"type": "circle", "coords": [x0, y0, r], "layer": "SECTION_MARKERS", "style": "solid"})
# Line cutting through
geom["lines"].append({"start": [x0 - r*2, y0], "end": [x0 + r*2, y0], "layer": "SECTION_MARKERS", "style": "solid"})
# Triangle pointer
if direction == "UP":
geom["lines"].append({"start": [x0 - r, y0], "end": [x0, y0 + r*1.5], "layer": "SECTION_MARKERS", "style": "solid"})
geom["lines"].append({"start": [x0, y0 + r*1.5], "end": [x0 + r, y0], "layer": "SECTION_MARKERS", "style": "solid"})
geom["texts"].append({"pos": [x0, y0 - r*0.5], "text": label, "size": 4.5 * scale, "layer": "TEXT"})
return geom
@@ -0,0 +1,313 @@
"""
===========================================================================
core/cabinet_graph_builder.py — Spatial Layout Graph Builder
===========================================================================
Constructs the spatial layout graph of cabinets, appliances, and openings.
Calculates offsets, identifies adjacency, and builds the target schemas.
Invariant: base-vs-upper is a first-class field all the way to the output.
Each cabinet dict carries a "tier" key ("base" | "upper") and the wall
dict uses two separate keys — "cabinets" (base run) and "uppers" (upper
run) — matching the shape of project_config.json and _draw_elevation_view.
The merged flat-list that discarded tier info has been removed.
===========================================================================
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from core.ai_vision_classifier import CabinetItem, ElevationResult
class CabinetGraphBuilder:
"""
Constructs spatial relationship graphs from elevation classification results
and builds the standard deliverables.
"""
def __init__(self):
pass
def build_shop_drawing_schema(
self,
unit_type: str,
elevations: list[ElevationResult],
kitchen_type: str,
bathroom_type: str,
layout_shape: str = "straight"
) -> dict:
"""
Builds the shop drawing JSON schema.
"""
walls_list = []
appliances_list = []
ceiling_height = 108.0
for ev in elevations:
# Standardize wall label name from elevation label
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
# If the label is KITCHEN or BATH, use a friendly shorthand
if wall_name.upper() in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
wall_name = "A"
# Parse ceiling height if reported
if ev.ceiling_height_in is not None:
ceiling_height = ev.ceiling_height_in
# Build wall info
# 1. Base run sequence
# Standardize cabinet items
base_items = []
upper_items = []
for cab in ev.cabinets:
# convert width_in to inches
w_in = round(cab.width_in)
h_in = round(cab.height_in)
d_in = round(cab.depth_in)
cid = cab.cabinet_id or cab.code
cab_dict = {
"id": cid,
"type": cab.cabinet_type,
"width": w_in,
"height": h_in,
"depth": d_in,
"cabinet_type": cab.cabinet_type,
"notes": cab.notes,
"is_ada": cab.is_ada
}
if cab.cabinet_type in ("upper_wall", "microwave_shelf", "corner_upper", "medicine_cabinet"):
upper_items.append(cab_dict)
else:
base_items.append(cab_dict)
# ── Tier 1: base run — cursor from x=0 ───────────────────────
base_x = 0
tall_right_x = 0 # right edge of REF/tall column (upper cursor origin)
sequenced_base_cabs = []
for b in base_items:
b["x"] = base_x
b["tier"] = "base" # ← preserve tier all the way to output
sequenced_base_cabs.append(b)
# Track REF/tall right edge so upper cursor starts correctly
is_tall = any(kw in (b.get("cabinet_type", "") + b["id"]).lower()
for kw in ("ref", "tall", "pantry", "refrigerator"))
if is_tall:
tall_right_x = max(tall_right_x, base_x + b["width"])
# Appliance spaces → also add to the appliances list
if b["type"] == "appliance_space" or b["cabinet_type"] == "appliance_space":
app_type = "REF"
for t in ["REF", "DW", "RANGE", "MIC", "HOOD", "OVEN"]:
if t in b["notes"].upper() or t in b["id"].upper():
app_type = t
break
appliances_list.append({
"type": app_type,
"wall": wall_name,
"x": base_x,
"width": b["width"]
})
base_x += b["width"]
# ── Tier 2: upper run — cursor starts at REF/tall right edge ─
# (matches ElevationLayout.build_two_tier() behaviour)
upper_x = tall_right_x
sequenced_upper_cabs = []
for u in upper_items:
u["x"] = upper_x
u["tier"] = "upper" # ← preserve tier all the way to output
sequenced_upper_cabs.append(u)
upper_x += u["width"]
# ── Emit two separate lists (base/uppers) not one merged list ─
# Shape matches project_config.json and _draw_elevation_view so
# all downstream consumers see "cabinets" (base) + "uppers" (upper)
# and can distinguish the two tiers without ambiguity.
base_output = [
{
"id": c["id"],
"x": c["x"],
"width": c["width"],
"height": c["height"],
"tier": "base",
}
for c in sequenced_base_cabs
if c["type"] != "appliance_space"
]
upper_output = [
{
"id": c["id"],
"x": c["x"],
"width": c["width"],
"height": c["height"],
"tier": "upper",
}
for c in sequenced_upper_cabs
if c["type"] != "appliance_space"
]
# Process openings
doors_output = []
for d in ev.doors:
doors_output.append({
"x": d.get("x_in", 0),
"width": d.get("width_in", 36),
"height": d.get("height_in", 80)
})
windows_output = []
for w in ev.windows:
windows_output.append({
"x": w.get("x_in", 0),
"width": w.get("width_in", 36),
"height": w.get("height_in", 48),
"sill_height": w.get("sill_height_in", 36)
})
# wall_length = base run end (authoritative).
# Do NOT use max(base_x, upper_x): upper_x starts at tall_right_x
# and its final value exceeds wall bounds if uppers fill past the base run.
wall_length = base_x
if wall_length == 0:
wall_length = 90.0 # default wall length
walls_list.append({
"name": wall_name,
"length": wall_length,
"doors": doors_output,
"windows": windows_output,
"cabinets": base_output, # base run
"uppers": upper_output, # upper run — separate key, not merged
})
# Try to parse appliances list directly from elevations if none added from base run
if not appliances_list:
for ev in elevations:
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
if wall_name.upper() in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
wall_name = "A"
for app in ev.appliances:
appliances_list.append({
"type": getattr(app, "type", "REF"),
"wall": wall_name,
"x": getattr(app, "x_in", 0),
"width": getattr(app, "width_in", 36)
})
# Normalize layout shape
layout_map = {
"K1": "single_wall",
"K2": "l_shape",
"K3": "galley"
}
layout_name = layout_map.get(kitchen_type, layout_shape.lower())
return {
"unit": unit_type,
"kitchen_type": kitchen_type,
"layout": layout_name,
"ceiling_height": ceiling_height,
"walls": walls_list,
"appliances": appliances_list
}
def build_cost_schema(
self,
unit_type: str,
elevations: list[ElevationResult],
is_ada: bool = False
) -> dict:
"""
Builds the cost estimation JSON schema.
"""
cabinets_summary = {}
fillers = []
panels = []
moldings = []
special_items = []
countertop_in = 0.0
upper_cabinet_in = 0.0
pantry_count = 0
has_island = False
for ev in elevations:
# Aggregate cabinets count
for cab in ev.cabinets:
w_in = round(cab.width_in)
cid = cab.cabinet_id or cab.code
# Check for special properties
if cab.cabinet_type == "pantry":
pantry_count += 1
if "island" in cab.location.lower() or "island" in cab.notes.lower():
has_island = True
# Skip appliance spaces and fillers in primary cabinet list
if cab.cabinet_type == "appliance_space":
continue
if cab.cabinet_type == "filler":
# track filler keynotes (e.g. F3)
fillers.append(cid)
continue
cabinets_summary[cid] = cabinets_summary.get(cid, 0) + cab.quantity
# Calculate linear feet dimensions
if cab.cabinet_type in ("upper_wall", "microwave_shelf", "corner_upper"):
upper_cabinet_in += w_in * cab.quantity
elif cab.cabinet_type in ("base", "sink_base", "dw_adjacent", "vanity"):
countertop_in += w_in * cab.quantity
# Gather other filler/panel/molding lists from elevation metadata
for f in ev.fillers:
if f not in fillers:
fillers.append(f)
for p in ev.panels:
if p not in panels:
panels.append(p)
for m in ev.moldings:
if m not in moldings:
moldings.append(m)
# Build final cabinet list format
cabinets_list = [
{"code": code, "qty": qty}
for code, qty in sorted(cabinets_summary.items())
]
# Calculate linear feet (inches / 12)
countertop_lf = round(countertop_in / 12.0, 1)
upper_cabinet_lf = round(upper_cabinet_in / 12.0, 1)
# Detect special items
if is_ada:
special_items.append("ADA")
if pantry_count > 0:
special_items.append("Pantry")
if has_island:
special_items.append("Island")
# Determine installation complexity
total_boxes = sum(c["qty"] for c in cabinets_list)
if has_island or (pantry_count > 0 and is_ada) or total_boxes > 15:
complexity = "high"
elif total_boxes >= 8 or is_ada:
complexity = "medium"
else:
complexity = "low"
return {
"unit_type": unit_type,
"cabinets": cabinets_list,
"countertop_lf": countertop_lf,
"upper_cabinet_lf": upper_cabinet_lf,
"fillers": fillers,
"panels": panels,
"moldings": moldings,
"special_items": special_items,
"installation_complexity": complexity
}
+57 -57
View File
@@ -6,9 +6,9 @@
grade sanity checks to validate the output before auto-approving.
Validation rules:
1. All widths must be within ±25mm of a standard catalog size
2. Total cabinet run width must ≤ room width + 50mm tolerance
3. Base cabinet height: 720mm (or 864mm for ADA)
1. All widths must be within ±25in of a standard catalog size
2. Total cabinet run width must ≤ room width + 50in tolerance
3. Base cabinet height: 720in (or 864in for ADA)
4. Every kitchen elevation must have ≥ 1 base + ≥ 1 upper
5. No two corner cabinets side-by-side
6. Confidence score per item must be ≥ 0.70 to auto-approve
@@ -26,9 +26,9 @@ from dataclasses import dataclass, field
from typing import Optional
from core.config import (
STANDARD_WIDTHS_MM, CABINET_WIDTH_TOLERANCE_MM,
ROOM_WIDTH_TOLERANCE_MM, AUTO_APPROVE_CONFIDENCE,
BASE_CABINET_HEIGHT_STD_MM, BASE_CABINET_HEIGHT_ADA_MM,
STANDARD_WIDTHS_IN, CABINET_WIDTH_TOLERANCE_IN,
ROOM_WIDTH_TOLERANCE_IN, AUTO_APPROVE_CONFIDENCE,
BASE_CABINET_HEIGHT_STD_IN, BASE_CABINET_HEIGHT_ADA_IN,
)
from core.ai_vision_classifier import CabinetItem
@@ -67,13 +67,13 @@ class CabinetValidator:
Usage:
validator = CabinetValidator()
result = validator.validate(cabinets, room_width_mm=4267.2, is_ada=False)
result = validator.validate(cabinets, room_width_in=168.0, is_ada=False)
"""
def validate(
self,
cabinets: list[CabinetItem],
room_width_mm: Optional[float] = None,
room_width_in: Optional[float] = None,
is_ada: bool = False,
location: str = "unknown", # for logging
) -> list[CabinetItem]:
@@ -82,7 +82,7 @@ class CabinetValidator:
Returns corrected cabinets (in-place modifications).
Also prints validation report.
"""
result = self.get_validation_result(cabinets, room_width_mm, is_ada, location)
result = self.get_validation_result(cabinets, room_width_in, is_ada, location)
print(f"\n Validation [{location}]: {result.summary}")
for flag in result.flags:
@@ -97,7 +97,7 @@ class CabinetValidator:
def get_validation_result(
self,
cabinets: list[CabinetItem],
room_width_mm: Optional[float] = None,
room_width_in: Optional[float] = None,
is_ada: bool = False,
location: str = "unknown",
) -> ValidationResult:
@@ -132,49 +132,49 @@ class CabinetValidator:
if cab.cabinet_type == "appliance_space":
continue # appliances are fine with non-standard widths
# Auto-fix: width=0 means Gemini couldn't read it → snap to 762mm default
if cab.width_mm <= 0:
old_w = cab.width_mm
cab.width_mm = 762.0 # 30" — most common standard cabinet width
# Auto-fix: width=0 means Gemini couldn't read it → snap to 762in default
if cab.width_in <= 0:
old_w = cab.width_in
cab.width_in = 30.0 # 30" — most common standard cabinet width
corrections.append(
f"Item {cab.item_num} ({cab.cabinet_type}) had width={old_w:.0f}mm "
f"→ defaulted to 762mm (30\"). Verify against drawing."
f"Item {cab.item_num} ({cab.cabinet_type}) had width={old_w:.0f}in "
f"→ defaulted to 762in (30\"). Verify against drawing."
)
warnings.append(
f"Item {cab.item_num} width was 0/null — used 762mm default"
f"Item {cab.item_num} width was 0/null — used 30in default"
)
nearest, delta = _nearest_standard_width(cab.width_mm)
if delta > CABINET_WIDTH_TOLERANCE_MM:
nearest, delta = _nearest_standard_width(cab.width_in)
if delta > CABINET_WIDTH_TOLERANCE_IN:
flags.append(
f"Item {cab.item_num} ({cab.cabinet_type}) width "
f"{cab.width_mm:.0f}mm is {delta:.0f}mm from nearest "
f"standard ({nearest:.0f}mm)"
f"{cab.width_in:.0f}in is {delta:.0f}in from nearest "
f"standard ({nearest:.0f}in)"
)
elif delta > 5:
# Auto-correct small deviations
old_w = cab.width_mm
cab.width_mm = nearest
old_w = cab.width_in
cab.width_in = nearest
corrections.append(
f"Item {cab.item_num} width snapped "
f"{old_w:.0f}→{nearest:.0f}mm"
f"{old_w:.0f}→{nearest:.0f}in"
)
# ── Check 3: Height correctness ───────────────────────────────────
expected_base_h = BASE_CABINET_HEIGHT_ADA_MM if is_ada else BASE_CABINET_HEIGHT_STD_MM
expected_base_h = BASE_CABINET_HEIGHT_ADA_IN if is_ada else BASE_CABINET_HEIGHT_STD_IN
BASE_TYPES = {"base", "sink_base", "dw_adjacent", "corner_base"}
for cab in cabinets:
if cab.cabinet_type in BASE_TYPES and cab.height_mm > 0:
if is_ada and cab.height_mm > BASE_CABINET_HEIGHT_ADA_MM + 50:
if cab.cabinet_type in BASE_TYPES and cab.height_in > 0:
if is_ada and cab.height_in > BASE_CABINET_HEIGHT_ADA_IN + 2.0:
flags.append(
f"Item {cab.item_num} ADA base height {cab.height_mm:.0f}mm "
f"exceeds ADA max {BASE_CABINET_HEIGHT_ADA_MM:.0f}mm"
f"Item {cab.item_num} ADA base height {cab.height_in:.0f}in "
f"exceeds ADA max {BASE_CABINET_HEIGHT_ADA_IN:.0f}in"
)
elif not is_ada and abs(cab.height_mm - BASE_CABINET_HEIGHT_STD_MM) > 80:
elif not is_ada and abs(cab.height_in - BASE_CABINET_HEIGHT_STD_IN) > 3.0:
warnings.append(
f"Item {cab.item_num} base height {cab.height_mm:.0f}mm "
f"differs from standard {BASE_CABINET_HEIGHT_STD_MM:.0f}mm"
f"Item {cab.item_num} base height {cab.height_in:.0f}in "
f"differs from standard {BASE_CABINET_HEIGHT_STD_IN:.0f}in"
)
# ── Check 4: At least 1 base + 1 upper in kitchen elevation ───────
@@ -193,18 +193,18 @@ class CabinetValidator:
warnings.append("No base cabinets detected — verify elevation is kitchen")
# ── Check 5: Total width vs. room width ───────────────────────────
if room_width_mm and room_width_mm > 0:
total_run = sum(c.width_mm for c in cabinets)
delta = total_run - room_width_mm
if delta > ROOM_WIDTH_TOLERANCE_MM:
if room_width_in and room_width_in > 0:
total_run = sum(c.width_in for c in cabinets)
delta = total_run - room_width_in
if delta > ROOM_WIDTH_TOLERANCE_IN:
flags.append(
f"Total cabinet run {total_run:.0f}mm exceeds "
f"room width {room_width_mm:.0f}mm by {delta:.0f}mm"
f"Total cabinet run {total_run:.0f}in exceeds "
f"room width {room_width_in:.0f}in by {delta:.0f}in"
)
elif delta < -(ROOM_WIDTH_TOLERANCE_MM * 3):
elif delta < -(ROOM_WIDTH_TOLERANCE_IN * 3):
warnings.append(
f"Total cabinet run {total_run:.0f}mm is significantly less "
f"than room width {room_width_mm:.0f}mm — may be missing items"
f"Total cabinet run {total_run:.0f}in is significantly less "
f"than room width {room_width_in:.0f}in — may be missing items"
)
# ── Check 6: No consecutive corner cabinets ───────────────────────
@@ -241,24 +241,24 @@ class CabinetValidator:
# HELPERS
# ══════════════════════════════════════════════════════════════════════════
def _nearest_standard_width(width_mm: float) -> tuple[float, float]:
"""Return (nearest_standard_mm, delta_mm)."""
if not STANDARD_WIDTHS_MM:
return width_mm, 0.0
nearest = min(STANDARD_WIDTHS_MM, key=lambda s: abs(s - width_mm))
return nearest, abs(nearest - width_mm)
def _nearest_standard_width(width_in: float) -> tuple[float, float]:
"""Return (nearest_standard_in, delta_in)."""
if not STANDARD_WIDTHS_IN:
return width_in, 0.0
nearest = min(STANDARD_WIDTHS_IN, key=lambda s: abs(s - width_in))
return nearest, abs(nearest - width_in)
def validate_schedule(
cabinets: list[CabinetItem],
room_width_mm: Optional[float] = None,
room_width_in: Optional[float] = None,
is_ada: bool = False,
location: str = "unknown",
) -> tuple[list[CabinetItem], ValidationResult]:
"""Convenience wrapper. Returns (corrected_cabinets, validation_result)."""
validator = CabinetValidator()
result = validator.get_validation_result(cabinets, room_width_mm, is_ada, location)
corrected = validator.validate(cabinets, room_width_mm, is_ada, location)
result = validator.get_validation_result(cabinets, room_width_in, is_ada, location)
corrected = validator.validate(cabinets, room_width_in, is_ada, location)
return corrected, result
@@ -270,18 +270,18 @@ if __name__ == "__main__":
# Sample cabinet schedule for Unit A1 - Elevation A
test_cabinets = [
CabinetItem(1, "upper_wall", 762.0, 300.0, 330.0, "Left of range", "ELEVATION A", 0.92),
CabinetItem(2, "upper_wall", 900.0, 300.0, 330.0, "Right of range","ELEVATION A", 0.88),
CabinetItem(3, "microwave_shelf", 300.0, 460.0, 330.0, "Over range", "ELEVATION A", 0.85),
CabinetItem(4, "base", 762.0, 720.0, 600.0, "Left base", "ELEVATION A", 0.95),
CabinetItem(5, "appliance_space", 610.0, 720.0, 600.0, "DW space", "ELEVATION A", 0.98),
CabinetItem(6, "base", 900.0, 720.0, 600.0, "Right base", "ELEVATION A", 0.91),
CabinetItem(1, "upper_wall", 30.0, 12.0, 13.0, "Left of range", "ELEVATION A", 0.92),
CabinetItem(2, "upper_wall", 36.0, 12.0, 13.0, "Right of range","ELEVATION A", 0.88),
CabinetItem(3, "microwave_shelf", 12.0, 18.0, 13.0, "Over range", "ELEVATION A", 0.85),
CabinetItem(4, "base", 30.0, 34.5, 24.0, "Left base", "ELEVATION A", 0.95),
CabinetItem(5, "appliance_space", 24.0, 34.5, 24.0, "DW space", "ELEVATION A", 0.98),
CabinetItem(6, "base", 36.0, 34.5, 24.0, "Right base", "ELEVATION A", 0.91),
]
validator = CabinetValidator()
result = validator.get_validation_result(
test_cabinets,
room_width_mm=4267.2, # 14'
room_width_in=168.0, # 14'
is_ada=False,
location="Unit A1 Elevation A",
)
@@ -0,0 +1,75 @@
"""
===========================================================================
core/ceiling_height_extractor.py — Ceiling & Soffit Height Extractor
===========================================================================
Parses drawing annotations for ceiling heights and dropped bulkheads.
===========================================================================
"""
from __future__ import annotations
import re
from typing import Optional, List, Dict
from core.pdf_extractor import TextSpan
class CeilingHeightExtractor:
"""
Parses ceiling elevations and soffit bounds from details annotations.
"""
@staticmethod
def extract_heights(spans: list[TextSpan]) -> dict:
"""
Scan page text spans and extract ceiling_height and soffit_height.
Returns values in inches (default: ceiling=108, soffit=None).
"""
ceiling_height = 108.0 # default 9'
soffit_height = None
# Sort spans top-to-bottom, left-to-right
sorted_spans = sorted(spans, key=lambda s: (s.y0, s.x0))
for idx, s in enumerate(sorted_spans):
t = s.text.upper()
# Look for ceiling keywords: CEILING, CLG, AFF
if "CEILING" in t or "CLG" in t or "AFF" in t or "SOFFIT" in t:
# Search nearby spans (prev/next 5 spans) for height matches
search_range = sorted_spans[max(0, idx-5):min(len(sorted_spans), idx+6)]
for neighbor in search_range:
nt = neighbor.text.upper()
height_in = CeilingHeightExtractor._parse_height(nt)
if height_in is not None:
if "SOFFIT" in t or "SOFFIT" in nt:
soffit_height = height_in
else:
ceiling_height = height_in
break
return {
"ceiling_height": ceiling_height,
"soffit_height": soffit_height or (ceiling_height - 12.0 if soffit_height is None else soffit_height)
}
@staticmethod
def _parse_height(text: str) -> Optional[float]:
"""
Helper to parse height specs e.g. 9'-0" clg or 8'-6" AFF to inches.
"""
# Match 9'-0" or 9'0" or 9'-6"
m_ft_in = re.search(r"(\d+)'\s*-?\s*(\d+)?\"?", text)
if m_ft_in:
ft = float(m_ft_in.group(1))
inch_val = float(m_ft_in.group(2)) if m_ft_in.group(2) else 0.0
return ft * 12 + inch_val
# Match 108" or 96 in
m_in = re.search(r"(\d+)\s*(?:\"|IN|INCHES)", text, re.IGNORECASE)
if m_in:
return float(m_in.group(1))
# Match 9 FT or 9FT
m_ft = re.search(r"(\d+)\s*(?:FT|FEET)", text, re.IGNORECASE)
if m_ft:
return float(m_ft.group(1)) * 12.0
return None
+68
View File
@@ -0,0 +1,68 @@
"""
===========================================================================
core/confidence_engine.py — QA Confidence Engine
===========================================================================
Runs rule-based validation checks on extracted metadata models to calculate
overall QA score and list warning items.
===========================================================================
"""
from __future__ import annotations
from typing import List, Dict, Any
from core.ai_vision_classifier import CabinetItem, ElevationResult
class ConfidenceEngine:
"""
Computes quality metrics and reports warning flags on takeoff outcomes.
"""
@staticmethod
def evaluate(elevation: ElevationResult) -> dict:
"""
Runs checks and returns:
{
"confidence_score": 0.85,
"needs_review": False,
"warnings": []
}
"""
warnings = []
cabinets = elevation.cabinets
# 1. Base confidence
base_confidence = elevation.avg_confidence if cabinets else 1.0
# 2. Check: Duplicate keynote ID
ids = [c.cabinet_id for c in cabinets if c.cabinet_id]
if len(ids) != len(set(ids)):
warnings.append("Duplicate keynote ID detected in same elevation run")
base_confidence -= 0.1
# 3. Check: Base/Upper alignment
base_count = sum(1 for c in cabinets if c.cabinet_type in ("base", "sink_base", "dw_adjacent"))
upper_count = sum(1 for c in cabinets if c.cabinet_type in ("upper_wall", "microwave_shelf"))
if base_count == 0 and upper_count > 0:
warnings.append("Elevation has upper cabinets but no matching base run support")
base_confidence -= 0.15
# 4. Check: ADA constraints
if elevation.is_ada:
for cab in cabinets:
if cab.cabinet_type in ("base", "sink_base", "vanity") and cab.height_mm > 864:
warnings.append(f"ADA Unit contains cabinet {cab.code} exceeding 864mm height limit")
base_confidence -= 0.1
# 5. Check: Sink/Range matching
sink_count = sum(1 for c in cabinets if c.cabinet_type == "sink_base")
if sink_count > 1:
warnings.append("Multiple sink base cabinets found in single run")
base_confidence -= 0.05
final_score = max(0.0, min(1.0, base_confidence))
needs_review = final_score < 0.80 or len(warnings) > 0
return {
"confidence_score": round(final_score, 2),
"needs_review": needs_review,
"warnings": warnings
}
+21 -18
View File
@@ -26,12 +26,15 @@ GEMINI_API_KEY: str = os.getenv("GEMINI_API_KEY", "")
GROQ_API_KEY: str = os.getenv("GROQ_API_KEY", "")
OPENROUTER_API_KEY: str = os.getenv("OPENROUTER_API_KEY", "")
# Legacy provider constants retained for older experiments; production vision
# extraction uses OpenRouter Gemini from core.ai_vision_classifier.
CLAUDE_MODEL = "claude-3-5-sonnet-20241022"
CLAUDE_MAX_TOKENS = 4096
CLAUDE_TEMPERATURE = 0.1
GPT4O_MODEL = "gpt-4o"
# Legacy provider constants retained for older experiments; production
# extraction uses OpenRouter Gemini from core.ai_vision_classifier
CLAUDE_MODEL = "claude-3-5-sonnet-20241022"
CLAUDE_MAX_TOKENS = 4096
CLAUDE_TEMPERATURE = 0.1
GPT4O_MODEL = "gpt-4o"
# Production vision extraction model
VISION_MODEL = "google/gemini-pro-vision"
# ── Currency & Unit Conversion ──────────────────────────────────────────────
EUR_USD_RATE: float = float(os.getenv("EUR_USD_RATE", "1.09"))
@@ -55,21 +58,21 @@ DEFAULT_MISC_ALLOWANCE: float = float(os.getenv("MISC_ALLOWANCE",
DEFAULT_CABINETS_PER_CONTAINER: int = int(os.getenv("CABINETS_PER_CONTAINER", "220"))
# ── Validation Thresholds ───────────────────────────────────────────────────
# Cabinet width must be within ±25mm of a standard catalog size to auto-approve
CABINET_WIDTH_TOLERANCE_MM = 25.0
# Total cabinet run must be within ±50mm of room width to auto-approve
ROOM_WIDTH_TOLERANCE_MM = 50.0
# Cabinet width must be within ±1 inch of a standard catalog size to auto-approve
CABINET_WIDTH_TOLERANCE_IN = 1.0
# Total cabinet run must be within ±2 inches of room width to auto-approve
ROOM_WIDTH_TOLERANCE_IN = 2.0
# AI confidence threshold for auto-approval (no human review needed)
AUTO_APPROVE_CONFIDENCE = 0.90
# Standard base cabinet height (non-ADA)
BASE_CABINET_HEIGHT_STD_MM = 720.0
# ADA base cabinet height (max 34" countertop)
BASE_CABINET_HEIGHT_ADA_MM = 864.0
BASE_CABINET_HEIGHT_STD_IN = 34.5
# ADA base cabinet height (max 34" countertop AFF — per drawings A.4, A.13 note
# "HEIGHT OF COUNTER TOP @ 34\" AFF")
BASE_CABINET_HEIGHT_ADA_IN = 34.0
# ── Standard Cabinet Widths (industry standard, in mm) ─────────────────────
STANDARD_WIDTHS_MM = [
150, 200, 250, 300, 350, 400, 450, 500, 550, 600,
610, 762, 900, 1050, 1200, 1500, # 24", 30", 35.4", 41.3", 47.2", 59"
# ── Standard Cabinet Widths (industry standard, in inches) ─────────────────────
STANDARD_WIDTHS_IN = [
6.0, 9.0, 12.0, 15.0, 18.0, 21.0, 24.0, 27.0, 30.0, 33.0, 36.0, 39.0, 42.0, 45.0, 48.0
]
# ── Region Detection Labels ─────────────────────────────────────────────────
@@ -146,7 +149,7 @@ if __name__ == "__main__":
for w in warnings:
print(f" • {w}")
else:
print("✅ Configuration OK")
print(" Configuration OK")
print(f"\n EUR/USD rate: {EUR_USD_RATE}")
print(f" OpenRouter key: {'SET' if OPENROUTER_API_KEY else 'NOT SET'}")
print(f" Auto-approve threshold: {AUTO_APPROVE_CONFIDENCE}")
+66
View File
@@ -0,0 +1,66 @@
"""
===========================================================================
core/config_loader.py — Config Schema Normalization
===========================================================================
Provides a strict Pydantic model for project configuration files to
handle schema drift (e.g., owner vs client_name).
===========================================================================
"""
import json
from pathlib import Path
from pydantic import BaseModel, Field
class ProjectConfig(BaseModel):
project_id: str
project_name: str
# Metadata mapped with aliases for backward compatibility
date: str = ""
revision: str = "1.0"
drawn_by: str = ""
checker: str = ""
owner: str = Field(default="", alias="client_name")
architect: str = ""
address: str = Field(default="", alias="project_address")
finish: str = Field(default="", alias="cabinet_finish")
door_style: str = ""
finish_tier: int = 1
# Pricing & Metrics
gp_target_pct: float = 0.35
commission_pct: float = 0.05
bond_pct: float = 0.015
price_list_tier: int = 1
eur_usd_rate: float = 1.09
price_list_path: str = ""
unit_plan_pdfs: dict[str, str] = Field(default_factory=dict)
buildings: dict[str, list[str]] | dict[str, dict] = Field(default_factory=dict)
class Config:
populate_by_name = True
extra = "allow"
def load_project_config(config_path: str | Path) -> dict:
"""Load and validate project configuration JSON, returning a normalized dict."""
config_path = Path(config_path)
if not config_path.exists():
raise FileNotFoundError(f"Project config not found: {config_path}")
with open(config_path, encoding="utf-8") as f:
raw_config = json.load(f)
# Map legacy keys if present
if "client_name" in raw_config and "owner" not in raw_config:
raw_config["owner"] = raw_config["client_name"]
if "cabinet_finish" in raw_config and "finish" not in raw_config:
raw_config["finish"] = raw_config["cabinet_finish"]
if "project_address" in raw_config and "address" not in raw_config:
raw_config["address"] = raw_config["project_address"]
# Validate with Pydantic
parsed = ProjectConfig(**raw_config)
# Return as dict for full backward compatibility in the pipeline
return parsed.model_dump(by_alias=False)
+22 -25
View File
@@ -70,8 +70,8 @@ _IMPERIAL_RE = re.compile(
)
# Valid cabinet width range in mm (2" to 72")
_MIN_CAB_MM = 50.0
_MAX_CAB_MM = 2000.0
_MIN_CAB_IN = 2.0
_MAX_CAB_IN = 2000.0
_VALID_CM_RANGE = (5.0, 350.0) # 5cm to 350cm = 50mm to 3500mm
@@ -82,7 +82,7 @@ _VALID_CM_RANGE = (5.0, 350.0) # 5cm to 350cm = 50mm to 3500mm
@dataclass
class ParsedDimension:
"""A single dimension value extracted from a text span."""
value_mm: float # canonical value in mm
value_in: float # canonical value in mm
source_text: str # original text e.g. "76.20" or "2' - 6\""
dim_type: str # "METRIC" | "IMPERIAL" | "FRACTION"
span_x: float # x-coordinate of span origin
@@ -96,11 +96,11 @@ class DimensionPair:
A cross-validated dimension — metric + imperial values for the same measurement.
When both are found and agree, confidence is HIGH.
"""
value_mm: float
value_in: float
metric_text: Optional[str]
imperial_text: Optional[str]
confidence: str # "HIGH" | "METRIC_ONLY" | "IMPERIAL_ONLY" | "MISMATCH"
mismatch_mm: Optional[float] = None # difference if mismatch
mismatch_in: Optional[float] = None # difference if mismatch
@dataclass
@@ -163,9 +163,8 @@ def parse_imperial_mm(text: str) -> Optional[float]:
frac_den = int(bracket_m.group(4) or 1)
frac = frac_num / frac_den if frac_den else 0
total_inches = feet * 12 + inches + frac
mm = total_inches * 25.4
if _MIN_CAB_MM <= mm <= _MAX_CAB_MM * 3:
return mm
if _MIN_CAB_IN <= total_inches <= _MAX_CAB_IN * 3:
return total_inches * 25.4
return None
# Feet + inches form: "2' - 6\""
@@ -179,24 +178,22 @@ def parse_imperial_mm(text: str) -> Optional[float]:
frac_den = int(fi_m.group(4) or 1)
frac = frac_num / frac_den if frac_den else 0
total_inches = feet * 12 + inches + frac
mm = total_inches * 25.4
if _MIN_CAB_MM <= mm <= _MAX_CAB_MM * 2:
return mm
if _MIN_CAB_IN <= total_inches <= _MAX_CAB_IN * 2:
return total_inches * 25.4
# Feet only: "14'"
feet_only = re.search(r'^(\d+)\s*[\'′]$', text)
if feet_only:
total_inches = int(feet_only.group(1)) * 12
mm = total_inches * 25.4
if _MIN_CAB_MM <= mm <= _MAX_CAB_MM * 2:
return mm
if _MIN_CAB_IN <= total_inches <= _MAX_CAB_IN * 2:
return total_inches * 25.4
# Inches only: "36\""
inches_only = re.search(r'^(\d+(?:\.\d+)?)\s*["″]$', text)
if inches_only:
mm = float(inches_only.group(1)) * 25.4
if _MIN_CAB_MM <= mm <= _MAX_CAB_MM * 2:
return mm
total_inches = float(inches_only.group(1))
if _MIN_CAB_IN <= total_inches <= _MAX_CAB_IN * 2:
return total_inches * 25.4
return None
@@ -214,36 +211,36 @@ def cross_validate(
diff = abs(metric_mm - imperial_mm)
if diff <= tolerance_mm:
return DimensionPair(
value_mm = metric_mm, # prefer metric (exact)
value_in = metric_mm, # prefer metric (exact)
metric_text = f"{metric_mm/10:.2f}cm",
imperial_text = f"{imperial_mm/25.4:.2f}\"",
confidence = "HIGH",
)
else:
return DimensionPair(
value_mm = metric_mm,
value_in = metric_mm,
metric_text = f"{metric_mm/10:.2f}cm",
imperial_text = f"{imperial_mm/25.4:.2f}\"",
confidence = "MISMATCH",
mismatch_mm = diff,
mismatch_in = diff,
)
elif metric_mm is not None:
return DimensionPair(
value_mm = metric_mm,
value_in = metric_mm,
metric_text = f"{metric_mm/10:.2f}cm",
imperial_text = None,
confidence = "METRIC_ONLY",
)
elif imperial_mm is not None:
return DimensionPair(
value_mm = imperial_mm,
value_in = imperial_mm,
metric_text = None,
imperial_text = f"{imperial_mm/25.4:.2f}\"",
confidence = "IMPERIAL_ONLY",
)
else:
return DimensionPair(
value_mm=0, metric_text=None, imperial_text=None,
value_in=0, metric_text=None, imperial_text=None,
confidence="NONE",
)
@@ -417,6 +414,6 @@ if __name__ == "__main__":
print("\n=== Cross-Validation ===")
pair = cross_validate(762.0, 762.0)
print(f" 76.20cm + [2'-6\"] → {pair.confidence} ({pair.value_mm}mm)")
print(f" 76.20cm + [2'-6\"] → {pair.confidence} ({pair.value_in}mm)")
pair = cross_validate(762.0, 914.4)
print(f" 76.20cm + 36\" → {pair.confidence} (diff={pair.mismatch_mm:.1f}mm)")
print(f" 76.20cm + 36\" → {pair.confidence} (diff={pair.mismatch_in:.1f}mm)")
+70
View File
@@ -0,0 +1,70 @@
"""
===========================================================================
core/drawing_classifier.py — Stage 0 Drawing Sheet Page Classifier
===========================================================================
Analyzes text spans on a drawing page to classify it into:
- FLOOR PLAN
- UNIT PLAN
- ELEVATION
- RCP
- DETAIL
- SECTION
===========================================================================
"""
from __future__ import annotations
import re
from typing import List, Any
from core.pdf_extractor import TextSpan
class DrawingClassifier:
"""
Classifies drawings based on text tokens and layout annotations.
"""
@staticmethod
def classify_page(spans: list[Any]) -> str:
"""
Classifies page text content into drawing type labels.
Uses largest text spans first (title block) to prevent body text callouts
(e.g., 'REFER TO ELEVATION') from overriding the actual sheet type.
"""
if not spans:
return "UNIT PLAN"
# Check the largest text on the page (likely the title block)
sorted_spans = sorted(spans, key=lambda s: getattr(s, 'size', 0), reverse=True)
title_text = " ".join(s.text.upper() for s in sorted_spans[:15])
if "RCP" in title_text or "REFLECTED CEILING" in title_text:
return "RCP"
if "UNIT PLAN" in title_text or "ENLARGED PLAN" in title_text:
return "UNIT PLAN"
if "FLOOR PLAN" in title_text or "GROUND LEVEL" in title_text or "LEVEL PLAN" in title_text or "OVERALL PLAN" in title_text:
return "FLOOR PLAN"
if "ELEVATION" in title_text or "INT. ELEV" in title_text:
return "ELEVATION"
# Fallback to full page text, reordered so Plan > Elevation
text_content = " ".join(s.text.upper() for s in spans)
if "RCP" in text_content or "REFLECTED CEILING" in text_content:
return "RCP"
if "UNIT PLAN" in text_content or "UNIT A" in text_content or "UNIT B" in text_content or "UNIT D" in text_content or "UNIT ST" in text_content or "ENLARGED PLAN" in text_content:
return "UNIT PLAN"
if "FLOOR PLAN" in text_content or "GROUND LEVEL" in text_content or "LEVEL PLAN" in text_content or "OVERALL PLAN" in text_content:
return "FLOOR PLAN"
if "ELEVATION" in text_content or "INT. ELEV" in text_content:
return "ELEVATION"
if "BUILDING SECTION" in text_content or "WALL SECTION" in text_content:
return "SECTION"
if "DETAIL" in text_content or "SECTION" in text_content or "MOUNTING" in text_content:
return "DETAIL"
# Fallback
return "UNIT PLAN" # Most details pages are unit plan/elevations
+272
View File
@@ -0,0 +1,272 @@
"""
===========================================================================
core/engines/ada_engine.py — ADA Compliance Validation
===========================================================================
Validates kitchen and bathroom layouts against ADA/FHA requirements.
ADA requirements implemented here:
- 60" turning circle (kitchen and bathroom)
- 30×48 clear floor space in front of sink base
- Counter height max 34" AFF (from config.BASE_CABINET_HEIGHT_ADA_IN)
- Upper cabinet reach range: operable parts 15"–48" AFF
- Sink base must be accessible type (knee clearance capable)
Input geometry dict shape (walls_info from pipeline):
{
"walls": [
{
"name": "KITCHEN",
"length": 120.0, # inches
"cabinets": [
{"x": 0, "width": 36, "cabinet_type": "sink_base", ...},
...
]
}
],
"room_depth": 96.0 # inches — how deep the room is (needed for circle test)
}
===========================================================================
"""
from __future__ import annotations
from typing import Dict, List, Any
try:
from shapely.geometry import Polygon, Point
_SHAPELY = True
except ImportError:
_SHAPELY = False
from core.config import BASE_CABINET_HEIGHT_ADA_IN
# ── ADA dimension constants ───────────────────────────────────────────────
TURNING_CIRCLE_DIAMETER = 60.0 # inches — ANSI A117.1 §304.3
CLEAR_FLOOR_WIDTH = 30.0 # inches — parallel approach
CLEAR_FLOOR_DEPTH = 48.0 # inches — parallel approach
REACH_RANGE_MIN = 15.0 # inches AFF
REACH_RANGE_MAX = 48.0 # inches AFF
def _build_cabinet_footprint(
wall_length: float,
cabinets: list[dict],
room_depth: float,
cabinet_depth: float = 24.0,
) -> "Polygon | None":
"""
Build a Shapely Polygon representing the walkable floor area
in a kitchen/vanity (the room rectangle minus all base-cabinet footprints).
Returns None if Shapely is unavailable.
"""
if not _SHAPELY:
return None
room_rect = Polygon([
(0, 0),
(wall_length, 0),
(wall_length, room_depth),
(0, room_depth),
])
walkable = room_rect
for cab in cabinets:
x = float(cab.get("x", 0))
w = float(cab.get("width", 0))
depth = float(cab.get("depth", cabinet_depth))
cab_rect = Polygon([
(x, 0),
(x + w, 0),
(x + w, depth),
(x, depth),
])
try:
walkable = walkable.difference(cab_rect)
except Exception:
pass
return walkable
class ADAEngine:
"""Validates and enforces ADA compliance rules for kitchen and vanity layouts."""
@staticmethod
def validate_clearances(geometry: Dict[str, Any]) -> Dict[str, Any]:
"""
Checks for minimum 60" turning circle and 30×48 clear floor spaces.
geometry dict keys used:
walls — list of wall dicts with 'length', 'cabinets'
room_depth — float, depth of the room in inches
"""
issues = []
walls = geometry.get("walls", [])
room_depth = float(geometry.get("room_depth", 0.0))
if not walls or room_depth <= 0:
issues.append({
"severity": "WARNING",
"message": "Room dimensions not available — ADA clearance check skipped.",
})
return {"status": "NEEDS_REVIEW", "issues": issues}
if not _SHAPELY:
issues.append({
"severity": "WARNING",
"message": "Shapely not installed — geometric ADA clearance check skipped.",
})
return {"status": "NEEDS_REVIEW", "issues": issues}
# Combine all cabinets across walls into a single floor plan
all_cabinets: list[dict] = []
max_wall_len = max((float(w.get("length", 0)) for w in walls), default=0.0)
for w in walls:
all_cabinets.extend(w.get("cabinets", []))
walkable = _build_cabinet_footprint(max_wall_len, all_cabinets, room_depth)
# ── Turning circle test ──────────────────────────────────────────
if walkable is not None and not walkable.is_empty:
radius = TURNING_CIRCLE_DIAMETER / 2.0
# Try to inscribe a 60" diameter circle anywhere in walkable space
# by checking a grid of candidate center points
found_circle = False
bounds = walkable.bounds # (minx, miny, maxx, maxy)
step = 6.0 # check every 6 inches
x = bounds[0] + radius
while x <= bounds[2] - radius:
y = bounds[1] + radius
while y <= bounds[3] - radius:
circle = Point(x, y).buffer(radius)
if walkable.contains(circle):
found_circle = True
break
y += step
if found_circle:
break
x += step
if not found_circle:
issues.append({
"severity": "ERROR",
"message": (
f"No 60\" turning circle fits in walkable kitchen/bath floor area "
f"({walkable.area:.0f} sq-in available). "
f"ADA §304.3 requires unobstructed 60\" diameter."
),
})
# ── 30×48 clear floor space in front of sink ───────────────────
sink_cabs = [c for c in all_cabinets if c.get("cabinet_type") == "sink_base"]
for sink in sink_cabs:
sx = float(sink.get("x", 0))
sw = float(sink.get("width", 36))
sink_center_x = sx + sw / 2.0
# Clear zone extends 48" from front of cabinets (y=24") into room
clear_zone = Polygon([
(sink_center_x - CLEAR_FLOOR_WIDTH / 2, 24.0),
(sink_center_x + CLEAR_FLOOR_WIDTH / 2, 24.0),
(sink_center_x + CLEAR_FLOOR_WIDTH / 2, 24.0 + CLEAR_FLOOR_DEPTH),
(sink_center_x - CLEAR_FLOOR_WIDTH / 2, 24.0 + CLEAR_FLOOR_DEPTH),
])
if walkable is not None and not walkable.contains(clear_zone):
issues.append({
"severity": "ERROR",
"message": (
f"30\"×48\" clear floor space obstructed in front of sink base "
f"at x={sx:.0f}\"–{sx+sw:.0f}\". ADA §306.2 requires knee clearance."
),
})
return {
"status": "PASS" if not any(i["severity"] == "ERROR" for i in issues) else "FAIL",
"issues": issues,
}
@staticmethod
def validate_reach_ranges(cabinets: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Validates that operable parts are within 15 to 48 inches AFF."""
issues = []
for cab in cabinets:
if cab.get("cabinet_type", "").startswith("upper"):
# ADA uppers must be mounted so bottom rail ≤ 48" AFF
# Standard upper bottom is at 54" — flag for hardware review
issues.append({
"severity": "WARNING",
"message": (
f"Upper cabinet '{cab.get('id', cab.get('cabinet_type', ''))}' "
f"may exceed 48\" AFF reach range. Verify pull-down hardware or "
f"lower mounting height per ADA §308.2."
),
})
return {
"status": "PASS" if not any(i["severity"] == "ERROR" for i in issues) else "FAIL",
"issues": issues,
}
@staticmethod
def validate_sink_approach(sink_cabinet: Dict[str, Any]) -> Dict[str, Any]:
"""Validates that sink bases have removable fronts and pipe protection."""
issues = []
cab_type = sink_cabinet.get("cabinet_type", "") or sink_cabinet.get("render_style", "")
if "sink" not in cab_type.lower():
issues.append({
"severity": "ERROR",
"message": (
"ADA sink location does not map to a sink_base cabinet type. "
"Cabinet must provide knee clearance (min 27\" H × 30\" W × 19\" D)."
),
})
return {
"status": "PASS" if not issues else "FAIL",
"issues": issues,
}
@staticmethod
def run_full_validation(unit_data: Dict[str, Any]) -> Dict[str, Any]:
"""Runs all ADA validation checks on a unit."""
if not unit_data.get("is_ada", False):
return {"status": "NOT_APPLICABLE"}
geometry = unit_data.get("geometry", {})
cabinets = unit_data.get("cabinets", [])
clearance_res = ADAEngine.validate_clearances(geometry)
reach_res = ADAEngine.validate_reach_ranges(cabinets)
# Sink approach check: find actual sink cabinet in the list
sink_cabs = [c for c in cabinets
if "sink" in str(c.get("cabinet_type", "")).lower()]
sink_res_issues: list[dict] = []
for sink in sink_cabs:
r = ADAEngine.validate_sink_approach(sink)
sink_res_issues.extend(r["issues"])
# Counter height check — compare against config constant
height_issues: list[dict] = []
for cab in cabinets:
h = float(cab.get("height_in", cab.get("height", 0)) or 0)
if h > 0 and h > BASE_CABINET_HEIGHT_ADA_IN:
height_issues.append({
"severity": "ERROR",
"message": (
f"Cabinet '{cab.get('id', cab.get('cabinet_type', ''))}' height "
f"{h}\" exceeds ADA max counter height {BASE_CABINET_HEIGHT_ADA_IN}\" AFF."
),
})
all_issues = (
clearance_res["issues"]
+ reach_res["issues"]
+ sink_res_issues
+ height_issues
)
return {
"status": "PASS" if not any(i["severity"] == "ERROR" for i in all_issues) else "FAIL",
"issues": all_issues,
}
@@ -0,0 +1,94 @@
from typing import Dict, List, Any
class AnnotationEngine:
"""Handles textual and symbol annotations like callouts, labels, and tags."""
@staticmethod
def draw_cabinet_tag(x: float, y: float, text: str, scale: float = 1.0) -> Dict[str, List]:
"""Draws a standard hexagonal or circular cabinet tag."""
geom = {"lines": [], "blocks": [], "texts": []}
# Hexagon tag
r = 3.0 * scale
pts = []
import math
for i in range(6):
angle_deg = 60 * i
angle_rad = math.pi / 180 * angle_deg
pts.append([x + r * math.cos(angle_rad), y + r * math.sin(angle_rad)])
geom["blocks"].append({
"type": "polygon",
"points": pts,
"layer": "ANNOTATION",
"style": "solid"
})
geom["texts"].append({
"pos": [x, y],
"text": text,
"size": 2.5 * scale,
"layer": "ANNOTATION_TEXT",
"align": "CENTER"
})
return geom
@staticmethod
def draw_leader_callout(start_pt: List[float], end_pt: List[float], text: str, scale: float = 1.0) -> Dict[str, List]:
"""Draws a leader line pointing from an object to a text note."""
geom = {"lines": [], "blocks": [], "texts": []}
x1, y1 = start_pt
x2, y2 = end_pt
# Leader line
geom["lines"].append({"start": [x1, y1], "end": [x2, y2], "layer": "ANNOTATION", "style": "solid"})
# Leader shoulder (horizontal landing)
shoulder_len = 5.0 * scale
direction = 1 if x2 > x1 else -1
x3 = x2 + (shoulder_len * direction)
geom["lines"].append({"start": [x2, y2], "end": [x3, y2], "layer": "ANNOTATION", "style": "solid"})
# Text
geom["texts"].append({
"pos": [x3 + (1.0 * direction * scale), y2 + (1.0 * scale)],
"text": text,
"size": 3.0 * scale,
"layer": "ANNOTATION_TEXT",
"align": "LEFT" if direction == 1 else "RIGHT"
})
return geom
@staticmethod
def draw_elevation_marker(x: float, y: float, view_name: str, sheet_num: str, scale: float = 1.0) -> Dict[str, List]:
"""Draws a standard elevation target marker (circle with an arrow)."""
geom = {"lines": [], "blocks": [], "texts": []}
r = 4.0 * scale
# Circle
geom["blocks"].append({
"type": "circle",
"center": [x, y],
"radius": r,
"layer": "ANNOTATION",
"style": "solid"
})
# Split line
geom["lines"].append({"start": [x - r, y], "end": [x + r, y], "layer": "ANNOTATION", "style": "solid"})
# Texts
geom["texts"].append({"pos": [x, y + (r/2)], "text": view_name, "size": 2.5 * scale, "layer": "ANNOTATION_TEXT", "align": "CENTER"})
geom["texts"].append({"pos": [x, y - (r/2)], "text": sheet_num, "size": 2.5 * scale, "layer": "ANNOTATION_TEXT", "align": "CENTER"})
# Arrow (pointing up as default)
geom["blocks"].append({
"type": "polygon",
"points": [[x, y + r + (2*scale)], [x - (2*scale), y + r], [x + (2*scale), y + r]],
"layer": "ANNOTATION",
"style": "solid"
})
return geom
@@ -0,0 +1,297 @@
from dataclasses import dataclass
from typing import Dict, Optional, List
@dataclass
class ApplianceModel:
"""Specification for a single appliance model."""
model_code: str # e.g., "GTE18GSNRSS"
model_name: str # e.g., "GTE18GSNRSS"
appliance_type: str # "refrigerator", "range", "dishwasher", "microwave", "hood"
width_in: float
height_in: float
depth_in: float
width_mm: float
height_mm: float
depth_mm: float
is_ada: bool
manufacturer: str
notes: str = ""
class ApplianceDatabase:
"""Central database for appliance specifications."""
CATALOG = {
# Refrigerators
"GTE18GSNRSS": ApplianceModel(
model_code="GTE18GSNRSS",
model_name="GTE18GSNRSS",
appliance_type="refrigerator",
width_in=28.0,
height_in=67.6,
depth_in=29.75,
width_mm=711.2,
height_mm=1717.04,
depth_mm=755.65,
is_ada=False,
manufacturer="GE",
notes="Standard French door refrigerator"
),
# Ranges - Regular
"GRF400PV": ApplianceModel(
model_code="GRF400PV",
model_name="GRF400PV",
appliance_type="range",
width_in=30.0,
height_in=36.0,
depth_in=28.75,
width_mm=762.0,
height_mm=914.4,
depth_mm=730.3,
is_ada=False,
manufacturer="GE",
notes="Gas range with oven"
),
# Ranges - ADA
"GRS500PVSS": ApplianceModel(
model_code="GRS500PVSS",
model_name="GRS500PVSS",
appliance_type="range",
width_in=30.0,
height_in=34.0,
depth_in=28.5,
width_mm=762.0,
height_mm=863.6,
depth_mm=723.9,
is_ada=True,
manufacturer="GE",
notes="ADA-compliant gas range, max 34\" height"
),
# Dishwashers - Regular
"GDT535PSRSS": ApplianceModel(
model_code="GDT535PSRSS",
model_name="GDT535PSRSS",
appliance_type="dishwasher",
width_in=24.0,
height_in=33.875,
depth_in=24.75,
width_mm=609.6,
height_mm=860.55,
depth_mm=628.65,
is_ada=False,
manufacturer="GE",
notes="Standard undercounter dishwasher"
),
# Dishwashers - ADA
"GDT225SSLSS": ApplianceModel(
model_code="GDT225SSLSS",
model_name="GDT225SSLSS ADA",
appliance_type="dishwasher",
width_in=24.0,
height_in=33.875,
depth_in=24.75,
width_mm=609.6,
height_mm=860.55,
depth_mm=628.65,
is_ada=True,
manufacturer="GE",
notes="ADA-compliant dishwasher"
),
# Microwaves - Regular
"JVM3160RFSS": ApplianceModel(
model_code="JVM3160RFSS",
model_name="JVM3160RFSS",
appliance_type="microwave",
width_in=30.0,
height_in=15.875,
depth_in=15.375,
width_mm=762.0,
height_mm=403.225,
depth_mm=390.525,
is_ada=False,
manufacturer="GE",
notes="Over-the-range microwave"
),
# Microwaves - ADA
"JES1145SHSS": ApplianceModel(
model_code="JES1145SHSS",
model_name="JES1145SHSS",
appliance_type="microwave",
width_in=30.0,
height_in=15.625,
depth_in=15.375,
width_mm=762.0,
height_mm=396.875,
depth_mm=390.525,
is_ada=True,
manufacturer="GE",
notes="ADA-compliant microwave oven"
),
# Range Hoods - ADA Only
"JVX3300SJSS": ApplianceModel(
model_code="JVX3300SJSS",
model_name="JVX3300SJSS",
appliance_type="hood",
width_in=30.0,
height_in=17.0,
depth_in=20.0,
width_mm=762.0,
height_mm=431.8,
depth_mm=508.0,
is_ada=True,
manufacturer="GE",
notes="ADA range hood for accessible kitchens"
),
# Another refrigerator model just in case
"GTE18GTNRBB": ApplianceModel(
model_code="GTE18GTNRBB",
model_name="GTE18GTNRBB",
appliance_type="refrigerator",
width_in=28.0,
height_in=67.6,
depth_in=29.75,
width_mm=711.2,
height_mm=1717.04,
depth_mm=755.65,
is_ada=False,
manufacturer="GE",
notes="Standard refrigerator"
),
# Frigidaire Range - Albert Project
"FCRE3062AS": ApplianceModel(
model_code="FCRE3062AS",
model_name="FCRE3062AS",
appliance_type="range",
width_in=30.0,
height_in=36.0,
depth_in=28.75,
width_mm=762.0,
height_mm=914.4,
depth_mm=730.3,
is_ada=False,
manufacturer="Frigidaire",
notes="30\" Electric Range"
),
# Frigidaire Microwave - Albert Project
"FMOS1846BS": ApplianceModel(
model_code="FMOS1846BS",
model_name="FMOS1846BS",
appliance_type="microwave",
width_in=30.0,
height_in=16.4,
depth_in=15.0,
width_mm=762.0,
height_mm=416.56,
depth_mm=381.0,
is_ada=False,
manufacturer="Frigidaire",
notes="1.8 Cu. Ft. OTR Microwave"
),
# Frigidaire Refrigerator - Albert Project
"FRSS2623AS": ApplianceModel(
model_code="FRSS2623AS",
model_name="FRSS2623AS",
appliance_type="refrigerator",
width_in=36.0,
height_in=70.0,
depth_in=33.25,
width_mm=914.4,
height_mm=1778.0,
depth_mm=844.55,
is_ada=False,
manufacturer="Frigidaire",
notes="36\" Side-by-Side Refrigerator"
),
# Frigidaire Dishwasher - Albert Project
"FDPC4314AS": ApplianceModel(
model_code="FDPC4314AS",
model_name="FDPC4314AS",
appliance_type="dishwasher",
width_in=24.0,
height_in=33.5,
depth_in=25.0,
width_mm=609.6,
height_mm=850.9,
depth_mm=635.0,
is_ada=False,
manufacturer="Frigidaire",
notes="24\" Built-In Dishwasher"
)
}
@classmethod
def get_appliance(cls, model_code: str) -> Optional[ApplianceModel]:
"""Retrieve appliance specification by model code."""
return cls.CATALOG.get(model_code)
@classmethod
def get_appliances_by_type(cls, appliance_type: str, ada: bool = False) -> List[ApplianceModel]:
"""Get all appliances of a type (optionally filtered for ADA)."""
return [
app for app in cls.CATALOG.values()
if app.appliance_type == appliance_type
and (not ada or app.is_ada)
]
@classmethod
def get_appliance_schedule(cls, project_config: dict) -> dict:
"""Generate appliance schedule from project config.
Validates that specified models exist in database.
"""
schedule = {
'regular': [],
'ada': []
}
for model_str in project_config.get('appliances_regular', []):
model_code = cls._extract_model_code(model_str)
app = cls.get_appliance(model_code)
if app:
schedule['regular'].append({
'model': model_code,
'spec': app,
'name': model_str
})
for model_str in project_config.get('appliances_ada', []):
model_code = cls._extract_model_code(model_str)
app = cls.get_appliance(model_code)
if app:
schedule['ada'].append({
'model': model_code,
'spec': app,
'name': model_str
})
return schedule
@staticmethod
def _extract_model_code(model_string: str) -> str:
"""Extract model code from description string."""
parts = model_string.split()
if "MODEL" in model_string:
try:
idx = parts.index("MODEL")
if idx + 1 < len(parts):
# In cases like "GTE18GSNRSS ADA", take the first part
return parts[idx + 1]
except ValueError:
pass
# If MODEL is not found or fails, try to find a known code
for known_code in ApplianceDatabase.CATALOG.keys():
if known_code in model_string:
return known_code
return ""
@@ -0,0 +1,586 @@
"""
===========================================================================
core/engines/appliance_library.py — CAD Symbol Library
===========================================================================
Procedural generator for appliance and fixture CAD blocks.
Produces geometry dicts consumed by DXF and PDF shop drawing generators.
Kitchen appliances:
- Refrigerator (elevation + plan)
- Dishwasher (elevation)
- Range / Stove (elevation + plan)
- Microwave (elevation)
- Wall Oven (elevation)
- Kitchen Sink (elevation dashed + plan)
- Range Hood (elevation)
Bathroom / Vanity fixtures:
- Vanity Sink (elevation + plan)
- Toilet (plan)
- Bathtub (plan)
- Shower (plan)
- Medicine Cabinet (elevation)
- Linen Cabinet (elevation)
===========================================================================
"""
from typing import Dict, List, Any
class ApplianceLibrary:
"""Procedural generator for appliance and fixture CAD blocks."""
# ─────────────────────────────────────────────────────────────────────
# KITCHEN APPLIANCES
# ─────────────────────────────────────────────────────────────────────
@staticmethod
def draw_refrigerator_elevation(x0: float, y0: float, width: float, height: float = 72.0, scale_x: float = 4.0, scale_y: float = 3.0, label: str = "REF") -> Dict[str, List]:
"""Draws a refrigerator in elevation view."""
geom = {"lines": [], "blocks": [], "texts": [], "block_refs": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
# Standard DXF block ref
geom["block_refs"].append({
"name": "REF_BLOCK",
"coords": [x0, y0],
"scale": [width * scale_x, height * scale_y],
"layer": "APPLIANCES"
})
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "REF", "layer": "APPLIANCES", "style": "solid",
"is_legacy_appliance": True
})
# Doors divide
mid_x = x0 + (width / 2.0) * scale_x
geom["lines"].append({"start": [mid_x, y0], "end": [mid_x, y1], "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True})
# Handles
h_start_y = y0 + 30.0 * scale_y
h_end_y = y0 + 48.0 * scale_y
geom["lines"].append({"start": [mid_x - 1.5, h_start_y], "end": [mid_x - 1.5, h_end_y], "layer": "HANDLES", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [mid_x + 1.5, h_start_y], "end": [mid_x + 1.5, h_end_y], "layer": "HANDLES", "style": "solid", "is_legacy_appliance": True})
# Format label to avoid spilling
import re
label = re.sub(r'(?i)refrigerator', 'REF', label).upper()
lines = label.split("\n")
for i, ln in enumerate(reversed(lines)):
geom["texts"].append({"pos": [(x0 + x1) / 2, ((y0 + y1) / 2) + i * 15], "text": ln, "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_dishwasher_elevation(x0: float, y0: float, width: float, height: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": [], "block_refs": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
geom["block_refs"].append({
"name": "DW_BLOCK",
"coords": [x0, y0],
"scale": [width * scale_x, height * scale_y],
"layer": "APPLIANCES"
})
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "D/W", "layer": "APPLIANCES", "style": "solid",
"is_legacy_appliance": True
})
# Control panel
geom["lines"].append({"start": [x0, y1 - 4.0 * scale_y], "end": [x1, y1 - 4.0 * scale_y], "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2 - 2.0 * scale_y], "text": "D/W S.S", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_range_elevation(x0: float, y0: float, width: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": [], "block_refs": []}
x1 = x0 + width * scale_x
y1_stove = y0 + 36.0 * scale_y
geom["block_refs"].append({
"name": "RANGE_BLOCK",
"coords": [x0, y0],
"scale": [width * scale_x, 36.0 * scale_y],
"layer": "APPLIANCES"
})
# Main body
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1_stove - y0],
"id": "STOVE", "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True
})
# Bottom warming drawer
geom["lines"].append({"start": [x0, y0 + 8.0 * scale_y], "end": [x1, y0 + 8.0 * scale_y], "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True})
# Glass window
geom["blocks"].append({
"type": "rect",
"coords": [x0 + 4.0 * scale_x, y0 + 12.0 * scale_y, (width - 8.0) * scale_x, 14.0 * scale_y],
"id": "", "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True
})
# Control panel
geom["lines"].append({"start": [x0, y1_stove - 4.0 * scale_y], "end": [x1, y1_stove - 4.0 * scale_y], "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True})
# Knobs
for i in range(1, 5):
kx = x0 + (width / 5.0 * i) * scale_x
geom["blocks"].append({
"type": "rect",
"coords": [kx - 1.0, y1_stove - 3.0 * scale_y, 2.0, 2.0 * scale_y],
"id": "", "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True
})
return geom
@staticmethod
def draw_microwave_elevation(x0: float, y0: float, width: float, height: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "MW", "layer": "APPLIANCES", "style": "solid"
})
# Keypad
geom["lines"].append({"start": [x1 - 6.0 * scale_x, y0], "end": [x1 - 6.0 * scale_x, y1], "layer": "APPLIANCES", "style": "solid"})
geom["blocks"].append({
"type": "rect",
"coords": [x1 - 5.0 * scale_x, y0 + 2.0 * scale_y, 3.0 * scale_x, 6.0 * scale_y],
"id": "", "layer": "APPLIANCES", "style": "solid"
})
# Window
geom["blocks"].append({
"type": "rect",
"coords": [x0 + 2.0 * scale_x, y0 + 2.0 * scale_y, (width - 10.0) * scale_x, (height - 4.0) * scale_y],
"id": "", "layer": "APPLIANCES", "style": "solid"
})
return geom
@staticmethod
def draw_wall_oven_elevation(x0: float, y0: float, width: float, height: float = 24.0, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""Draws a single or double wall oven in elevation."""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
# Body
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "OVEN", "layer": "APPLIANCES", "style": "solid"
})
# Glass window (inner rect)
pw = (width - 6.0) * scale_x
ph = (height - 8.0) * scale_y
geom["blocks"].append({
"type": "rect",
"coords": [x0 + 3.0 * scale_x, y0 + 4.0 * scale_y, pw, ph],
"id": "", "layer": "APPLIANCES", "style": "solid"
})
# Handle
geom["lines"].append({"start": [x0 + 4.0 * scale_x, y0 + 2.5 * scale_y], "end": [x1 - 4.0 * scale_x, y0 + 2.5 * scale_y], "layer": "HANDLES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "OVEN", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_range_hood_elevation(x0: float, y0: float, width: float, depth: float = 6.0, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""Draws a range hood (trapezoid) in elevation."""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
# Trapezoid: wider at bottom, narrower at top
inset = 3.0 * scale_x
geom["lines"].append({"start": [x0, y0], "end": [x1, y0], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [x0, y0], "end": [x0 + inset, y1], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [x1, y0], "end": [x1 - inset, y1], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [x0 + inset, y1], "end": [x1 - inset, y1], "layer": "APPLIANCES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, y0 + depth / 2 * scale_y], "text": "HOOD", "size": 3.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_sink_elevation(x0: float, y1: float, width: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""Draws a sink bowl (dashed) and a faucet (solid) on the countertop in elevation."""
geom = {"lines": [], "blocks": [], "texts": [], "block_refs": []}
x1 = x0 + width * scale_x
cx = (x0 + x1) / 2.0
sink_d = 8.0 * scale_y
geom["block_refs"].append({
"name": "SINK_BLOCK",
"coords": [cx, y1], # Insertion point is top-center of the counter
"scale": [width * scale_x, sink_d],
"layer": "SINK"
})
# Sink bowl (dashed, behind the cabinet face)
geom["lines"].append({"start": [x0 + 3.0 * scale_x, y1], "end": [x0 + 3.0 * scale_x, y1 - sink_d], "layer": "SINK", "style": "dashed", "is_legacy_appliance": True})
geom["lines"].append({"start": [x0 + 3.0 * scale_x, y1 - sink_d], "end": [x1 - 3.0 * scale_x, y1 - sink_d], "layer": "SINK", "style": "dashed", "is_legacy_appliance": True})
geom["lines"].append({"start": [x1 - 3.0 * scale_x, y1 - sink_d], "end": [x1 - 3.0 * scale_x, y1], "layer": "SINK", "style": "dashed", "is_legacy_appliance": True})
# Faucet base on top of counter
faucet_h = 4.0 * scale_y
faucet_w = 1.0 * scale_x
geom["lines"].append({"start": [cx - faucet_w, y1], "end": [cx - faucet_w, y1 + faucet_h], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [cx + faucet_w, y1], "end": [cx + faucet_w, y1 + faucet_h], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [cx - faucet_w, y1 + faucet_h], "end": [cx + faucet_w, y1 + faucet_h], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
# Faucet spout (arching over)
spout_w = 4.0 * scale_x
geom["lines"].append({"start": [cx - faucet_w, y1 + faucet_h], "end": [cx - spout_w, y1 + faucet_h + 2.0 * scale_y], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [cx - spout_w, y1 + faucet_h + 2.0 * scale_y], "end": [cx - spout_w, y1 + 1.0 * scale_y], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
# Faucet handles
geom["lines"].append({"start": [cx - faucet_w - 2.0 * scale_x, y1 + 1.0 * scale_y], "end": [cx - faucet_w, y1 + 1.0 * scale_y], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [cx + faucet_w, y1 + 1.0 * scale_y], "end": [cx + faucet_w + 2.0 * scale_x, y1 + 1.0 * scale_y], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
return geom
@staticmethod
def draw_toilet_elevation(x0: float, y0: float, width: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""Draws a standard toilet in elevation view (tank + bowl)."""
geom = {"lines": [], "blocks": [], "texts": []}
cx = x0 + (width / 2.0) * scale_x
# Toilet Tank (centered, approx 16" wide, 14" high, starting 15" from floor)
tank_w = 16.0 * scale_x
tank_h = 14.0 * scale_y
tank_y = y0 + 15.0 * scale_y
geom["blocks"].append({
"type": "rect",
"coords": [cx - tank_w/2.0, tank_y, tank_w, tank_h],
"id": "TOILET_TANK", "layer": "FIXTURES", "style": "solid"
})
# Toilet Bowl Base (approx 10" wide, 15" high from floor)
base_w = 10.0 * scale_x
base_h = 15.0 * scale_y
geom["blocks"].append({
"type": "rect",
"coords": [cx - base_w/2.0, y0, base_w, base_h],
"id": "TOILET_BASE", "layer": "FIXTURES", "style": "solid"
})
# Toilet Seat/Lid line (horizontal line at 15" height, slightly wider than base)
seat_w = 14.0 * scale_x
geom["blocks"].append({
"type": "rect",
"coords": [cx - seat_w/2.0, y0 + base_h, seat_w, 1.5 * scale_y],
"id": "TOILET_SEAT", "layer": "FIXTURES", "style": "solid"
})
# Flush handle
geom["blocks"].append({
"type": "rect",
"coords": [cx + tank_w/2.0 - 3.0*scale_x, tank_y + tank_h - 3.0*scale_y, 2.0*scale_x, 1.0*scale_y],
"id": "TOILET_HANDLE", "layer": "FIXTURES", "style": "solid"
})
geom["texts"].append({"pos": [cx, y0 + 5.0 * scale_y], "text": "TOILET", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_sink_plan(x0: float, y0: float, width: float, depth: float, scale_x: float = 4.0, scale_y: float = 4.0) -> Dict[str, List]:
"""Draws kitchen sink symbol in floor plan."""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
cx = x0 + (width / 2.0) * scale_x
cy = y0 + (depth / 2.0) * scale_y
sink_w = min(width - 6.0, 24.0) * scale_x
sink_h = 16.0 * scale_y
# Outer rim
geom["blocks"].append({
"type": "rect",
"coords": [cx - sink_w/2, cy - sink_h/2, sink_w, sink_h],
"id": "SINK", "layer": "APPLIANCES", "style": "solid"
})
# Drain circle approximation (diamond)
dx, dy = cx, cy + 2.0 * scale_y
r = 1.0 * scale_x
geom["lines"].append({"start": [dx-r, dy], "end": [dx, dy+r], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [dx, dy+r], "end": [dx+r, dy], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [dx+r, dy], "end": [dx, dy-r], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [dx, dy-r], "end": [dx-r, dy], "layer": "APPLIANCES", "style": "solid"})
return geom
@staticmethod
def draw_range_plan(x0: float, y0: float, width: float, depth: float, scale_x: float = 4.0, scale_y: float = 4.0) -> Dict[str, List]:
"""Draws range symbol with 4 burners in floor plan."""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, width * scale_x, depth * scale_y],
"id": "RANGE", "layer": "APPLIANCES", "style": "solid"
})
# 4 burners
for bx in [x0 + 4.0 * scale_x, x1 - 4.0 * scale_x]:
for by in [y0 + 4.0 * scale_y, y1 - 4.0 * scale_y]:
geom["lines"].append({"start": [bx-2, by], "end": [bx+2, by], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [bx, by-2], "end": [bx, by+2], "layer": "APPLIANCES", "style": "solid"})
return geom
# ─────────────────────────────────────────────────────────────────────
# BATHROOM / VANITY FIXTURES
# ─────────────────────────────────────────────────────────────────────
@staticmethod
def draw_vanity_sink_elevation(x0: float, y1: float, width: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""
Draws vanity sink bowl in elevation (dashed, shown behind vanity cabinet).
Standard vanity sink: 16–21\" wide, 8\" deep drop.
"""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
sink_d = 6.0 * scale_y # vanity sink shallower than kitchen
# Oval/rectangular sink shown as dashed hidden lines
geom["lines"].append({"start": [x0 + 2.5 * scale_x, y1], "end": [x0 + 2.5 * scale_x, y1 - sink_d], "layer": "SINK", "style": "dashed"})
geom["lines"].append({"start": [x0 + 2.5 * scale_x, y1 - sink_d], "end": [x1 - 2.5 * scale_x, y1 - sink_d], "layer": "SINK", "style": "dashed"})
geom["lines"].append({"start": [x1 - 2.5 * scale_x, y1 - sink_d], "end": [x1 - 2.5 * scale_x, y1], "layer": "SINK", "style": "dashed"})
# Drain
cx = (x0 + x1) / 2
geom["texts"].append({"pos": [cx, y1 - sink_d / 2], "text": "o", "size": 3.0, "layer": "SINK"})
return geom
@staticmethod
def draw_toilet_plan(x0: float, y0: float, width: float = 17.0, depth: float = 29.0, scale_x: float = 4.0, scale_y: float = 4.0) -> Dict[str, List]:
"""
Draws toilet symbol in floor plan.
Standard toilet: 14–17\" wide tank, 28–30\" total depth.
"""
geom = {"lines": [], "blocks": [], "texts": []}
tank_h = 7.0 * scale_y # tank depth
bowl_h = (depth - 7.0) * scale_y
x1 = x0 + width * scale_x
# Tank (rectangle)
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, width * scale_x, tank_h],
"id": "TOILET_TANK", "layer": "FIXTURES", "style": "solid"
})
# Bowl (D-shape approximation as tapered rect)
bowl_w_top = width * scale_x
bowl_w_bot = (width - 4.0) * scale_x
cx = x0 + width * scale_x / 2
geom["lines"].append({"start": [x0, y0 + tank_h], "end": [x1, y0 + tank_h], "layer": "FIXTURES", "style": "solid"})
geom["lines"].append({"start": [x0, y0 + tank_h], "end": [cx - bowl_w_bot/2, y0 + tank_h + bowl_h], "layer": "FIXTURES", "style": "solid"})
geom["lines"].append({"start": [x1, y0 + tank_h], "end": [cx + bowl_w_bot/2, y0 + tank_h + bowl_h], "layer": "FIXTURES", "style": "solid"})
geom["lines"].append({"start": [cx - bowl_w_bot/2, y0 + tank_h + bowl_h], "end": [cx + bowl_w_bot/2, y0 + tank_h + bowl_h], "layer": "FIXTURES", "style": "solid"})
# Seat ring (inner oval approximated as inner rect)
geom["blocks"].append({
"type": "rect",
"coords": [cx - bowl_w_bot/2 + 1.5*scale_x, y0 + tank_h + 2.0*scale_y, bowl_w_bot - 3.0*scale_x, bowl_h - 4.0*scale_y],
"id": "", "layer": "FIXTURES", "style": "solid"
})
geom["texts"].append({"pos": [cx, y0 + tank_h + bowl_h / 2], "text": "WC", "size": 3.0, "layer": "TEXT"})
return geom
@staticmethod
def draw_bathtub_elevation(x0: float, y0: float, width: float, height: float = 45.0, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""Draws a standard bathtub profile in elevation view."""
geom = {"blocks": [], "lines": [], "texts": []}
w_pt = width * scale_x
h_pt = height * scale_y
# Tub outline
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, w_pt, h_pt],
"layer": "FIXTURES",
"style": "solid"
})
# Lip/Edge line near the top (about 2 inches down)
geom["lines"].append({
"start": [x0, y0 + h_pt - 2.0 * scale_y],
"end": [x0 + w_pt, y0 + h_pt - 2.0 * scale_y],
"layer": "FIXTURES",
"style": "continuous"
})
# Label "TUB BY OTHERS"
cx = x0 + w_pt / 2.0
geom["texts"].append({"pos": [cx, y0 + h_pt/2.0 + 3.0*scale_y], "text": "TUB BY", "size": 4.5, "layer": "TEXT"})
geom["texts"].append({"pos": [cx, y0 + h_pt/2.0 - 2.0*scale_y], "text": "OTHERS", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_bathtub_plan(x0: float, y0: float, width: float = 32.0, length: float = 60.0, scale_x: float = 4.0, scale_y: float = 4.0) -> Dict[str, List]:
"""
Draws bathtub symbol in floor plan.
Standard tub: 32–36\" wide × 60\" long. ADA tubs may be 36\" wide.
"""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + length * scale_x # length runs along wall
y1 = y0 + width * scale_y
# Outer rim
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, length * scale_x, width * scale_y],
"id": "TUB", "layer": "FIXTURES", "style": "solid"
})
# Inner tub basin (inset 3" all sides)
inset_x = 3.0 * scale_x
inset_y = 3.0 * scale_y
geom["blocks"].append({
"type": "rect",
"coords": [x0 + inset_x, y0 + inset_y, (length - 6.0) * scale_x, (width - 6.0) * scale_y],
"id": "", "layer": "FIXTURES", "style": "solid"
})
# Drain (at foot end, right side)
drain_x = x1 - 6.0 * scale_x
drain_y = y0 + width / 2 * scale_y
r = 1.5 * scale_x
geom["lines"].append({"start": [drain_x-r, drain_y], "end": [drain_x+r, drain_y], "layer": "FIXTURES", "style": "solid"})
geom["lines"].append({"start": [drain_x, drain_y-r], "end": [drain_x, drain_y+r], "layer": "FIXTURES", "style": "solid"})
# Faucet end marker (left side)
geom["lines"].append({"start": [x0 + 4.0*scale_x, y0 + 2.0*scale_y], "end": [x0 + 4.0*scale_x, y1 - 2.0*scale_y], "layer": "FIXTURES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "TUB", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_shower_plan(x0: float, y0: float, width: float = 36.0, depth: float = 36.0, scale_x: float = 4.0, scale_y: float = 4.0) -> Dict[str, List]:
"""
Draws shower stall symbol in floor plan.
Standard: 36×36\" min. Roll-in ADA shower: 60×36\".
Shows diagonal hatch lines to indicate tiled floor.
"""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + depth * scale_y
# Outer boundary
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, width * scale_x, depth * scale_y],
"id": "SHOWER", "layer": "FIXTURES", "style": "solid"
})
# Diagonal hatch lines (every 8" in drawing space = 8 * scale_x pts)
step = 8.0 * scale_x
x = x0
while x < x1 + (y1 - y0):
lx0 = max(x0, x - (y1 - y0))
ly0 = y0 if x > x0 else y0 + (x0 - x)
lx1 = min(x1, x)
ly1 = y0 + (x - lx0) if x < x1 else y1
if lx0 < lx1:
geom["lines"].append({"start": [lx0, ly0], "end": [lx1, ly1], "layer": "FIXTURES", "style": "solid"})
x += step
# Drain in centre
cx = x0 + width / 2 * scale_x
cy = y0 + depth / 2 * scale_y
r = 1.5 * scale_x
geom["lines"].append({"start": [cx-r, cy], "end": [cx+r, cy], "layer": "FIXTURES", "style": "solid"})
geom["lines"].append({"start": [cx, cy-r], "end": [cx, cy+r], "layer": "FIXTURES", "style": "solid"})
geom["texts"].append({"pos": [cx, cy], "text": "SHR", "size": 3.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_medicine_cabinet_elevation(x0: float, y0: float, width: float, height: float = 24.0, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""
Draws medicine cabinet / mirrored cabinet in elevation.
Shown as dashed (recessed into wall) with mirror crosshatch.
Standard: 14–24\" wide × 24–30\" tall.
"""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
# Body (dashed — recessed)
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "MED_CAB", "layer": "FIXTURES", "style": "dashed"
})
# Mirror crosshatch (two diagonals)
geom["lines"].append({"start": [x0, y0], "end": [x1, y1], "layer": "FIXTURES", "style": "solid"})
geom["lines"].append({"start": [x1, y0], "end": [x0, y1], "layer": "FIXTURES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "MED\nCAB", "size": 3.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_linen_cabinet_elevation(x0: float, y0: float, width: float, height: float = 84.0, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""
Draws linen / storage cabinet in elevation.
Typically floor-to-near-ceiling tall cabinet, 18–24\" wide.
"""
geom = {"lines": [], "blocks": [], "texts": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
# Body
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "LINEN", "layer": "APPLIANCES", "style": "solid"
})
# Shelf lines (every 12" height)
shelf_y = y0 + 12.0 * scale_y
while shelf_y < y1 - 6.0 * scale_y:
geom["lines"].append({"start": [x0, shelf_y], "end": [x1, shelf_y], "layer": "APPLIANCES", "style": "solid"})
shelf_y += 12.0 * scale_y
# Handle
mid_x = (x0 + x1) / 2
geom["lines"].append({"start": [mid_x - 1.5, y0 + 2.5 * scale_y], "end": [mid_x + 1.5, y0 + 2.5 * scale_y], "layer": "HANDLES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "LINEN", "size": 4.0, "layer": "TEXT"})
return geom
# ─────────────────────────────────────────────────────────────────────
# DISPATCH — get any symbol by type name
# ─────────────────────────────────────────────────────────────────────
# Standard default sizes (inches) keyed by YOLO class / appliance type
DEFAULT_SIZES: dict = {
# Kitchen
"REF": {"width": 36.0, "height": 72.0, "depth": 30.0},
"RANGE": {"width": 30.0, "height": 36.0, "depth": 24.0},
"DW": {"width": 24.0, "height": 34.5, "depth": 24.0},
"OVEN": {"width": 27.0, "height": 24.0, "depth": 24.0},
"MIC": {"width": 30.0, "height": 18.0, "depth": 15.0},
"HOOD": {"width": 30.0, "height": 6.0, "depth": 18.0},
"SINK": {"width": 33.0, "height": 8.0, "depth": 22.0},
# Bathroom
"VANITY_SINK": {"width": 21.0, "height": 6.0, "depth": 18.0},
"TOILET": {"width": 17.0, "height": 0.0, "depth": 29.0},
"BATHTUB": {"width": 32.0, "height": 0.0, "depth": 60.0},
"SHOWER": {"width": 36.0, "height": 0.0, "depth": 36.0},
"MED_CAB": {"width": 20.0, "height": 24.0, "depth": 4.0},
"LINEN": {"width": 18.0, "height": 84.0, "depth": 15.0},
}
@@ -0,0 +1,101 @@
import re
from functools import lru_cache
from typing import Dict, Any
class CabinetLibraryResolver:
@staticmethod
@lru_cache(maxsize=512)
def resolve_cabinet(nomenclature: str) -> Dict[str, Any]:
"""Resolves a cabinet string like SB36 or W3036 into a detailed dictionary."""
nom = nomenclature.upper().strip()
# Extract all numbers
nums = re.findall(r'\d+', nom)
width = float(nums[0]) if nums else 0.0
height = 0.0
depth = 0.0
family = 'BASE'
render_style = 'standard'
doors = 1 if width < 24 else 2
drawers = 1 if width < 24 else 2
if nom.startswith('W'):
family = 'UPPER'
depth = 12.0
if len(nums) >= 2:
height = float(nums[1])
else:
height = 30.0
drawers = 0
if nom.startswith('WF'):
render_style = 'filler'
doors = 0
elif nom.startswith('WEP') or nom == 'WP':
render_style = 'panel'
width = width if width > 0 else 1.5
doors = 0
elif nom.startswith('P') or nom.startswith('WP') or nom.startswith('REP'):
family = 'TALL'
depth = 24.0
height = 84.0
if len(nums) >= 2:
height = float(nums[1])
drawers = 0
if nom.startswith('TF'):
render_style = 'filler'
doors = 0
elif nom.startswith('REP') or nom.startswith('TP') or nom.startswith('TEP'):
render_style = 'panel'
width = width if width > 0 else 1.5
doors = 0
elif nom.startswith('SB') or 'SINK' in nom:
family = 'BASE'
depth = 24.0
height = 34.5
render_style = 'sink_base'
drawers = 0 # Sink bases usually have false fronts, not functional drawers
elif nom.startswith('DB') or nom.startswith('3DB') or nom.startswith('4DB'):
family = 'BASE'
depth = 24.0
height = 34.5
render_style = 'drawer_base'
doors = 0
if '3' in nom: drawers = 3
elif '4' in nom: drawers = 4
else: drawers = 3
elif nom.startswith('F') or nom.startswith('BF'):
family = 'BASE'
depth = 24.0
height = 34.5
render_style = 'filler'
doors = 0
drawers = 0
elif nom.startswith('BEP') or nom == 'BP':
family = 'BASE'
depth = 24.0
height = 34.5
render_style = 'panel'
width = width if width > 0 else 1.5
doors = 0
drawers = 0
else:
family = 'BASE'
depth = 24.0
height = 34.5
return {
'family': family,
'width': width,
'depth': depth,
'height': height,
'doors': doors,
'drawers': drawers,
'render_style': render_style
}
@@ -0,0 +1,219 @@
from typing import Dict, List, Any
class CabinetRendererFactory:
"""Renders cabinet geometry based on type, producing detailed architectural graphics."""
@staticmethod
def render_elevation(cab: Dict[str, Any], x0: float, y0: float, x1: float, y1: float, is_upper: bool, is_pantry: bool, is_drawer: bool, render_style: str = 'standard', scale_x: float = 1.0, scale_y: float = 1.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
layer = "CABINETS_UPPER" if is_upper else "CABINETS_BASE"
cab_w = (x1 - x0) / scale_x
cab_h = (y1 - y0) / scale_y
# 1. Outer box (Face frame / carcass)
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": cab.get("cabinet_id", ""),
"layer": layer,
"style": "solid"
})
if render_style in ('filler', 'panel'):
# Just return the solid box for a filler or panel, no doors/drawers
return geom
if render_style == 'section':
# Section cut: no face frame, just shelves.
# 1 shelf for base, 2 for upper/tall.
num_shelves = 2 if is_upper or is_pantry else 1
shelf_h = cab_h / (num_shelves + 1)
for i in range(1, num_shelves + 1):
sy = y0 + i * shelf_h
geom["lines"].append({
"start": [x0, sy],
"end": [x1, sy],
"layer": layer,
"style": "solid"
})
return geom
# 1.5 Face Frame Inner Edge (1.5" frame width)
frame_w = 1.5 * scale_x
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w, y0 + frame_w, (x1 - x0) - 2*frame_w, (y1 - y0) - 2*frame_w],
"layer": layer,
"style": "solid"
})
if is_drawer:
# 3-drawer stack with fronts
drawers = 3
drawer_h = ((y1 - y0) - 2*frame_w) / drawers
for i in range(drawers):
dy_bottom = y0 + frame_w + i * drawer_h
dy_top = dy_bottom + drawer_h
# Drawer front gap (1/8")
gap = 0.125 * scale_x
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, dy_bottom + gap, (x1 - x0) - 2*(frame_w + gap), drawer_h - 2*gap],
"layer": "DOOR_PANEL",
"style": "solid"
})
# Handle
hy = dy_bottom + drawer_h / 2
geom["lines"].append({
"start": [(x0 + x1)/2 - 3.0 * scale_x, hy],
"end": [(x0 + x1)/2 + 3.0 * scale_x, hy],
"layer": "HANDLES", "style": "solid"
})
geom["blocks"].append({
"type": "circle",
"coords": [(x0 + x1)/2 - 3.0 * scale_x, hy, 0.2 * scale_x],
"layer": "HANDLES", "style": "solid"
})
geom["blocks"].append({
"type": "circle",
"coords": [(x0 + x1)/2 + 3.0 * scale_x, hy, 0.2 * scale_x],
"layer": "HANDLES", "style": "solid"
})
else:
y1_door = y1 - frame_w
# Top drawer for base cabinets
drawer_h = 6.0 * scale_y
if not is_upper and not is_pantry and cab_h > drawer_h + 3.0:
dy_drawer = y1 - frame_w - drawer_h
gap = 0.125 * scale_x
if cab_w > 21.0:
# Double top drawers
xm = (x0 + x1) / 2
# Left Drawer
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, dy_drawer + gap, (xm - x0) - frame_w - 2*gap, drawer_h - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Left Drawer Handle
hy = dy_drawer + drawer_h/2
geom["lines"].append({"start": [(x0 + xm)/2 - 3.0 * scale_x, hy], "end": [(x0 + xm)/2 + 3.0 * scale_x, hy], "layer": "HANDLES", "style": "solid"})
# Right Drawer
geom["blocks"].append({
"type": "rect",
"coords": [xm + gap, dy_drawer + gap, (x1 - xm) - frame_w - 2*gap, drawer_h - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Right Drawer Handle
geom["lines"].append({"start": [(xm + x1)/2 - 3.0 * scale_x, hy], "end": [(xm + x1)/2 + 3.0 * scale_x, hy], "layer": "HANDLES", "style": "solid"})
else:
# Single top drawer
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, dy_drawer + gap, (x1 - x0) - 2*(frame_w + gap), drawer_h - 2*gap],
"layer": "DOOR_PANEL",
"style": "solid"
})
# Drawer Handle
hy = dy_drawer + drawer_h/2
geom["lines"].append({
"start": [(x0 + x1)/2 - 3.0 * scale_x, hy],
"end": [(x0 + x1)/2 + 3.0 * scale_x, hy],
"layer": "HANDLES", "style": "solid"
})
# Drawer separator line
geom["lines"].append({"start": [x0 + frame_w, dy_drawer], "end": [x1 - frame_w, dy_drawer], "layer": layer, "style": "solid"})
y1_door = dy_drawer
# Doors
gap = 0.125 * scale_x
if is_pantry:
# Tall cabinets have split doors (upper and lower)
split_y = y0 + 34.5 * scale_y # typically matches counter height
# Lower door
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, y0 + frame_w + gap, (x1 - x0) - 2*frame_w - 2*gap, (split_y - y0) - frame_w - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Upper door
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, split_y + gap, (x1 - x0) - 2*frame_w - 2*gap, (y1_door - split_y) - frame_w - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Split line
geom["lines"].append({"start": [x0 + frame_w, split_y], "end": [x1 - frame_w, split_y], "layer": layer, "style": "solid"})
# Swings Lower
geom["lines"].append({"start": [x0 + frame_w, y0 + frame_w], "end": [x1 - frame_w, split_y - gap], "layer": "SWING", "style": "dashed"})
geom["lines"].append({"start": [x0 + frame_w, split_y - gap], "end": [x1 - frame_w, y0 + frame_w], "layer": "SWING", "style": "dashed"})
# Swings Upper
geom["lines"].append({"start": [x0 + frame_w, split_y + gap], "end": [x1 - frame_w, y1_door], "layer": "SWING", "style": "dashed"})
geom["lines"].append({"start": [x0 + frame_w, y1_door], "end": [x1 - frame_w, split_y + gap], "layer": "SWING", "style": "dashed"})
# Handles
xm = (x0 + x1) / 2
geom["lines"].append({"start": [xm - 5.0 * scale_x, split_y - 7.0 * scale_y], "end": [xm - 5.0 * scale_x, split_y - 2.0 * scale_y], "layer": "HANDLES", "style": "solid"})
geom["lines"].append({"start": [xm - 5.0 * scale_x, split_y + 2.0 * scale_y], "end": [xm - 5.0 * scale_x, split_y + 7.0 * scale_y], "layer": "HANDLES", "style": "solid"})
elif cab_w > 21.0:
# Double door
xm = (x0 + x1) / 2
# Left Door
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, y0 + frame_w + gap, (xm - x0) - frame_w - 2*gap, (y1_door - y0) - frame_w - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Right Door
geom["blocks"].append({
"type": "rect",
"coords": [xm + gap, y0 + frame_w + gap, (x1 - xm) - frame_w - 2*gap, (y1_door - y0) - frame_w - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Swings (Left Door)
geom["lines"].append({"start": [x0 + frame_w, (y0 + y1_door) / 2], "end": [xm, y0 + frame_w], "layer": "SWING", "style": "dashed"})
geom["lines"].append({"start": [x0 + frame_w, (y0 + y1_door) / 2], "end": [xm, y1_door - gap], "layer": "SWING", "style": "dashed"})
# Swings (Right Door)
geom["lines"].append({"start": [x1 - frame_w, (y0 + y1_door) / 2], "end": [xm, y0 + frame_w], "layer": "SWING", "style": "dashed"})
geom["lines"].append({"start": [x1 - frame_w, (y0 + y1_door) / 2], "end": [xm, y1_door - gap], "layer": "SWING", "style": "dashed"})
# Handles
if is_upper:
geom["lines"].append({"start": [xm - 1.5 * scale_x, y0 + frame_w + 2.0 * scale_y], "end": [xm - 1.5 * scale_x, y0 + frame_w + 7.0 * scale_y], "layer": "HANDLES", "style": "solid"})
geom["lines"].append({"start": [xm + 1.5 * scale_x, y0 + frame_w + 2.0 * scale_y], "end": [xm + 1.5 * scale_x, y0 + frame_w + 7.0 * scale_y], "layer": "HANDLES", "style": "solid"})
else:
geom["lines"].append({"start": [xm - 1.5 * scale_x, y1_door - 7.0 * scale_y], "end": [xm - 1.5 * scale_x, y1_door - 2.0 * scale_y], "layer": "HANDLES", "style": "solid"})
geom["lines"].append({"start": [xm + 1.5 * scale_x, y1_door - 7.0 * scale_y], "end": [xm + 1.5 * scale_x, y1_door - 2.0 * scale_y], "layer": "HANDLES", "style": "solid"})
else:
# Single door
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, y0 + frame_w + gap, (x1 - x0) - 2*frame_w - 2*gap, (y1_door - y0) - frame_w - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
geom["lines"].append({"start": [x0 + frame_w, (y0 + y1_door) / 2], "end": [x1 - frame_w, y0 + frame_w], "layer": "SWING", "style": "dashed"})
geom["lines"].append({"start": [x0 + frame_w, (y0 + y1_door) / 2], "end": [x1 - frame_w, y1_door - gap], "layer": "SWING", "style": "dashed"})
if is_upper:
geom["lines"].append({"start": [x1 - frame_w - 1.5 * scale_x, y0 + frame_w + 2.0 * scale_y], "end": [x1 - frame_w - 1.5 * scale_x, y0 + frame_w + 7.0 * scale_y], "layer": "HANDLES", "style": "solid"})
else:
geom["lines"].append({"start": [x1 - frame_w - 1.5 * scale_x, y1_door - 7.0 * scale_y], "end": [x1 - frame_w - 1.5 * scale_x, y1_door - 2.0 * scale_y], "layer": "HANDLES", "style": "solid"})
# Shelves (visible as dashed lines representing internal shelves)
if is_pantry or is_upper:
num_shelves = 4 if is_pantry else 2
for i in range(1, num_shelves + 1):
sy = y0 + (y1 - y0) * (i / (num_shelves + 1))
geom["lines"].append({"start": [x0 + frame_w, sy], "end": [x1 - frame_w, sy], "layer": "CABINETS_UPPER", "style": "dashed"})
return geom
@@ -0,0 +1,135 @@
"""
config_validator.py
====================
Validates project_config.json before any PDF/DXF generation runs.
Checks performed:
1. Cabinet width sum vs wall length (phantom cabinet detection)
- Iterates every kitchen type, every wall (wall_a, wall_b).
- Sums base cabinet width_cm and compares against wall length_cm.
- Raises ConfigValidationError on overflow; logs a WARNING on underflow
(gap fill may be intentional).
2. Skips wall_b cleanly if absent or has no length_cm (single-wall layouts).
Usage:
from core.engines.config_validator import validate_config
validate_config(config) # raises ConfigValidationError if invalid
# or
errors = validate_config(config, raise_on_error=False)
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
TOLERANCE_CM = 0.5 # allow up to 0.5 cm floating-point slack
class ConfigValidationError(ValueError):
"""Raised when project_config.json fails validation."""
def _validate_wall(
wall: dict,
wall_key: str,
kitchen_key: str,
errors: list,
warnings: list,
) -> None:
"""Check that base cabinet widths don't exceed the wall length."""
length_cm: Optional[float] = wall.get("length_cm")
cabinets: list = wall.get("cabinets", [])
# Skip walls with no length specified (valid for empty/single-wall layouts)
if length_cm is None:
return
total_cabinet_cm = sum(cab.get("width_cm", 0.0) for cab in cabinets)
overflow = total_cabinet_cm - length_cm
if overflow > TOLERANCE_CM:
errors.append(
f"[{kitchen_key} / {wall_key}] Cabinet total {total_cabinet_cm:.2f} cm "
f"EXCEEDS wall length {length_cm:.2f} cm by {overflow:.2f} cm. "
f"({len(cabinets)} cabinet(s) listed)"
)
elif (length_cm - total_cabinet_cm) > 10.0:
# Large gap may indicate a missing cabinet entry — warn but don't block
warnings.append(
f"[{kitchen_key} / {wall_key}] Cabinet total {total_cabinet_cm:.2f} cm is "
f"{length_cm - total_cabinet_cm:.2f} cm UNDER wall length {length_cm:.2f} cm. "
f"Verify this gap is intentional (filler / open area)."
)
def validate_config(config: dict, raise_on_error: bool = True) -> list[str]:
"""
Validate the project config dict.
Parameters
----------
config : The loaded project_config.json dict.
raise_on_error : If True, raises ConfigValidationError on first failure batch.
If False, returns a list of error strings (empty = clean).
Returns
-------
List of error strings (empty if clean).
"""
errors: list[str] = []
warnings: list[str] = []
kitchen_types: dict = config.get("kitchen_types", {})
if not kitchen_types:
warnings.append("No 'kitchen_types' key found in config — skipping wall validation.")
logger.warning("No kitchen_types in config.")
for k_key, k_data in kitchen_types.items():
for wall_key in ("wall_a", "wall_b"):
wall = k_data.get(wall_key)
if not wall:
continue # wall_b absent on single-wall layouts — skip cleanly
_validate_wall(wall, wall_key, k_key, errors, warnings)
for w in warnings:
logger.warning(w)
if errors:
msg = "\n ".join(["ConfigValidationError — layout issues detected:"] + errors)
if raise_on_error:
raise ConfigValidationError(msg)
logger.error(msg)
return errors
def validate_config_file(path: Path | str, raise_on_error: bool = True) -> list[str]:
"""Convenience wrapper — loads JSON from path and validates."""
with open(path, encoding="utf-8") as f:
config = json.load(f)
return validate_config(config, raise_on_error=raise_on_error)
# ── CLI self-test ─────────────────────────────────────────────────────────────
if __name__ == "__main__":
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
config_path = Path(sys.argv[1]) if len(sys.argv) > 1 else (
Path(__file__).parents[2] / "Casa familia" / "project_config.json"
)
print(f"Validating: {config_path}")
errs = validate_config_file(config_path, raise_on_error=False)
if errs:
print(f"\n[FAIL] {len(errs)} error(s) found:")
for e in errs:
print(f" * {e}")
sys.exit(1)
else:
print("[OK] Config is valid -- no cabinet overflow detected.")
sys.exit(0)
@@ -0,0 +1,259 @@
"""
===========================================================================
core/engines/constraint_solver.py — Constraint Extraction & Solving
===========================================================================
Phase 4: Separates the "what is physically there" (Extraction) from
"what usable space remains" (Solving).
Constraint Extraction reads:
- Wall lengths
- Window positions and widths
- Door positions and widths
- Column/chase positions and widths
- Plumbing fixture positions (sink center)
- Appliance positions and widths
Constraint Solver creates:
- Available wall runs (wall minus all obstructions)
- Sink anchor point (center-line)
- Corner conditions (blind corner, L-shape)
- Required filler zones
- Appliance clearance zones
- Dead space (unusable runs too short for any catalog cabinet)
===========================================================================
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Optional
# ── Standard catalog widths (inches) ─────────────────────────────────────
# These are the only widths the Placement Engine is allowed to use.
STANDARD_BASE_WIDTHS = [9, 12, 15, 18, 21, 24, 27, 30, 33, 36]
STANDARD_UPPER_WIDTHS = [9, 12, 15, 18, 21, 24, 27, 30, 33, 36]
STANDARD_SINK_BASE_WIDTHS = [30, 33, 36, 42]
STANDARD_DW_WIDTHS = [24] # Dishwasher opening is always 24"
MIN_FILLER_WIDTH = 1.5 # Minimum filler strip
MAX_FILLER_WIDTH = 6.0 # Maximum filler before it becomes a cabinet
MIN_CABINET_WIDTH = 9 # Smallest catalog base cabinet
@dataclass
class Obstruction:
"""Something on a wall that cabinets cannot occupy."""
type: str # "window" | "door" | "column" | "chase" | "pipe"
# | "toilet" | "bathtub" | "shower" | "bidet"
x_start: float # Left edge, inches from wall origin
x_end: float # Right edge, inches from wall origin
notes: str = ""
@dataclass
class Anchor:
"""A point on the wall that constrains placement (e.g. sink center)."""
type: str # "sink_center", "range_center", "corner"
x_center: float # Center-line position, inches from wall origin
width: float # Width of the anchored object (e.g. sink base = 36")
notes: str = ""
@dataclass
class ApplianceSlot:
"""A fixed-width slot reserved for an appliance."""
type: str # Kitchen: "REF" | "RANGE" | "DW" | "MIC" | "HOOD" | "OVEN"
# Bathroom: "MED_CAB" | "LINEN"
x_start: float
width: float
notes: str = ""
@property
def x_end(self) -> float:
return self.x_start + self.width
@dataclass
class AvailableRun:
"""A contiguous segment of wall available for cabinet placement."""
x_start: float
x_end: float
anchors: List[Anchor] = field(default_factory=list)
@property
def length(self) -> float:
return self.x_end - self.x_start
@dataclass
class WallConstraints:
"""Fully solved constraints for one wall."""
wall_name: str
wall_length: float
obstructions: List[Obstruction] = field(default_factory=list)
anchors: List[Anchor] = field(default_factory=list)
appliance_slots: List[ApplianceSlot] = field(default_factory=list)
available_runs: List[AvailableRun] = field(default_factory=list)
windows: List[Obstruction] = field(default_factory=list)
is_ada: bool = False
issues: List[str] = field(default_factory=list)
# Standard clearance depths for bathroom fixtures (inches).
# Toilet: 30" clear in front (ADA: 48").
# Bathtub: no cabinet on tub-face wall.
# Shower: no cabinet on shower-face wall.
TOILET_CLEARANCE_DEPTH: float = 30.0
BATHTUB_CLEARANCE_DEPTH: float = 0.0 # full wall blocked
SHOWER_CLEARANCE_DEPTH: float = 0.0 # full wall blocked
class ConstraintExtractor:
"""
Phase 1: Reads raw architectural intent and produces typed constraint objects.
Does NOT compute available space — just classifies what's on the wall.
"""
@staticmethod
def extract(
wall_name: str,
wall_length: float,
openings: list,
appliances: list,
fixtures: list,
structural: list,
is_ada: bool = False,
) -> WallConstraints:
wc = WallConstraints(
wall_name=wall_name,
wall_length=wall_length,
is_ada=is_ada,
)
# Openings → Obstructions
# Doors are hard obstructions. Windows are soft (base cabinets can go under them).
# Bathroom fixtures that block the wall are also obstructions.
for o in openings:
x_in = float(getattr(o, 'x_in', 0) if hasattr(o, 'x_in') else o.get('x_in', 0))
w_in = float(getattr(o, 'width_in', 0) if hasattr(o, 'width_in') else o.get('width_in', 0))
o_type = getattr(o, 'type', '') if hasattr(o, 'type') else o.get('type', '')
notes = getattr(o, 'notes', '') if hasattr(o, 'notes') else o.get('notes', '')
if 'window' in o_type.lower():
wc.windows.append(Obstruction(
type=o_type,
x_start=x_in,
x_end=x_in + w_in,
notes=notes,
))
continue
# Bathroom fixtures that block the wall entirely
if o_type.lower() in ('bathtub', 'shower', 'toilet', 'bidet'):
wc.obstructions.append(Obstruction(
type=o_type,
x_start=x_in,
x_end=x_in + w_in,
notes=notes,
))
continue
wc.obstructions.append(Obstruction(
type=o_type,
x_start=x_in,
x_end=x_in + w_in,
notes=notes,
))
# Structural → Obstructions
for s in structural:
x_in = float(getattr(s, 'x_in', 0) if hasattr(s, 'x_in') else s.get('x_in', 0))
w_in = float(getattr(s, 'width_in', 0) if hasattr(s, 'width_in') else s.get('width_in', 0))
s_type = getattr(s, 'type', '') if hasattr(s, 'type') else s.get('type', '')
notes = getattr(s, 'notes', '') if hasattr(s, 'notes') else s.get('notes', '')
wc.obstructions.append(Obstruction(
type=s_type,
x_start=x_in,
x_end=x_in + w_in,
notes=notes,
))
# Fixtures → Anchors (sink center, vanity sink center, etc.)
for f in fixtures:
x_in = float(getattr(f, 'x_in', 0) if hasattr(f, 'x_in') else f.get('x_in', 0))
w_in = float(getattr(f, 'width_in', 0) if hasattr(f, 'width_in') else f.get('width_in', 0))
f_type = getattr(f, 'type', '') if hasattr(f, 'type') else f.get('type', '')
notes = getattr(f, 'notes', '') if hasattr(f, 'notes') else f.get('notes', '')
# Both kitchen sink and vanity sink become positional anchors
anchor_type = "vanity_sink_center" if 'vanity' in f_type.lower() else f"{f_type}_center"
wc.anchors.append(Anchor(
type=anchor_type,
x_center=x_in,
width=w_in,
notes=notes,
))
# Appliances → ApplianceSlots
for a in appliances:
x_in = float(getattr(a, 'x_in', 0) if hasattr(a, 'x_in') else a.get('x_in', 0))
w_in = float(getattr(a, 'width_in', 0) if hasattr(a, 'width_in') else a.get('width_in', 0))
a_type = getattr(a, 'type', '') if hasattr(a, 'type') else a.get('type', '')
notes = getattr(a, 'notes', '') if hasattr(a, 'notes') else a.get('notes', '')
wc.appliance_slots.append(ApplianceSlot(
type=a_type,
x_start=x_in,
width=w_in,
notes=notes,
))
return wc
class ConstraintSolver:
"""
Phase 2: Takes extracted constraints and computes available wall runs.
Subtracts all obstructions and appliance slots from the wall, producing
the contiguous free segments where cabinets can be placed.
"""
@staticmethod
def solve(wc: WallConstraints) -> WallConstraints:
# Build list of all occupied intervals [start, end]
occupied: list[tuple[float, float]] = []
for obs in wc.obstructions:
occupied.append((obs.x_start, obs.x_end))
for slot in wc.appliance_slots:
occupied.append((slot.x_start, slot.x_end))
# Sort by start position
occupied.sort(key=lambda x: x[0])
# Merge overlapping intervals
merged: list[tuple[float, float]] = []
for start, end in occupied:
if merged and start <= merged[-1][1]:
merged[-1] = (merged[-1][0], max(merged[-1][1], end))
else:
merged.append((start, end))
# Compute free segments
free_segments: list[tuple[float, float]] = []
cursor = 0.0
for occ_start, occ_end in merged:
if occ_start > cursor:
free_segments.append((cursor, occ_start))
cursor = max(cursor, occ_end)
if cursor < wc.wall_length:
free_segments.append((cursor, wc.wall_length))
# Build AvailableRun objects, attaching any anchors that fall within them
wc.available_runs = []
for seg_start, seg_end in free_segments:
run = AvailableRun(x_start=seg_start, x_end=seg_end)
for anchor in wc.anchors:
if seg_start <= anchor.x_center <= seg_end:
run.anchors.append(anchor)
wc.available_runs.append(run)
return wc
@@ -0,0 +1,204 @@
from typing import Dict, List
class DimensionEngine:
"""Generates standard CAD-compatible dimension objects."""
# ─────────────────────────────────────────────────────────────────────
# Formatting utility — single source of truth for all dimension labels
# ─────────────────────────────────────────────────────────────────────
@staticmethod
def format_dimension(inches: float) -> str:
"""
Convert a raw float in inches to a clean architectural label.
Rules:
- Round to the nearest 1/16"
- Format as: [feet'-inches fraction"]
e.g. 30.0 → 2'-6"
36.0 → 3'-0"
18.5 → 1'-6 1/2"
0.5 → 1/2"
29.9999→ 2'-6" (float safety)
Never outputs a raw decimal.
"""
# Guard
if inches < 0:
inches = 0.0
# Round to nearest 1/16"
sixteenths = round(inches * 16)
feet = sixteenths // 192 # 16 * 12 = 192 sixteenths per foot
rem16 = sixteenths % 192
whole_in = rem16 // 16
frac16 = rem16 % 16
# Fraction string
def _frac(f: int) -> str:
if f == 0: return ""
if f % 8 == 0: return f"{f // 8}/2"
if f % 4 == 0: return f"{f // 4}/4"
if f % 2 == 0: return f"{f // 2}/8"
return f"{f}/16"
frac_str = _frac(frac16)
if feet > 0:
if whole_in == 0 and not frac_str:
return f"{feet}'-0\""
elif not frac_str:
return f"{feet}'-{whole_in}\""
else:
return f"{feet}'-{whole_in} {frac_str}\""
else:
if whole_in == 0 and not frac_str:
return '0"'
elif not frac_str:
return f'{whole_in}"'
else:
return f'{whole_in} {frac_str}"'
# ─────────────────────────────────────────────────────────────────────
# Dimension generators
# ─────────────────────────────────────────────────────────────────────
@staticmethod
def generate_horizontal_chain(
components: List[Dict], start_x: float, y_pos: float, scale: float = 1.0
) -> List[Dict]:
"""
Generates continuous chain dimensions for a row of components.
Labels are formatted via format_dimension() — never raw floats.
Narrow segments are staggered vertically to avoid collision.
"""
dims = []
current_x = start_x
toggle_offset = False
for comp in components:
width = float(comp.get("width", 0))
is_blank = comp.get("blank", False)
if width > 0:
scaled_width = width * scale
if not is_blank:
# Stagger if the segment is narrow (e.g., filler or panel < 12cm = 4.7 inches)
# But actually, let's stagger anything < 15.0cm just in case.
current_y_pos = y_pos
if width < 20.0:
if toggle_offset:
current_y_pos += 8.0 # Push up
else:
current_y_pos -= 8.0 # Push down
toggle_offset = not toggle_offset
dims.append({
"start": [current_x, current_y_pos],
"end": [current_x + scaled_width, current_y_pos],
"text": DimensionEngine.format_dimension(width),
})
current_x += scaled_width
return dims
@staticmethod
def generate_vertical_chain(
components: List[Dict], x_pos: float, start_y: float, scale: float = 1.0
) -> List[Dict]:
"""
Generates continuous chain dimensions vertically.
Components should provide 'height' instead of 'width'.
"""
dims = []
current_y = start_y
toggle_offset = False
for comp in components:
height = float(comp.get("height", 0))
if height > 0:
scaled_height = height * scale
current_x_pos = x_pos
dims.append({
"start": [current_x_pos, current_y],
"end": [current_x_pos, current_y + scaled_height],
"text": DimensionEngine.format_dimension(height),
})
current_y += scaled_height
return dims
@staticmethod
def generate_overall_dimensions(
start_pos: List[float], end_pos: List[float], total_width: float
) -> Dict:
"""Generates the overall total dimension line."""
return {
"start": start_pos,
"end": end_pos,
"text": DimensionEngine.format_dimension(total_width),
}
@staticmethod
def generate_vertical_dimensions(
start_pos: List[float], end_pos: List[float], total_height: float
) -> Dict:
"""Generates overall vertical dimension."""
return {
"start": start_pos,
"end": end_pos,
"text": DimensionEngine.format_dimension(total_height),
}
@staticmethod
def generate_opening_dimensions(
start_pos: List[float], end_pos: List[float], width: float, label: str = "OPENING"
) -> Dict:
"""Generates dimension for appliance/fixture openings."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{DimensionEngine.format_dimension(width)} {label}",
}
@staticmethod
def generate_countertop_dimensions(
start_pos: List[float], end_pos: List[float], width: float
) -> Dict:
"""Generates countertop specific dimensions including overhangs."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{DimensionEngine.format_dimension(width)} C.TOP",
}
@staticmethod
def generate_appliance_dimensions(
start_pos: List[float], end_pos: List[float], width: float, label: str
) -> Dict:
"""Generates specific appliance dimension callouts."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{DimensionEngine.format_dimension(width)} {label}",
}
@staticmethod
def generate_clearance_dimensions(
start_pos: List[float],
end_pos: List[float],
width: float,
required_clearance: float,
) -> Dict:
"""Generates clearance dimensions for ADA validation."""
return {
"start": start_pos,
"end": end_pos,
"text": (
f"{DimensionEngine.format_dimension(width)} CLR "
f"(MIN {DimensionEngine.format_dimension(required_clearance)})"
),
}
@@ -0,0 +1,71 @@
from typing import Tuple, Dict
class DimensionFormatter:
"""Converts and formats dimensions for dual representation."""
@staticmethod
def inches_to_mm(inches: float) -> float:
"""Convert inches to millimeters."""
return round(inches * 25.4, 2)
@staticmethod
def format_imperial(inches: float) -> str:
"""Convert decimal inches to feet and inches.
Example:
98.62" → "8'-2 5/8\""
"""
feet = int(inches // 12)
remaining = inches - (feet * 12)
# Convert to fraction
frac_16ths = round(remaining * 16)
frac_inches = frac_16ths // 16
frac_num = frac_16ths % 16
if feet == 0:
if frac_num == 0:
return f"{int(frac_inches)}\""
else:
gcd_val = DimensionFormatter._gcd(frac_num, 16)
frac_num //= gcd_val
frac_den = 16 // gcd_val
return f"{int(frac_inches)} {frac_num}/{frac_den}\""
if frac_num == 0:
return f"{feet}'-{int(frac_inches)}\""
else:
# Simplify fraction
gcd_val = DimensionFormatter._gcd(frac_num, 16)
frac_num //= gcd_val
frac_den = 16 // gcd_val
return f"{feet}'-{int(frac_inches)} {frac_num}/{frac_den}\""
@staticmethod
def format_dual(inches: float) -> Dict[str, str]:
"""Return both metric and imperial formats.
Returns:
{
'metric': '228.60',
'metric_unit': 'mm',
'imperial': "7'-6\"",
'imperial_short': '228.6\"'
}
"""
mm = DimensionFormatter.inches_to_mm(inches)
imperial = DimensionFormatter.format_imperial(inches)
return {
'metric': f"{mm:.2f}",
'metric_unit': 'mm',
'imperial': imperial,
'imperial_short': f'{inches:.2f}"'
}
@staticmethod
def _gcd(a: int, b: int) -> int:
"""Calculate greatest common divisor."""
while b:
a, b = b, a % b
return a
@@ -0,0 +1,303 @@
"""
===========================================================================
core/engines/elevation_generator.py — Kitchen/Vanity Elevation Generator
===========================================================================
Generates elevation geometry for one or more walls.
Architecture (post-refactor):
- Each wall dict carries two SEPARATE cabinet lists:
"base_cfg" — base/tall/appliance cabinets
"upper_cfg" — wall/upper cabinets
These are passed to ElevationLayout.build_two_tier(), which runs two
independent cursors so uppers are never misplaced off the wall.
- Shared reference lines computed once per elevation via RefLines.
- ElevationLayout.validate() runs before rendering and embeds a visible
warning on the drawing instead of crashing the whole PDF pipeline.
- All dimension labels go through DimensionEngine.format_dimension() —
no raw floats ever reach the renderer.
- Elevation title is placed ABOVE the wall border (ceiling_y + 12")
so it never collides with the bottom dimension chain.
===========================================================================
"""
from __future__ import annotations
from typing import Dict, List, Any
from core.engines.appliance_library import ApplianceLibrary
from core.engines.dimension_engine import DimensionEngine
from core.engines.cabinet_renderer import CabinetRendererFactory
from core.engines.elevation_layout import ElevationLayout
class ElevationGenerator:
"""Generates the Kitchen/Vanity Elevation geometry."""
@staticmethod
def generate(
walls: List[Dict],
start_ox: float,
start_oy: float,
ceiling_height: float = 96.0,
scale_x: float = 4.0,
scale_y: float = 3.0,
) -> Dict[str, List]:
"""
Parameters
----------
walls : list of wall dicts, each with:
"name" (str)
"length" (float, inches)
"base_cfg" (list of base/tall cabinet dicts)
"upper_cfg" (list of upper cabinet dicts)
Legacy key "cabinets" (flat merged list) is also
accepted for backward compatibility — it is passed
to build() (single-cursor) instead of build_two_tier().
start_ox/oy : canvas origin for the first wall (PDF points).
ceiling_height : wall height in inches.
scale_x/y : pts per inch.
"""
geom: Dict[str, List] = {"lines": [], "blocks": [], "texts": [], "dimensions": []}
elev_ox = start_ox
elev_oy = start_oy
for w_idx, wall in enumerate(walls):
wall_length = wall.get("length", 90.0)
is_ada = wall.get("is_ada", False)
# ── offset origin for subsequent walls ────────────────────────
if w_idx > 0:
prev_length = walls[w_idx - 1].get("length", 90.0)
elev_ox += prev_length * scale_x + 100.0
# ── build validated layout ────────────────────────────────────
base_cfg = wall.get("base_cfg", None)
upper_cfg = wall.get("upper_cfg", None)
if base_cfg is not None:
# Two-tier path (preferred)
layout = ElevationLayout.build_two_tier(
base_cfg = base_cfg,
upper_cfg = upper_cfg or [],
wall_length_in = wall_length,
ceiling_h_in = ceiling_height,
is_ada = is_ada,
)
else:
# Legacy flat-list path (single-tier walls only)
layout = ElevationLayout.build(
segments_cfg = wall.get("cabinets", []),
wall_length_in = wall_length,
ceiling_h_in = ceiling_height,
is_ada = is_ada,
)
# Validate — hard structural errors become a drawing banner; soft
# NKBA guideline warnings are annotated below it without blocking.
try:
layout.validate()
except ValueError as exc:
geom["texts"].append({
"pos": [elev_ox + 10, elev_oy + ceiling_height * scale_y / 2],
"text": f"⚠ LAYOUT ERROR: {exc}",
"layer": "TEXT_ERROR",
"size": 5,
})
# Soft NKBA guideline warnings — annotated on the drawing, not fatal
for i, warn in enumerate(layout.warnings):
geom["texts"].append({
"pos": [elev_ox + 10, elev_oy - (25 + i * 8)],
"text": f"⚑ {warn}",
"layer": "TEXT_NKBA_WARN",
"size": 3.5,
})
ref = layout.ref
# ── elevation title — ABOVE the wall border ───────────────────
title_y = elev_oy + (ceiling_height + 25.0) * scale_y
geom["texts"].append({
"pos": [elev_ox + wall_length * scale_x / 2.0, title_y],
"text": f"{wall.get('name', 'WALL')} ELEVATION VIEW",
"layer": "TEXT",
"size": 6,
"anchor": "center",
})
# ── render each segment ───────────────────────────────────────
dim_items: List[Dict] = []
upper_dim_items: List[Dict] = []
for seg in layout.segments:
x0 = elev_ox + seg.x_in * scale_x
x1 = elev_ox + seg.x1_in * scale_x
y0 = elev_oy + seg.y0_in * scale_y
y1 = elev_oy + seg.y1_in * scale_y
# Collect width for the base-tier dimension chain
if not seg.is_upper:
if seg.is_bathtub:
dim_items.append({"width": seg.width_in, "blank": True})
elif seg.is_toilet:
dim_items.append({"width": seg.width_in / 2.0})
dim_items.append({"width": seg.width_in / 2.0})
else:
dim_items.append({"width": seg.width_in})
else:
upper_dim_items.append({"width": seg.width_in, "x_in": seg.x_in})
# ── dispatch to the right renderer ───────────────────────
if seg.is_ref:
app_geom = ApplianceLibrary.draw_refrigerator_elevation(
x0, elev_oy, seg.width_in, seg.height_in,
scale_x, scale_y, label=seg.label,
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif seg.is_dw:
app_geom = ApplianceLibrary.draw_dishwasher_elevation(
x0, y0, seg.width_in, seg.height_in, scale_x, scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif seg.is_range:
app_geom = ApplianceLibrary.draw_range_elevation(
x0, elev_oy, seg.width_in, scale_x, scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif seg.is_toilet:
app_geom = ApplianceLibrary.draw_toilet_elevation(
x0, elev_oy, seg.width_in, scale_x, scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif seg.is_bathtub:
app_geom = ApplianceLibrary.draw_bathtub_elevation(
x0, elev_oy, seg.width_in, height=18.0, scale_x=scale_x, scale_y=scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif seg.is_dw:
app_geom = ApplianceLibrary.draw_dishwasher_elevation(
x0, elev_oy, seg.width_in, seg.height_in or ref.counter_top_y, scale_x, scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
else:
cab_geom = CabinetRendererFactory.render_elevation(
{"cabinet_id": seg.label, "is_ada": seg.is_ada},
x0, y0, x1, y1,
seg.is_upper, seg.is_tall, seg.is_drawer,
seg.render_style, scale_x, scale_y,
)
geom["blocks"].extend(cab_geom["blocks"])
geom["lines"].extend(cab_geom["lines"])
geom["texts"].extend(cab_geom["texts"])
if seg.is_sink:
sink_geom = ApplianceLibrary.draw_sink_elevation(
x0, y1, seg.width_in, scale_x, scale_y
)
geom["lines"].extend(sink_geom["lines"])
# ── toe kick for base cabs ────────────────────────────────
if (not seg.is_upper and not seg.is_tall and not seg.is_ref
and not seg.is_range and not seg.is_toilet and not seg.is_bathtub
and seg.render_style != "panel"):
geom["blocks"].append({
"type": "rect",
"coords": [x0, elev_oy, x1 - x0, y0 - elev_oy],
"layer": "CABINETS_BASE",
"style": "solid",
})
# ── base-tier dimension chain (below floor line) ──────────────
dim_y = elev_oy - 10.0
geom["dimensions"].extend(
DimensionEngine.generate_horizontal_chain(dim_items, elev_ox, dim_y, scale_x)
)
# ── upper-tier dimension chain (above ceiling line) ───────────
upper_dim_y = elev_oy + (ceiling_height + 5.0) * scale_y
if upper_dim_items:
# upper_dim_items might not be contiguous if there's a gap, but for now we just use the chain.
# Since the width sum might not equal wall length, generate_horizontal_chain just adds them up.
geom["dimensions"].extend(
DimensionEngine.generate_horizontal_chain(upper_dim_items, elev_ox, upper_dim_y, scale_x)
)
# ── overall dimension (above ceiling) ─────────────────────────
overall_y = elev_oy + (ceiling_height + 15.0) * scale_y
geom["dimensions"].append(
DimensionEngine.generate_overall_dimensions(
[elev_ox, overall_y],
[elev_ox + wall_length * scale_x, overall_y],
wall_length,
)
)
# ── vertical dimension chains (left and right) ────────────────
vert_dims = [
{"height": ref.counter_top_y},
{"height": 1.6},
{"height": ref.wall_cab_bot_y - ref.counter_top_y - 1.6},
{"height": ref.wall_cab_top_y - ref.wall_cab_bot_y}
]
geom["dimensions"].extend(
DimensionEngine.generate_vertical_chain(vert_dims, elev_ox - 10.0 * scale_x, elev_oy, scale_y)
)
geom["dimensions"].extend(
DimensionEngine.generate_vertical_chain(vert_dims, elev_ox + wall_length * scale_x + 10.0 * scale_x, elev_oy, scale_y)
)
# overall vertical dimension
geom["dimensions"].append(
DimensionEngine.generate_overall_dimensions(
[elev_ox - 20.0 * scale_x, elev_oy],
[elev_ox - 20.0 * scale_x, elev_oy + ref.wall_cab_top_y * scale_y],
ref.wall_cab_top_y,
)
)
geom["dimensions"].append(
DimensionEngine.generate_overall_dimensions(
[elev_ox + wall_length * scale_x + 20.0 * scale_x, elev_oy],
[elev_ox + wall_length * scale_x + 20.0 * scale_x, elev_oy + ref.wall_cab_top_y * scale_y],
ref.wall_cab_top_y,
)
)
# ── wall border ───────────────────────────────────────────────
w_pt = wall_length * scale_x
h_pt = ceiling_height * scale_y
geom["lines"].append({"start": [elev_ox, elev_oy ], "end": [elev_ox + w_pt, elev_oy ], "layer": "WALLS", "style": "continuous"})
geom["lines"].append({"start": [elev_ox + w_pt, elev_oy ], "end": [elev_ox + w_pt, elev_oy + h_pt], "layer": "WALLS", "style": "continuous"})
geom["lines"].append({"start": [elev_ox + w_pt, elev_oy + h_pt], "end": [elev_ox, elev_oy + h_pt], "layer": "WALLS", "style": "continuous"})
# ── countertop callout ────────────────────────────────────────────
c_x = elev_ox + (wall_length / 2.0) * scale_x
c_y = elev_oy + ref.counter_top_y * scale_y
text_y = c_y + 15.0 * scale_y
geom["lines"].append({"start": [c_x + 20.0 * scale_x, text_y], "end": [c_x + 5.0 * scale_x, text_y], "layer": "CALLOUTS", "style": "continuous"})
geom["lines"].append({"start": [c_x + 5.0 * scale_x, text_y], "end": [c_x, c_y], "layer": "CALLOUTS", "style": "continuous"})
geom["texts"].append({
"pos": [c_x + 22.0 * scale_x, text_y],
"text": "COUNTERTOP BY OTHERS",
"layer": "CALLOUTS",
"size": 4.0,
"anchor": "left"
})
return geom
@@ -0,0 +1,490 @@
"""
===========================================================================
core/engines/elevation_layout.py — Validated Elevation Layout Model
===========================================================================
Builds a single, validated data model for one elevation wall.
Two-tier cursor model (replaces single flat-list cursor):
- Base tier cursor : starts at x=0, walks left-to-right through base/tall
- Upper tier cursor : starts at tall_right_in (REF/tall right edge, or 0 if
no tall column), walks left-to-right through uppers
The two tiers are fully independent — the upper cursor never inherits the
base cursor's position, and no UPPER_SPACER is needed or accepted.
API:
layout = ElevationLayout.build_two_tier(
base_cfg = wall_data["cabinets"], # list of base/tall dicts
upper_cfg = wall_data["uppers"], # list of upper dicts
wall_length_in = wall["length"],
ceiling_h_in = ceiling_height,
is_ada = False,
)
layout.validate() # raises ValueError on bad geometry
for seg in layout.segments:
...render seg...
Legacy single-list API (build()) is still available for callers that
already have a pre-merged segment list (e.g. appliance-only walls).
===========================================================================
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Optional
# Tolerance (inches) for the width-sum vs wall-length check
_WIDTH_TOL = 0.5 # ~1.3 cm — generous for rounding in cm→inch conversion
_OVERLAP_TOL = 0.01 # pts — effectively zero
@dataclass
class RefLines:
"""
All shared horizontal reference lines for one elevation wall.
All values are in raw inches (before scale is applied in the renderer).
floor_y = 0.0 (local coordinate — caller adds elev_oy when rendering)
"""
floor_y: float = 0.0
toe_top_y: float = 4.0 # top of toe-kick (standard 4" toe)
counter_top_y: float = 34.5 # top of base cabinet / counter height
wall_cab_bot_y: float = 54.0 # bottom of wall cabinet run (AFF for standard)
wall_cab_top_y: float = 84.0 # top of wall cabinet run (= bot + cabinet height)
ceiling_y: float = 96.0 # ceiling / soffit
@dataclass
class Segment:
"""One unit in the ordered elevation layout."""
index: int
label: str
seg_type: str # 'base', 'upper', 'tall', 'ref', 'dw', 'range',
# 'sink_base', 'drawer_base', 'vanity', 'toilet',
# 'filler', 'panel'
width_in: float
height_in: float
x_in: float # left edge — always set by cursor, never assumed
# Snapped y bounds (inches, local coords — add elev_oy when scaling)
y0_in: float # bottom of cabinet body (above toe kick)
y1_in: float # top of cabinet body
render_style: str = "standard"
is_ada: bool = False
# Explicit placement tier set by the factory, not inferred from flags.
# "base" = placed by the base-cursor; "upper" = placed by the upper-cursor.
# Panels/fillers in the upper list have is_upper=False but tier="upper".
tier: str = "base"
# Convenience flags
is_upper: bool = False
is_tall: bool = False
is_ref: bool = False
is_dw: bool = False
is_range: bool = False
is_sink: bool = False
is_drawer: bool = False
is_toilet: bool = False
is_bathtub: bool = False
# NOTE: is_spacer intentionally removed — UPPER_SPACER mechanism deleted.
# Use build_two_tier() instead, which positions uppers correctly without spacers.
@property
def x1_in(self) -> float:
return self.x_in + self.width_in
def bbox(self):
"""Returns (x0, y0, x1, y1) in local inches."""
return (self.x_in, self.y0_in, self.x1_in, self.y1_in)
class ElevationLayout:
"""
Validated, two-tier-cursor-placed layout for one elevation wall.
After calling validate(), check `layout.warnings` for soft NKBA guideline
issues. Hard structural errors (overlaps, width-mismatch, upper overflow)
still raise ValueError so callers can surface them as drawing banners.
"""
def __init__(self, segments: List[Segment], ref: RefLines, wall_length_in: float):
self.segments = segments
self.ref = ref
self.wall_length_in = wall_length_in
# Soft NKBA warnings populated by validate() — don't block generation
self.warnings: List[str] = []
# ─────────────────────────────────────────────────────────────────────
# Primary factory — two-tier cursor
# ─────────────────────────────────────────────────────────────────────
@classmethod
def build_two_tier(
cls,
base_cfg: List[dict],
upper_cfg: List[dict],
wall_length_in: float,
ceiling_h_in: float = 96.0,
is_ada: bool = False,
) -> "ElevationLayout":
"""
Build the layout from two SEPARATE, independent segment lists.
base_cfg — base + tall + appliance (REF, DW, range) cabinets,
in left-to-right order. Cursor starts at x=0.
upper_cfg — wall/upper cabinets, in left-to-right order.
Cursor starts at the right edge of the first REF/tall
column in the base run (or 0 if none).
Neither list should contain UPPER_SPACER entries. The upper
cursor is positioned automatically based on the base-tier geometry.
Each dict must have at minimum:
- width (float, inches)
- height (float, inches) — body height, NOT total with toe
- type (str) — cabinet family hint
- id or cabinet_id (str) — used for appliance detection
"""
ref = _compute_ref_lines(ceiling_h_in, is_ada)
segments: List[Segment] = []
seg_index = 0
# ── Tier 1: base run (cursor from x=0) ───────────────────────────
base_cursor = 0.0
tall_left_in = 0.0
tall_right_in = 0.0 # will be set to REF/tall right edge if found
for cab in base_cfg:
seg, base_cursor = _make_segment(cab, seg_index, base_cursor, ref, is_ada)
seg.tier = "base" # explicit tier — panels/fillers in base stay base
seg_index += 1
# Track the REF/tall edges for the upper cursor start
if seg.is_tall or seg.is_ref:
if tall_right_in == 0.0:
tall_left_in = seg.x_in
tall_right_in = max(tall_right_in, seg.x1_in)
segments.append(seg)
# ── Tier 2: upper run ──────────────────────────────────────────────────
# If the tall cabinet is on the left edge, uppers start after it.
# Otherwise, they start at 0.
upper_cursor = tall_right_in if (tall_left_in <= 0.1 and tall_right_in > 0.0) else 0.0
for cab in upper_cfg:
if cab.get("anchor") == "over_tall":
upper_cursor = tall_left_in
seg, upper_cursor = _make_segment(cab, seg_index, upper_cursor, ref, is_ada)
seg.tier = "upper" # explicit tier — panels/fillers in upper list stay upper
seg_index += 1
segments.append(seg)
return cls(segments, ref, wall_length_in)
# ─────────────────────────────────────────────────────────────────────
# Legacy single-list factory (kept for appliance-only / test use)
# ─────────────────────────────────────────────────────────────────────
@classmethod
def build(
cls,
segments_cfg: List[dict],
wall_length_in: float,
ceiling_h_in: float = 96.0,
is_ada: bool = False,
) -> "ElevationLayout":
"""
Build from a single pre-ordered list. Suitable for walls that have
only base cabinets or only upper cabinets (e.g. appliance walls,
simple vanities, toilet walls).
WARNING: Do NOT pass base + upper cabinets in one list — the cursor
never resets between tiers, so uppers will land at the wrong x.
Use build_two_tier() for two-tier walls.
"""
ref = _compute_ref_lines(ceiling_h_in, is_ada)
segments: List[Segment] = []
cursor_x = 0.0
for i, cab in enumerate(segments_cfg):
seg, cursor_x = _make_segment(cab, i, cursor_x, ref, is_ada)
segments.append(seg)
return cls(segments, ref, wall_length_in)
# ─────────────────────────────────────────────────────────────────────
# Validation
# ─────────────────────────────────────────────────────────────────────
def validate(self) -> None:
"""
Raises ValueError with a descriptive message if any of:
Base tier:
- Width sum of base/tall segments diverges from wall_length_in
- Any two base/tall bounding boxes overlap
Upper tier:
- The upper run ends past the wall right edge
- Any two upper bounding boxes overlap
"""
# Use explicit tier field — panels/fillers in the upper config have
# is_upper=False but tier="upper", so they must NOT be counted in base_sum.
base_segs = [s for s in self.segments if s.tier == "base"]
upper_segs = [s for s in self.segments if s.tier == "upper"]
# 1. Base-tier width-sum check
base_sum = sum(s.width_in for s in base_segs)
if base_sum > 0 and abs(base_sum - self.wall_length_in) > _WIDTH_TOL:
raise ValueError(
f"width mismatch: base segments sum to {base_sum:.4f}\" "
f"but wall_length is {self.wall_length_in:.4f}\" "
f"(delta = {base_sum - self.wall_length_in:+.4f}\")"
)
# 2. Upper-tier right-edge check
if upper_segs:
upper_end = max(s.x1_in for s in upper_segs)
if upper_end > self.wall_length_in + _WIDTH_TOL:
hint = " (Hint: If an over-fridge cabinet is pushing the run out, ensure it has 'anchor': 'over_tall' in the config.)"
raise ValueError(
f"ElevationLayout upper run overflows wall: upper run ends at "
f"{upper_end:.4f}\" but wall_length is {self.wall_length_in:.4f}\" "
f"(overflow = {upper_end - self.wall_length_in:+.4f}\"){hint}"
)
# 3. Overlap check — within each tier independently
for tier_label, tier in (("base", base_segs), ("upper", upper_segs)):
for i, a in enumerate(tier):
for b in tier[i + 1:]:
if _boxes_overlap(a.bbox(), b.bbox()):
raise ValueError(
f"ElevationLayout {tier_label}-tier overlap: "
f"segment {a.index} ({a.label!r}, "
f"x={a.x_in:.2f}\"..{a.x1_in:.2f}\") overlaps "
f"segment {b.index} ({b.label!r}, "
f"x={b.x_in:.2f}\"..{b.x1_in:.2f}\")"
)
# ── 4. NKBA Guideline Checks (SOFT — appended to self.warnings, never raised) ──
#
# Rationale: A cabinet overlap or width mismatch means the drawing is
# physically impossible and must block generation. A dishwasher placed
# 40" from the sink or a range without a dedicated hood is a best-practice
# deviation that real small kitchens do intentionally — it should appear as
# an annotation on the drawing, not crash the whole sheet.
self.warnings.clear()
sinks = [s for s in base_segs if s.is_sink]
dws = [s for s in base_segs if s.is_dw]
ranges = [s for s in base_segs if s.is_range]
# Vent detection: check id, label, AND seg_type so WMH (label='') still matches.
def _is_vent(s: Segment) -> bool:
haystack = (s.label + " " + s.seg_type).lower()
id_lower = s.label.lower() # label was set from id in _make_segment
# Also peek at the raw cabinet id stored as the label when label==id
return any(kw in haystack for kw in ("hood", "mic", "vent", "wmh", "microwave"))
vents = [s for s in upper_segs if _is_vent(s)]
for dw in dws:
if not sinks:
# Skip — sink may be on a different wall (island kitchen, split layout)
continue
dw_center = dw.x_in + dw.width_in / 2.0
closest_sink = min(sinks, key=lambda s: abs((s.x_in + s.width_in / 2.0) - dw_center))
dist = abs((closest_sink.x_in + closest_sink.width_in / 2.0) - dw_center)
max_dist = (closest_sink.width_in / 2.0) + 36.0 + (dw.width_in / 2.0)
if dist > max_dist + _WIDTH_TOL:
self.warnings.append(
f"NKBA GUIDELINE: Dishwasher is {dist:.1f}\" from sink center "
f"(max recommended {max_dist:.1f}\" edge-to-edge)."
)
for rng in ranges:
rng_center = rng.x_in + rng.width_in / 2.0
has_vent = any(
abs(rng_center - (v.x_in + v.width_in / 2.0)) < (rng.width_in / 2.0 + 6.0)
for v in vents
)
if not has_vent:
self.warnings.append(
f"NKBA GUIDELINE: Range/Stove at x={rng.x_in:.1f}\" has no overhead "
f"ventilation (Hood or OTR Microwave) detected on this wall."
)
# ─────────────────────────────────────────────────────────────────────
# Convenience accessors
# ─────────────────────────────────────────────────────────────────────
def base_run_end_x(self) -> float:
"""X coordinate of the right edge of the last base/tall segment."""
base_segs = [s for s in self.segments if not s.is_upper]
if not base_segs:
return 0.0
return max(s.x1_in for s in base_segs)
def upper_run_start_x(self) -> float:
"""
Upper cabinets left-align to start after the first tall/REF column's
right edge. If no tall/REF column exists they start from x=0.
"""
tall_segs = [s for s in self.segments if s.is_tall or s.is_ref]
if tall_segs:
return max(s.x1_in for s in tall_segs)
return 0.0
def __repr__(self) -> str:
segs = ", ".join(f"{s.label}({s.width_in:.1f}\"@{s.x_in:.1f}\")" for s in self.segments)
return f"ElevationLayout(wall={self.wall_length_in:.1f}\", segs=[{segs}])"
# ─────────────────────────────────────────────────────────────────────────
# Private helpers
# ─────────────────────────────────────────────────────────────────────────
def _classify(cab_id: str, cab_type: str):
"""Return classification flags for one cabinet dict."""
cab_id_lower = cab_id.lower()
cab_type = cab_type.lower()
is_upper = ("upper" in cab_type or "wall" in cab_type) and "spacer" not in cab_type
is_upper = is_upper or (cab_id.startswith("W") and "spacer" not in cab_type)
is_tall = "pantry" in cab_type or "tall" in cab_type or cab_id.startswith("T")
is_ref = "ref" in cab_type or "refrigerator" in cab_id_lower or "ref" in cab_id_lower
is_dw = "dw" in cab_type or "dishwasher" in cab_id_lower or "dw" in cab_id_lower
is_range = "range" in cab_type or "range" in cab_id_lower or "cooktop" in cab_id_lower
is_sink = "sink" in cab_type or cab_id.startswith("SB")
is_drawer = "drawer" in cab_type or cab_id.startswith("DB") or cab_id.startswith("3DB")
is_toilet = "toilet" in cab_type or "toilet" in cab_id_lower
is_vanity = "vanity" in cab_type or cab_id.startswith("V") or "ada_vanity" in cab_type
is_bathtub = "bathtub" in cab_type or "tub" in cab_id_lower or "tub" in cab_type
is_filler = "filler" in cab_type or cab_id.startswith("F") or cab_id.startswith("BF")
is_panel = "panel" in cab_type or cab_id.startswith("P") or cab_id.startswith("BEP") or cab_id.startswith("WEP")
return (is_upper, is_tall, is_ref, is_dw, is_range,
is_sink, is_drawer, is_toilet, is_bathtub, is_vanity, is_filler, is_panel)
def _make_segment(
cab: dict,
index: int,
cursor_x: float,
ref: RefLines,
is_ada: bool,
force_upper: bool = False,
) -> tuple:
"""
Build one Segment from a cabinet dict, advancing cursor_x by its width.
Returns (Segment, new_cursor_x).
"""
cab_id = cab.get("cabinet_id", cab.get("id", "CAB")).upper()
cab_type = cab.get("cabinet_type", cab.get("type", "")).lower()
label = cab.get("label", cab_id) or cab_id # explicit "" falls back to cab_id
w_in = float(cab.get("width", 0.0))
h_in = float(cab.get("height", 0.0))
(is_upper, is_tall, is_ref, is_dw, is_range,
is_sink, is_drawer, is_toilet, is_bathtub, is_vanity, is_filler, is_panel) = _classify(cab_id, cab_type)
if force_upper:
is_upper = True
is_tall = False
# Derive render_style
if cab.get("is_section"): render_style = "section"
elif is_filler: render_style = "filler"
elif is_panel: render_style = "panel"
elif is_sink: render_style = "sink_base"
elif is_drawer: render_style = "drawer_base"
elif is_vanity: render_style = "vanity"
else: render_style = "standard"
y0_in, y1_in = _snap_to_ref(ref, h_in, is_upper, is_tall, is_ref, is_ada)
# FIX: Panels and fillers should start from the floor, not the top of the toe kick
if is_panel or is_filler:
if not is_upper:
y1_in = y0_in + h_in if h_in > 0 else (ref.counter_top_y if not is_tall else ref.wall_cab_top_y)
y0_in = ref.floor_y
# If the dict provided an explicit x, use it. Otherwise, use sequential cursor.
explicit_x = cab.get("x")
if explicit_x is not None:
cursor_x = float(explicit_x)
seg = Segment(
index = index,
label = label,
seg_type = cab_type or ("upper" if is_upper else ("tall" if is_tall else "base")),
width_in = w_in,
height_in = h_in,
x_in = cursor_x,
y0_in = y0_in,
y1_in = y1_in,
render_style= render_style,
is_ada = is_ada,
is_upper = is_upper,
is_tall = is_tall,
is_ref = is_ref,
is_dw = is_dw,
is_range = is_range,
is_sink = is_sink,
is_drawer = is_drawer,
is_toilet = is_toilet,
is_bathtub = is_bathtub,
)
return seg, cursor_x + w_in
def _compute_ref_lines(ceiling_h_in: float, is_ada: bool) -> RefLines:
"""Compute the shared wall reference lines for one elevation."""
toe_top = 4.0
counter = 32.5 if is_ada else 34.5
wall_bot = 48.0 if is_ada else 54.0
wall_top = wall_bot + 30.0
return RefLines(
floor_y = 0.0,
toe_top_y = toe_top,
counter_top_y = counter,
wall_cab_bot_y= wall_bot,
wall_cab_top_y= wall_top,
ceiling_y = ceiling_h_in,
)
def _snap_to_ref(
ref: RefLines,
h_in: float,
is_upper: bool,
is_tall: bool,
is_ref: bool,
is_ada: bool,
) -> tuple:
"""
Returns (y0_in, y1_in) snapped to the appropriate shared reference lines.
All values are LOCAL inches (caller adds elev_oy and multiplies by scale).
"""
if is_tall or is_ref:
y0 = ref.floor_y
y1 = h_in if h_in > 0 else ref.wall_cab_top_y
elif is_upper:
actual_h = h_in if h_in > 0 else 30.0
y1 = ref.wall_cab_top_y
y0 = y1 - actual_h
else:
actual_h = h_in if h_in > 0 else ref.counter_top_y
y0 = ref.toe_top_y
y1 = ref.toe_top_y + actual_h
return (y0, y1)
def _boxes_overlap(a: tuple, b: tuple, tol: float = _OVERLAP_TOL) -> bool:
"""
Returns True if two (x0, y0, x1, y1) boxes overlap more than tol in BOTH axes.
Touching edges (x1_a == x0_b) do not count as overlapping.
"""
ax0, ay0, ax1, ay1 = a
bx0, by0, bx1, by1 = b
x_overlap = ax0 < bx1 - tol and ax1 > bx0 + tol
y_overlap = ay0 < by1 - tol and ay1 > by0 + tol
return x_overlap and y_overlap
@@ -0,0 +1,139 @@
from typing import Dict, List, Any
from core.engines.appliance_library import ApplianceLibrary
from core.engines.dimension_engine import DimensionEngine
class FloorPlanGenerator:
"""Generates the Kitchen/Vanity Floor Plan geometry."""
@staticmethod
def generate(walls: List[Dict], start_ox: float, start_oy: float, scale_factor: float = 4.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": [], "dimensions": []}
plan_ox = start_ox
plan_oy = start_oy
for w_idx, wall in enumerate(walls):
wall_length = wall.get("length", 90.0)
base_cfg = wall.get("base_cfg", [])
upper_cfg = wall.get("upper_cfg", [])
legacy_cabinets = wall.get("cabinets", [])
if not base_cfg and not upper_cfg and legacy_cabinets:
base_cfg = legacy_cabinets # Fallback for old tests
dim_items = []
if w_idx > 0:
prev_length = walls[w_idx - 1].get("length", 90.0)
offset_x = (prev_length * scale_factor) + 100.0
plan_ox += offset_x
# Draw wall with thickness
wall_depth = 6.0 * scale_factor
wall_len = wall_length * scale_factor
geom["blocks"].append({
"type": "rect",
"coords": [plan_ox, plan_oy, wall_len, wall_depth],
"id": "", "layer": "WALLS", "style": "solid"
})
# Label the wall plan view
geom["texts"].append({
"pos": [plan_ox + wall_len/2.0 - 15.0, plan_oy - 20.0],
"text": f"{wall.get('name', 'WALL')} PLAN VIEW",
"layer": "TEXT"
})
def _draw_cabs(cabs, is_upper_tier):
# Separate over_tall from main
over_tall_cabs = [c for c in cabs if c.get("anchor") == "over_tall"]
main_cabs = [c for c in cabs if c.get("anchor") != "over_tall"]
tall_width = 0.0
if is_upper_tier:
tall_segs = [c for c in base_cfg if "ref" in c.get("type", "").lower() or "tall" in c.get("type", "").lower() or "pantry" in c.get("type", "").lower() or (c.get("id") or "").startswith("P")]
if tall_segs:
tall_width = sum(c.get("width", 0) for c in tall_segs)
def _draw_group(group_cabs, start_x):
cab_x_curr = start_x
for cab in group_cabs:
cab_id = cab.get("cabinet_id", cab.get("id", "Cab"))
cab_type = cab.get("cabinet_type", cab.get("type", "")).lower()
cab_w = cab.get("width", 0.0)
cab_d = cab.get("depth", 24.0) if not is_upper_tier else cab.get("depth", 12.0)
if cab_d <= 0:
cab_d = 24.0 if not is_upper_tier else 12.0
is_upper = is_upper_tier or cab_id.upper().startswith("W") or "upper" in cab_type
is_sink = "sink" in cab_type or cab_id.upper().startswith("SB")
is_range = "range" in cab_type or "range" in cab_id.lower() or "cooktop" in cab_id.lower()
is_ref = "ref" in cab_type or "refrigerator" in cab_id.lower()
is_dw = "dw" in cab_type or "dishwasher" in cab_id.lower()
is_toilet = "toilet" in cab_type or "toilet" in cab_id.lower()
cab_x_val = cab.get("x")
if cab_x_val is None:
cab_x_val = cab_x_curr
if not is_upper:
dim_items.append({"width": cab_w})
x0 = plan_ox + cab_x_val * scale_factor
y0 = plan_oy + wall_depth
if is_upper:
# Draw dashed hidden overhead footprint
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, cab_w * scale_factor, cab_d * scale_factor],
"id": cab_id, "layer": "CABINETS_UPPER", "style": "dashed"
})
elif is_toilet:
# Toilets do not have a standard rectangular footprint
toilet_geom = ApplianceLibrary.draw_toilet_plan(x0, y0, width=cab_w, depth=cab_d, scale_x=scale_factor, scale_y=scale_factor)
geom["blocks"].extend(toilet_geom["blocks"])
geom["lines"].extend(toilet_geom.get("lines", []))
else:
# Base footprint
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, cab_w * scale_factor, cab_d * scale_factor],
"id": cab_id, "layer": "CABINETS_BASE", "style": "solid"
})
if is_sink:
sink_geom = ApplianceLibrary.draw_sink_plan(x0, y0, cab_w, cab_d, scale_factor, scale_factor)
geom["blocks"].extend(sink_geom["blocks"])
geom["lines"].extend(sink_geom["lines"])
elif is_range:
rng_geom = ApplianceLibrary.draw_range_plan(x0, y0, cab_w, cab_d, scale_factor, scale_factor)
geom["blocks"].extend(rng_geom["blocks"])
geom["lines"].extend(rng_geom["lines"])
elif is_ref:
geom["texts"].append({"pos": [x0 + (cab_w*scale_factor)/2, y0 + (cab_d*scale_factor)/2], "text": "REF", "size": 4.0, "layer": "TEXT"})
elif is_dw:
geom["texts"].append({"pos": [x0 + (cab_w*scale_factor)/2, y0 + (cab_d*scale_factor)/2], "text": "D/W", "size": 4.0, "layer": "TEXT"})
if cab.get("x") is None:
cab_x_curr += cab_w
_draw_group(over_tall_cabs, 0.0)
_draw_group(main_cabs, tall_width if is_upper_tier else 0.0)
_draw_cabs(base_cfg, is_upper_tier=False)
_draw_cabs(upper_cfg, is_upper_tier=True)
# Add Horizontal Chain Dimension
chain_dims = DimensionEngine.generate_horizontal_chain(dim_items, plan_ox, plan_oy + wall_depth + 30.0 * scale_factor, scale_factor)
geom["dimensions"].extend(chain_dims)
# Add Overall Dimension
geom["dimensions"].append(DimensionEngine.generate_overall_dimensions(
[plan_ox, plan_oy + wall_depth + 38.0 * scale_factor],
[plan_ox + wall_length * scale_factor, plan_oy + wall_depth + 38.0 * scale_factor],
wall_length
))
return geom
@@ -0,0 +1,222 @@
"""
===========================================================================
core/engines/layout_fingerprint_engine.py — Layout Fingerprint Builder
===========================================================================
Phase 4: Generates deterministic fingerprints for kitchen/vanity layouts.
CLASSIFICATION INVARIANT POLICY:
- Abutting cabinet widths are pinned to catalog-standard values.
- ONLY the filler absorbs wall-length variance.
- If standard catalog blocks change (e.g. B36 drops to B33 because
the catalog matched a different block), it IS a different kitchen type.
- If the catalog blocks remain identical, but a 2" filler becomes a 3"
filler to absorb variance, it is the SAME kitchen type.
Implementation:
The fingerprint includes:
- Layout topology (Straight, L-Shape, U-Shape)
- Ordered sequence of catalog cabinet types and widths (NOT fillers)
- Appliance sequence and widths
- Opening types and positions (relative, not absolute)
- ADA flag
The fingerprint EXCLUDES:
- Filler widths (absorbed variance)
- Filler positions
- Absolute x-coordinates (different wall lengths → same kitchen)
- Total wall length
Hash: SHA-256 (not MD5) for collision resistance.
===========================================================================
"""
import json
import hashlib
from typing import Dict, Any, List, Optional
class LayoutFingerprintEngine:
"""
Engine to generate a deterministic layout fingerprint that classifies
kitchens into types (K1, K2, ...) based on the invariant policy.
"""
@staticmethod
def generate_input_fingerprint(region_type: str, pre_dims: List[Dict[str, Any]], is_ada: bool) -> str:
"""
Hash the raw physical footprint before AI extraction.
Used to bypass OpenRouter for identically dimensioned units.
"""
# Sort dims by x, y so the hash is stable regardless of OCR reading order
sorted_dims = sorted(pre_dims, key=lambda d: (d.get('x', 0), d.get('y', 0)))
dim_texts = [d.get('text', '') for d in sorted_dims]
fingerprint_dict = {
"region_type": region_type,
"dims": dim_texts,
"ada": is_ada
}
sig_str = json.dumps(fingerprint_dict, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(sig_str.encode('utf-8')).hexdigest()
@staticmethod
def _infer_layout_topology(cabinets: List[Dict[str, Any]]) -> str:
"""
Infer if the layout is Straight, L-Shape, U-Shape, etc.
based on corner cabinets.
"""
corner_count = 0
for cab in cabinets:
cab_type = cab.get('cabinet_type', '').lower()
notes = cab.get('notes', '').lower()
if 'corner' in cab_type or 'blind' in cab_type or 'corner' in notes:
corner_count += 1
if corner_count == 0:
return "Straight"
elif corner_count == 1:
return "L-Shape"
elif corner_count >= 2:
return "U-Shape"
return "Complex"
@staticmethod
def _extract_canonical_cabinets(cabinets: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""
Extract the ORDERED sequence of catalog cabinet types and widths,
EXCLUDING fillers and appliance spaces.
This is the core of the invariant: if the catalog blocks are
identical in type and width, the fingerprint is the same —
regardless of filler width changes.
"""
canonical = []
for cab in cabinets:
cab_type = cab.get('cabinet_type', '').lower()
# SKIP fillers — they absorb variance, not identity
if cab_type == 'filler' or 'filler' in cab_type:
continue
# SKIP appliance spaces — not cabinet identity
if cab_type == 'appliance_space':
continue
# SKIP microwave shelves treated as appliance slots
# (include only if it's a real cabinet)
canonical.append({
"type": cab_type,
"width": round(cab.get('width_in', 0.0)),
"height": round(cab.get('height_in', 0.0)),
})
return canonical
@staticmethod
def _extract_canonical_appliances(cabinets: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Extract appliance sequence (type + width only, no position)."""
appliances = []
for cab in cabinets:
cab_type = cab.get('cabinet_type', '').lower()
notes = cab.get('notes', '').lower()
if cab_type == 'appliance_space' or 'ref' in notes or 'range' in notes or 'dw' in notes:
appliances.append({
"type": cab_type,
"width": round(cab.get('width_in', 0.0)),
})
return appliances
@staticmethod
def _extract_canonical_openings(cabinets: List[Dict[str, Any]]) -> List[str]:
"""
Extract opening types (window/door/column) from notes.
Only the TYPE matters for classification, not the absolute position.
"""
openings = []
for cab in cabinets:
notes = cab.get('notes', '').lower()
if 'window' in notes:
openings.append("window")
if 'door' in notes:
openings.append("door")
if 'column' in notes:
openings.append("column")
return openings
@staticmethod
def generate_fingerprint(unit_elevation: Dict[str, Any]) -> str:
"""
Generates the SHA-256 hash of the canonical fingerprint.
Two units with the same catalog cabinet sequence but different
filler widths will produce the SAME fingerprint.
Two units where a B36 changes to a B33 will produce DIFFERENT
fingerprints.
"""
cabinets = unit_elevation.get('cabinets', [])
is_ada = unit_elevation.get('is_ada', False)
# 1. Layout Topology (Straight / L / U)
layout = LayoutFingerprintEngine._infer_layout_topology(cabinets)
# 2. Canonical cabinet sequence (fillers excluded)
canonical_cabs = LayoutFingerprintEngine._extract_canonical_cabinets(cabinets)
# 3. Canonical appliance sequence
canonical_apps = LayoutFingerprintEngine._extract_canonical_appliances(cabinets)
# 4. Canonical openings (type only)
canonical_openings = LayoutFingerprintEngine._extract_canonical_openings(cabinets)
# Build the canonical dict — sorted keys for determinism
fingerprint_dict = {
"layout": layout,
"cabinets": canonical_cabs,
"appliances": canonical_apps,
"openings": canonical_openings,
"ada": is_ada,
}
# Hash with SHA-256
sig_str = json.dumps(fingerprint_dict, sort_keys=True, separators=(',', ':'))
return hashlib.sha256(sig_str.encode('utf-8')).hexdigest()
@staticmethod
def fingerprints_match(fp1: str, fp2: str) -> bool:
"""Check if two fingerprints classify as the same kitchen type."""
return fp1 == fp2
@staticmethod
def explain_difference(
unit_a: Dict[str, Any],
unit_b: Dict[str, Any],
) -> List[str]:
"""
Explain WHY two units have different fingerprints.
Returns a list of human-readable difference strings.
"""
diffs = []
cabs_a = LayoutFingerprintEngine._extract_canonical_cabinets(unit_a.get('cabinets', []))
cabs_b = LayoutFingerprintEngine._extract_canonical_cabinets(unit_b.get('cabinets', []))
if len(cabs_a) != len(cabs_b):
diffs.append(f"Cabinet count differs: {len(cabs_a)} vs {len(cabs_b)}")
else:
for i, (a, b) in enumerate(zip(cabs_a, cabs_b)):
if a['type'] != b['type']:
diffs.append(f"Cabinet {i+1} type differs: {a['type']} vs {b['type']}")
if a['width'] != b['width']:
diffs.append(f"Cabinet {i+1} width differs: {a['width']}\" vs {b['width']}\"")
topo_a = LayoutFingerprintEngine._infer_layout_topology(unit_a.get('cabinets', []))
topo_b = LayoutFingerprintEngine._infer_layout_topology(unit_b.get('cabinets', []))
if topo_a != topo_b:
diffs.append(f"Layout topology differs: {topo_a} vs {topo_b}")
if unit_a.get('is_ada', False) != unit_b.get('is_ada', False):
diffs.append(f"ADA flag differs")
if not diffs:
diffs.append("Fingerprints match — these are the SAME kitchen type (filler-only variance)")
return diffs
@@ -0,0 +1,62 @@
from typing import Dict, List, Any
from collections import defaultdict
class MaterialTakeoffEngine:
"""Generates a Bill of Materials (BOM) for fabrication."""
@staticmethod
def generate_takeoff(cabinets: List[Dict[str, Any]]) -> Dict[str, Any]:
"""Calculates material requirements based on the cabinet schedule."""
takeoff = {
"total_cabinets": len(cabinets),
"sheet_goods_34": 0.0, # 3/4" material (e.g. plywood) in sq ft
"sheet_goods_14": 0.0, # 1/4" material (e.g. backings) in sq ft
"linear_edgebanding": 0.0, # edgebanding in linear feet
"hardware": defaultdict(int)
}
for cab in cabinets:
w_in = cab.get('width', 0)
h_in = cab.get('height', 0)
d_in = cab.get('depth', 0)
# Simple heuristic calculations for a standard box
# 2 sides, 1 top, 1 bottom, 1 back
side_area = (h_in * d_in) / 144.0
top_bottom_area = (w_in * d_in) / 144.0
back_area = (w_in * h_in) / 144.0
takeoff["sheet_goods_34"] += (side_area * 2) + (top_bottom_area * 2)
takeoff["sheet_goods_14"] += back_area
# Hardware
doors = cab.get('doors', 0)
drawers = cab.get('drawers', 0)
if doors > 0:
takeoff["hardware"]["hinges"] += (doors * 2)
takeoff["hardware"]["pulls"] += doors
if drawers > 0:
takeoff["hardware"]["drawer_slides"] += drawers
takeoff["hardware"]["pulls"] += drawers
# Convert defaultdict back to dict for clean JSON serialization
takeoff["hardware"] = dict(takeoff["hardware"])
return takeoff
@staticmethod
def print_takeoff(takeoff: Dict[str, Any]) -> str:
"""Formats the BOM for printing."""
lines = []
lines.append("=== MATERIAL TAKEOFF (BOM) ===")
lines.append(f"Total Cabinets: {takeoff['total_cabinets']}")
lines.append(f"3/4\" Sheet Goods (sq ft): {takeoff['sheet_goods_34']:.2f}")
lines.append(f"1/4\" Sheet Goods (sq ft): {takeoff['sheet_goods_14']:.2f}")
lines.append("\nHardware Requirements:")
for hw, qty in takeoff['hardware'].items():
lines.append(f" - {hw.replace('_', ' ').title()}: {qty}")
return "\n".join(lines)
@@ -0,0 +1,137 @@
from typing import Dict, List
from dataclasses import dataclass
@dataclass
class CabinetPart:
"""Single part in a cabinet assembly."""
part_id: str # "A", "B", "C", etc.
description: str # "SIDE PANEL 2 TIMES PER KITCHEN"
width_mm: float
height_mm: float
width_in: float
height_in: float
quantity: int
material: str
finish: str
notes: str = ""
edge_banding: str = ""
hinge_spec: str = ""
class PartsListGenerator:
"""Generate parts lists for shop drawings."""
# Standard parts for 90CM base kitchen
KITCHEN_BASE_90CM_PARTS = [
CabinetPart(
part_id='A',
description='BASE 90 CM',
width_mm=900, height_mm=720, width_in=35.4, height_in=28.4,
quantity=1,
material='PLYWOOD',
finish='STRUCTURE WHITE PER KITCHEN',
edge_banding='1mm PVC WHITE'
),
CabinetPart(
part_id='B',
description='SIDE PANEL',
width_mm=600, height_mm=720, width_in=23.6, height_in=28.4,
quantity=2,
material='PLYWOOD',
finish='FIXED PANEL FINISH',
edge_banding='1mm PVC COLOR MATCH'
),
CabinetPart(
part_id='C',
description='BACK PANEL',
width_mm=900, height_mm=600, width_in=35.4, height_in=23.6,
quantity=1,
material='PLYWOOD',
finish='STRUCTURE WHITE PER KITCHEN'
),
# ... more standard parts
]
KITCHEN_ADA_SINK_PARTS = [
CabinetPart(
part_id='A',
description='KITCHEN ADA SINK',
width_mm=840, height_mm=720, width_in=33.1, height_in=28.4,
quantity=1,
material='PLYWOOD',
finish='FIXED PANEL FINISH'
),
CabinetPart(
part_id='B',
description='SIDE PANEL',
width_mm=600, height_mm=720, width_in=23.6, height_in=28.4,
quantity=2,
material='PLYWOOD',
finish='FIXED PANEL FINISH'
),
# ... more parts
]
@classmethod
def generate_parts_list(cls, cabinet_type: str, kitchen_type: str) -> Dict:
"""Generate parts list for a specific cabinet type."""
if cabinet_type == 'base_90cm':
parts = cls.KITCHEN_BASE_90CM_PARTS
elif cabinet_type == 'ada_sink':
parts = cls.KITCHEN_ADA_SINK_PARTS
else:
parts = []
parts_list = {
'cabinet_type': cabinet_type,
'kitchen_type': kitchen_type,
'parts': parts,
'total_parts': sum(p.quantity for p in parts),
'scale': '1/2" = 1\'-0"'
}
return parts_list
@classmethod
def generate_all_parts_sheets(cls, project_config) -> List[Dict]:
"""Generate complete parts list sheets for project."""
sheets = []
kitchen_sheet = cls._generate_kitchen_sheet(project_config)
sheets.append(kitchen_sheet)
vanity_sheet = cls._generate_vanity_sheet(project_config)
sheets.append(vanity_sheet)
return sheets
@staticmethod
def _generate_kitchen_sheet(project_config) -> Dict:
"""Create kitchen parts sheet."""
return {
'title': 'PARTS BY KITCHEN',
'scale': '1/2" = 1\'-0"',
'page_layout': [
{
'section': 'BASE 90 CM',
'parts': PartsListGenerator.KITCHEN_BASE_90CM_PARTS,
'position': [50, 500]
},
{
'section': 'ADA SINK',
'parts': PartsListGenerator.KITCHEN_ADA_SINK_PARTS,
'position': [50, 200]
}
]
}
@staticmethod
def _generate_vanity_sheet(project_config) -> Dict:
"""Create vanity parts sheet."""
return {
'title': 'PARTS BY VANITIES',
'scale': '1/2" = 1\'-0"',
'page_layout': [
{
'section': 'VANITIES ADA SINK',
'parts': [],
'position': [50, 300]
}
]
}
@@ -0,0 +1,435 @@
"""
===========================================================================
core/engines/placement_engine.py — Deterministic Cabinet Placement
===========================================================================
Phase 4: Given solved wall constraints (available runs + anchors),
deterministically places cabinets using Manufacturing Rules and Design
Rules. This is the core intellectual property of the system.
The engine CONSUMES rules — it does not own them.
Manufacturing Rules (physical constraints):
- Toe kick height: 4.5" standard, varies by manufacturer
- Filler width: 1.5" min, 6" max
- Standard catalog widths only (no arbitrary sizes)
- Corner cabinets require 3" filler pull
Design Rules (placement logic):
- Sink base is centered on the sink anchor
- Dishwasher is always adjacent to sink base
- Remaining space is filled with largest-first standard bases
- Fillers absorb fractional inches at wall ends
- ADA: max countertop height 34", knee clearance at sink
The engine produces CabinetItem objects (legacy-compatible) that the
downstream pipeline, fingerprint, BOM, and drawing generators consume.
===========================================================================
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Optional, Tuple
from core.engines.constraint_solver import (
WallConstraints, AvailableRun, Anchor, ApplianceSlot,
STANDARD_BASE_WIDTHS, STANDARD_SINK_BASE_WIDTHS, STANDARD_DW_WIDTHS,
MIN_FILLER_WIDTH, MAX_FILLER_WIDTH, MIN_CABINET_WIDTH,
)
from core.config import BASE_CABINET_HEIGHT_ADA_IN
# ══════════════════════════════════════════════════════════════════════════
# MANUFACTURING RULES
# ══════════════════════════════════════════════════════════════════════════
@dataclass
class ManufacturingRules:
"""Physical constraints from the cabinet manufacturer."""
toe_kick_height: float = 4.5 # inches
base_height: float = 34.5 # inches (standard counter height)
ada_base_height: float = field(default_factory=lambda: BASE_CABINET_HEIGHT_ADA_IN)
base_depth: float = 24.0 # inches
upper_height: float = 30.0 # inches (default wall cabinet)
max_upper_stack_height: float = 90.5 # inches (default top of wall cabinets)
upper_depth: float = 12.0 # inches
standard_base_widths: List[int] = field(default_factory=lambda: list(STANDARD_BASE_WIDTHS))
standard_sink_widths: List[int] = field(default_factory=lambda: list(STANDARD_SINK_BASE_WIDTHS))
min_filler: float = MIN_FILLER_WIDTH
max_filler: float = MAX_FILLER_WIDTH
corner_filler_pull: float = 3.0 # inches
# ══════════════════════════════════════════════════════════════════════════
# DESIGN RULES
# ══════════════════════════════════════════════════════════════════════════
@dataclass
class DesignRules:
"""Placement logic rules."""
center_sink_on_anchor: bool = True
dw_adjacent_to_sink: bool = True
dw_side: str = "left" # "left" or "right" of sink
fill_largest_first: bool = True
filler_at_wall_ends: bool = True
ada_knee_clearance_at_sink: bool = True # ADA: open knee space under sink
# ══════════════════════════════════════════════════════════════════════════
# PLACED CABINET
# ══════════════════════════════════════════════════════════════════════════
@dataclass
class PlacedCabinet:
"""A cabinet placed at a specific position on a wall."""
cabinet_type: str # "base", "sink_base", "dw_adjacent", "filler"
width: int # inches (catalog standard)
x_start: float # inches from wall origin
height: float = 0.0 # inches (0.0 means default)
is_filler: bool = False
filler_width: float = 0.0 # actual filler width if is_filler
notes: str = ""
@property
def x_end(self) -> float:
if self.is_filler:
return self.x_start + self.filler_width
return self.x_start + self.width
@property
def code(self) -> str:
if self.is_filler:
return f"F{self.filler_width:.1f}".rstrip('0').rstrip('.')
prefix_map = {
"base": "B",
"sink_base": "SB",
"dw_adjacent": "DW",
"upper_wall": "W",
"microwave_shelf": "MW",
"appliance_space": "APP",
"pantry": "P",
"linen": "L",
"corner_upper": "CW"
}
return f"{prefix_map.get(self.cabinet_type, 'B')}{self.width}"
# ══════════════════════════════════════════════════════════════════════════
# PLACEMENT ENGINE
# ══════════════════════════════════════════════════════════════════════════
class PlacementEngine:
"""
Deterministically fills available wall runs with cabinets.
Algorithm for a run with a centered sink anchor:
1. Place sink base centered on the anchor.
2. Place dishwasher (24") adjacent to sink base (per design rules).
3. Fill remaining space on each side with largest-first standard bases.
4. Absorb any fractional remainder as filler at the wall ends.
Algorithm for a run with no anchor:
1. Fill with largest-first standard bases from left to right.
2. Absorb remainder as filler at the right wall end.
"""
def __init__(
self,
mfg_rules: Optional[ManufacturingRules] = None,
design_rules: Optional[DesignRules] = None,
):
self.mfg = mfg_rules or ManufacturingRules()
self.design = design_rules or DesignRules()
def place_wall(self, wc: WallConstraints) -> List[PlacedCabinet]:
"""Place cabinets on all available runs of a wall, plus appliance slots."""
all_placed: List[PlacedCabinet] = []
is_vanity = "vanity" in wc.wall_name.lower() or "bath" in wc.wall_name.lower()
for run in wc.available_runs:
placed = self._place_run(run, wc.is_ada, is_vanity)
all_placed.extend(placed)
# Place appliance slots as appliance spaces so they appear in BOM/Drawings
for slot in wc.appliance_slots:
all_placed.append(PlacedCabinet(
cabinet_type="appliance_space",
width=int(slot.width),
x_start=slot.x_start,
notes=slot.notes or slot.type
))
# Sort left-to-right
all_placed.sort(key=lambda c: c.x_start)
# Mirror bases to create upper cabinets
uppers = []
# Calculate heights based on vertical constraints
std_upper_aff = 54.0
if wc.is_ada:
std_upper_aff = 48.0
max_allowable_upper_h = min(self.mfg.upper_height, max(0.0, self.mfg.max_upper_stack_height - std_upper_aff))
over_fridge_h = max(0.0, self.mfg.max_upper_stack_height - 72.0)
for cab in all_placed:
# Check if this space intersects any window
has_window = any(
(cab.x_start < win.x_end) and ((cab.x_start + cab.width) > win.x_start)
for win in wc.windows
)
if cab.cabinet_type == "appliance_space":
if "REF" in cab.notes:
uppers.append(PlacedCabinet(
cabinet_type="upper_wall", width=cab.width, x_start=cab.x_start, height=over_fridge_h, notes="Over fridge (deep)"
))
elif "RANGE" in cab.notes:
uppers.append(PlacedCabinet(
cabinet_type="microwave_shelf", width=cab.width, x_start=cab.x_start, height=max_allowable_upper_h, notes="Over range"
))
elif "DW" in cab.notes and not has_window:
uppers.append(PlacedCabinet(
cabinet_type="upper_wall", width=cab.width, x_start=cab.x_start, height=max_allowable_upper_h
))
elif cab.cabinet_type == "sink_base":
if not has_window:
uppers.append(PlacedCabinet(
cabinet_type="upper_wall", width=cab.width, x_start=cab.x_start, height=max_allowable_upper_h, notes="Over sink"
))
elif cab.cabinet_type in ("base", "filler"):
if not has_window:
uppers.append(PlacedCabinet(
cabinet_type=cab.cabinet_type if cab.is_filler else "upper_wall",
width=cab.width,
x_start=cab.x_start,
height=max_allowable_upper_h,
is_filler=cab.is_filler,
filler_width=cab.filler_width
))
all_placed.extend(uppers)
return all_placed
def _place_run(self, run: AvailableRun, is_ada: bool = False, is_vanity: bool = False) -> List[PlacedCabinet]:
"""Place cabinets in one contiguous available run."""
if run.length < MIN_CABINET_WIDTH:
# Too short for any cabinet — filler only
if run.length >= MIN_FILLER_WIDTH:
return [PlacedCabinet(
cabinet_type="filler", width=0, x_start=run.x_start,
is_filler=True, filler_width=run.length,
notes="Dead space filler"
)]
return []
# Check for a sink anchor in this run
sink_anchors = [a for a in run.anchors if "sink" in a.type.lower()]
if is_vanity and sink_anchors:
return self._place_vanity_run(run, len(sink_anchors), is_ada)
elif sink_anchors and self.design.center_sink_on_anchor:
return self._place_with_centered_sink(run, sink_anchors[0], is_ada)
else:
return self._place_fill_run(run.x_start, run.x_end)
def _place_vanity_run(
self,
run: AvailableRun,
num_sinks: int = 1,
is_ada: bool = False,
) -> List[PlacedCabinet]:
"""
Specialized logic for vanity runs.
Symmetric filler/base placement and optional center gap for double sinks.
"""
result: List[PlacedCabinet] = []
if num_sinks >= 2:
sb_width = 24
center_gap = 3.0
total_cab_width = 2 * sb_width + center_gap
if total_cab_width <= run.length:
padding = (run.length - total_cab_width) / 2.0
cursor = run.x_start
result.extend(self._place_fill_run(cursor, cursor + padding))
cursor += padding
result.append(PlacedCabinet(cabinet_type="sink_base", width=sb_width, x_start=cursor, notes="Vanity Sink (Left)"))
cursor += sb_width
result.append(PlacedCabinet(cabinet_type="base", width=0, x_start=cursor, is_filler=True, filler_width=center_gap, notes="Vanity Center Spacer"))
cursor += center_gap
result.append(PlacedCabinet(cabinet_type="sink_base", width=sb_width, x_start=cursor, notes="Vanity Sink (Right)"))
cursor += sb_width
result.extend(self._place_fill_run(cursor, run.x_end))
return result
# Single sink fallback
sb_width = 30 if run.length >= 36 else 24
if sb_width > run.length:
sb_width = int(run.length)
padding = (run.length - sb_width) / 2.0
cursor = run.x_start
result.extend(self._place_fill_run(cursor, cursor + padding))
cursor += padding
result.append(PlacedCabinet(cabinet_type="sink_base", width=sb_width, x_start=cursor, notes="Vanity Sink"))
cursor += sb_width
result.extend(self._place_fill_run(cursor, run.x_end))
return result
def _place_with_centered_sink(
self,
run: AvailableRun,
anchor: Anchor,
is_ada: bool = False,
) -> List[PlacedCabinet]:
"""
Place cabinets with a centered sink base.
"""
result: List[PlacedCabinet] = []
# Pick sink base width — use anchor width if it matches a standard, else 36"
sb_width = 36
for sw in sorted(self.mfg.standard_sink_widths, reverse=True):
if sw <= anchor.width or sw == 36:
sb_width = sw
break
# Center the sink base on the anchor
sb_center = anchor.x_center
sb_x_start = sb_center - sb_width / 2.0
# Clamp to run boundaries
if sb_x_start < run.x_start:
sb_x_start = run.x_start
if sb_x_start + sb_width > run.x_end:
sb_x_start = run.x_end - sb_width
sb_x_end = sb_x_start + sb_width
# Place sink base
result.append(PlacedCabinet(
cabinet_type="sink_base", width=sb_width,
x_start=sb_x_start, notes="Centered on sink"
))
# Fill left of sink base
left_cabs = self._place_fill_run(run.x_start, sb_x_start)
result.extend(left_cabs)
# Fill right of sink base
right_cabs = self._place_fill_run(sb_x_end, run.x_end)
result.extend(right_cabs)
# Sort by x position
result.sort(key=lambda c: c.x_start)
return result
def _place_fill_run(
self,
x_start: float,
x_end: float,
) -> List[PlacedCabinet]:
"""
Fill a contiguous segment with standard base cabinets.
Finds the maximum possible cabinet width that is a multiple of 3
leaving at least MIN_FILLER_WIDTH.
"""
result: List[PlacedCabinet] = []
total = x_end - x_start
if total < MIN_FILLER_WIDTH:
return result
if total < MIN_CABINET_WIDTH:
result.append(PlacedCabinet(
cabinet_type="filler", width=0, x_start=x_start,
is_filler=True, filler_width=total, notes="Small gap"
))
return result
# We need a combination of standard widths (which are multiples of 3).
# We want the max integer 'cab_total' (multiple of 3) such that:
# 1. cab_total <= total
# 2. (total - cab_total) == 0 OR (total - cab_total) >= MIN_FILLER_WIDTH
best_cab_total = 0
best_filler = total
# Start from max possible integer and go down
max_int = int(total)
for cand in range(max_int, -1, -1):
if cand % 3 != 0:
continue
rem = total - cand
if rem == 0 or rem >= MIN_FILLER_WIDTH:
best_cab_total = cand
best_filler = rem
break
cursor = x_start
# Place cabinets using exact fill
if best_cab_total >= MIN_CABINET_WIDTH:
exact = self._find_exact_fill(best_cab_total)
if exact:
for w in exact:
result.append(PlacedCabinet(
cabinet_type="base", width=w, x_start=cursor
))
cursor += w
# Place remaining as filler (typically at the end of the run)
if best_filler > 0:
result.append(PlacedCabinet(
cabinet_type="filler", width=0, x_start=cursor,
is_filler=True, filler_width=best_filler
))
return result
def _find_exact_fill(self, total: int) -> Optional[List[int]]:
"""
Find a combination of standard base widths that sums exactly to `total`.
Prefers: (1) fewest cabinets, then (2) lowest max-width (most balanced).
Returns sorted list of widths, or None if no exact combination exists.
"""
widths = sorted(self.mfg.standard_base_widths, reverse=True)
# DP: best[s] = (cabinet_count, max_width, list_of_widths) or None
best: dict[int, Optional[tuple]] = {0: (0, 0, [])}
for s in range(1, total + 1):
best[s] = None
for w in widths:
if w <= s and best.get(s - w) is not None:
prev_count, prev_max, prev_list = best[s - w]
new_count = prev_count + 1
new_max = max(prev_max, w)
if best[s] is None:
best[s] = (new_count, new_max, prev_list + [w])
else:
cur_count, cur_max, _ = best[s]
# Prefer fewer cabinets, then lower max-width
if (new_count < cur_count) or (new_count == cur_count and new_max < cur_max):
best[s] = (new_count, new_max, prev_list + [w])
entry = best.get(total)
if entry is None:
return None
return sorted(entry[2])
def placed_to_codes(self, placed: List[PlacedCabinet]) -> List[str]:
"""Convert placed cabinets to a list of cabinet code strings."""
# Sort by position, then return codes
placed_sorted = sorted(placed, key=lambda c: c.x_start)
return [c.code for c in placed_sorted]
@@ -0,0 +1,53 @@
from typing import Dict, List, Any
import math
class RevisionEngine:
"""Handles revision tracking and dynamic revision cloud generation."""
@staticmethod
def draw_revision_cloud(x: float, y: float, w: float, h: float, arc_radius: float = 2.0, scale: float = 1.0) -> Dict[str, List]:
"""Draws a scalloped revision cloud around a bounding box."""
geom = {"lines": [], "blocks": [], "texts": []}
r = arc_radius * scale
x_min, x_max = x, x + (w * scale)
y_min, y_max = y, y + (h * scale)
# In a true CAD system, we'd draw arcs.
# For our abstract geometry model, we represent it as a specialized block or segmented arcs.
# Here we emit a custom block type 'rev_cloud' which the sheet composer can render appropriately.
geom["blocks"].append({
"type": "rev_cloud",
"coords": [x_min, y_min, w * scale, h * scale],
"arc_radius": r,
"layer": "REVISIONS",
"style": "cloud"
})
# Add a revision delta triangle
geom["blocks"].append({
"type": "polygon",
"points": [
[x_max, y_max],
[x_max + (3*scale), y_max + (5*scale)],
[x_max - (3*scale), y_max + (5*scale)]
],
"layer": "REVISIONS",
"style": "solid"
})
return geom
@staticmethod
def generate_revision_log(revisions: List[Dict[str, str]]) -> Dict[str, Any]:
"""Compiles a revision history for the title block."""
issues = []
for rev in revisions:
issues.append({
"rev_id": rev.get("id", ""),
"date": rev.get("date", ""),
"description": rev.get("description", ""),
"author": rev.get("author", "AUTO")
})
return {"revisions": issues}
@@ -0,0 +1,365 @@
from typing import Dict, List, Any
class SectionGenerator:
"""Generate detailed CAD sections with fabrication specs."""
SECTION_TYPES = {
'kitchen_standard': {
'title': 'KITCHEN SECTION',
'height': 228.0,
'callouts': [
'PLYWOOD BACKING 6" H',
'STANDARD CABINET',
]
},
'kitchen_ada': {
'title': 'KITCHEN ADA',
'height': 228.0, # 7'-6" typical
'callouts': [
'PLYWOOD BACKING 6" H',
'ACCESSIBLE CABINET',
'ADA SINK - MAX 34" HEIGHT TO COUNTERTOP',
]
},
'kitchen_drawer': {
'title': 'KITCHEN DRAWER',
'notes': 'Show internal drawer construction'
},
'kitchen_refrigerator': {
'title': 'REFRIGERATOR SECTION',
'callouts': [
'REFRIGERATOR GTE18GSNRSS',
'PLYWOOD BACKING 6" H',
'CLEARANCE FOR DOOR SWING'
]
},
'kitchen_microwave': {
'title': 'MICROWAVE SECTION',
'callouts': [
'24" MICROWAVE JVM3160RFSS',
'MOUNTING BRACKETS',
'CLEARANCE BELOW: MIN 15"'
]
},
'kitchen_hood': {
'title': 'KITCHEN HOOD',
'callouts': [
'RANGE HOOD (ADA: JVX3300SJSS)',
'MIN 24" ABOVE RANGE',
'DUCTWORK BY OTHERS'
]
},
'kitchen_pantry': {
'title': 'PANTRY SECTION',
'height': 228.0, # Full 7'-6" height
'callouts': [
'FULL HEIGHT PANTRY',
'SHELVING EVERY 12"',
'PLYWOOD BACKING FULL HEIGHT'
]
},
'vanity_standard': {
'title': 'VANITY SECTION',
'callouts': [
'STANDARD VANITY CABINET',
'MOUNTED AT STANDARD HEIGHT'
]
},
'vanity_ada': {
'title': 'VANITY ADA',
'callouts': [
'FULL ACCESSIBLE LAVATORY W/COVERED PANEL',
'KNEE CLEARANCE: MIN 27" W x 19" D @ 32" H',
'ACCESSIBILITY REQUIREMENTS MET',
'MOUNTED PER ADA GUIDELINES'
]
},
'vanity_pantry': {
'title': 'VANITY PANTRY',
'height': 228.0,
'callouts': [
'FULL HEIGHT LINEN STORAGE',
'ADJUSTABLE SHELVES',
'PLYWOOD BACKING 6" H'
]
}
}
@classmethod
def generate_section(cls, section_type: str, **kwargs) -> Dict[str, Any]:
"""Generate detailed section drawing.
Args:
section_type: One of SECTION_TYPES keys
**kwargs: Additional parameters (width, height, etc.)
Returns:
Dictionary with section geometry and callouts
"""
if section_type not in cls.SECTION_TYPES:
raise ValueError(f"Unknown section type: {section_type}")
spec = cls.SECTION_TYPES[section_type]
section = {
'type': section_type,
'title': spec['title'],
'geometry': {
'lines': [],
'blocks': [],
'circles': [],
'texts': [],
'dimensions': []
},
'callouts': spec.get('callouts', []),
'notes': spec.get('notes', '')
}
# Generate base outline based on section type
if 'pantry' in section_type:
cls._draw_pantry_outline(section, kwargs.get('width', 24.0),
kwargs.get('height', spec.get('height', 84.0)))
else:
default_width = 21.0 if 'vanity' in section_type else 24.0
cls._draw_base_outline(section, kwargs.get('width', default_width),
kwargs.get('height', spec.get('height', 84.0)),
is_vanity='vanity' in section_type)
# Add specific details based on type
if section_type == 'kitchen_ada':
cls._add_kitchen_ada_details(section, **kwargs)
elif section_type == 'kitchen_drawer':
cls._add_drawer_details(section, **kwargs)
elif section_type == 'vanity_ada':
cls._add_vanity_ada_details(section, **kwargs)
# ... more section types
# Add dimensions
cls._add_dimensions(section, **kwargs)
return section
@staticmethod
def _draw_pantry_outline(section: Dict, width: float, height: float, **kwargs):
"""Draw full height pantry profile."""
geom = section['geometry']
# FLOOR LINE
geom['lines'].append({'start': [0, 0], 'end': [width, 0], 'layer': 'FLOOR'})
# TOE KICK (3" inset, 4" high)
toe_kick_y = 4.0
toe_kick_inset = 3.0
geom['blocks'].append({
'type': 'rect',
'coords': [toe_kick_inset, 0, width - toe_kick_inset, toe_kick_y],
'hatch': 'DIAGONAL',
'layer': 'STRUCTURE'
})
# PANTRY CABINET (default 84" or 90" height)
geom['blocks'].append({
'type': 'rect',
'coords': [0, toe_kick_y, width, height],
'fill': False,
'layer': 'CABINET'
})
# PLYWOOD BACKING (full height)
geom['blocks'].append({
'type': 'rect',
'coords': [0, toe_kick_y, width, height],
'hatch': 'BRICKS',
'layer': 'BACKING'
})
@staticmethod
def _draw_base_outline(section: Dict, width: float, height: float, **kwargs):
"""Draw full cabinet profile."""
geom = section['geometry']
# Determine ADA flag for height
is_ada = kwargs.get('ada', False)
is_vanity = kwargs.get('is_vanity', False)
# FLOOR LINE
geom['lines'].append({'start': [0, 0], 'end': [width, 0], 'layer': 'FLOOR'})
# TOE KICK (3" inset, 4" high)
toe_kick_y = 4.0
toe_kick_inset = 3.0
geom['blocks'].append({
'type': 'rect',
'coords': [toe_kick_inset, 0, width - toe_kick_inset, toe_kick_y],
'hatch': 'DIAGONAL',
'layer': 'STRUCTURE'
})
# BASE CABINET (24" depth standard, 21" for vanities)
# Height of base cab above floor: 28.4" standard kitchen, 32.4" ADA, 32" standard vanity.
if is_vanity:
base_top = 32.4 if is_ada else 32.0
else:
base_top = 32.4 if is_ada else 28.4
geom['blocks'].append({
'type': 'rect',
'coords': [0, toe_kick_y, width, base_top],
'fill': False,
'layer': 'CABINET'
})
# PLYWOOD BACKING (6" height)
plywood_height = 6.0
geom['blocks'].append({
'type': 'rect',
'coords': [0, toe_kick_y, width, toe_kick_y + plywood_height],
'hatch': 'BRICKS',
'layer': 'BACKING'
})
# COUNTERTOP (1.6" thick, 1" overhang on front)
counter_y = base_top
counter_thickness = 1.6
counter_overhang = 1.0
geom['blocks'].append({
'type': 'rect',
'coords': [-counter_overhang, counter_y, width + counter_overhang, counter_y + counter_thickness],
'fill': False,
'layer': 'COUNTERTOP'
})
# UPPER CABINET (only for kitchens)
if not is_vanity:
upper_y = counter_y + counter_thickness + 16.0
upper_height = 30.0
upper_depth = 12.0
geom['blocks'].append({
'type': 'rect',
'coords': [width - upper_depth, upper_y, width, upper_y + upper_height],
'fill': False,
'layer': 'CABINET'
})
@staticmethod
def _add_kitchen_ada_details(section: Dict, **kwargs):
"""Add ADA-specific kitchen section details."""
geom = section['geometry']
# Accessible cabinet marker
geom['texts'].append({
'pos': [kwargs.get('width', 24.0) / 2, 15.0],
'text': 'ACCESSIBLE CABINET',
'size': 4.0,
'layer': 'CALLOUTS',
'bold': True
})
# Sink clearance zone (typical 27" W x 19" D)
# Note: In section view, we are looking at the side profile.
# Knee clearance is 19" depth from front of cabinet.
# Height is typically 27" min.
width = kwargs.get('width', 24.0)
knee_height = 27.0
knee_depth = 19.0
geom['blocks'].append({
'type': 'rect',
'coords': [-1.0, 0, knee_depth - 1.0, knee_height],
'id': 'SINK_CLEAR',
'layer': 'ACCESSIBILITY',
'fill': False,
'linestyle': 'dashed'
})
@staticmethod
def _add_drawer_details(section: Dict, **kwargs):
pass
@staticmethod
def _add_vanity_ada_details(section: Dict, **kwargs):
"""Add ADA vanity section details."""
geom = section['geometry']
# Covered panel specification
geom['blocks'].append({
'type': 'rect',
'coords': [0, 0, kwargs.get('width', 61.0), 32.0],
'id': 'COVERED_PANEL',
'layer': 'CONSTRUCTION',
'fill': False
})
# Knee clearance callout
geom['texts'].append({
'pos': [kwargs.get('width', 61.0) / 2, 16.0],
'text': 'FULL ACCESSIBLE LAVATORY\nW/COVERED PANEL',
'size': 3.5,
'layer': 'CALLOUTS',
'align': 'center'
})
@staticmethod
def _add_dimensions(section: Dict, **kwargs):
"""Add 15-20 dimension lines capturing all critical measurements."""
geom = section['geometry']
is_ada = kwargs.get('ada', False)
width = kwargs.get('width', 24.0)
base_top = 32.4 if is_ada else 28.4
toe_kick_y = 4.0
counter_y = base_top
upper_y = counter_y + 1.6 + 16.0
dims = []
# LEFT SIDE VERTICAL DIMENSIONS
if 'pantry' in section.get('type', ''):
dims.extend([
# Floor to toe kick top
{'start': [-30, 0], 'end': [-30, toe_kick_y], 'text': str(toe_kick_y), 'label': 'TOE KICK', 'position': 'left'},
# Toe kick to top of pantry
{'start': [-30, toe_kick_y], 'end': [-30, kwargs.get('height', 84.0)], 'text': str(round(kwargs.get('height', 84.0) - toe_kick_y, 1)), 'label': 'PANTRY CAB HEIGHT', 'position': 'left'},
# Total height
{'start': [-45, 0], 'end': [-45, kwargs.get('height', 84.0)], 'text': str(kwargs.get('height', 84.0)), 'label': 'TOTAL HEIGHT', 'position': 'left'},
])
else:
dims.extend([
# Floor to toe kick top
{'start': [-30, 0], 'end': [-30, toe_kick_y], 'text': str(toe_kick_y), 'label': 'TOE KICK', 'position': 'left'},
# Toe kick to counter top
{'start': [-30, toe_kick_y], 'end': [-30, counter_y], 'text': str(round(base_top - toe_kick_y, 1)), 'label': 'BASE CAB HEIGHT', 'position': 'left'},
# Counter thickness
{'start': [-30, counter_y], 'end': [-30, counter_y + 1.6], 'text': "1.6", 'label': 'COUNTERTOP', 'position': 'left'},
# Clearance from counter to upper
{'start': [-30, counter_y + 1.6], 'end': [-30, upper_y], 'text': "16.0", 'label': 'CLEARANCE', 'position': 'left'},
# Upper cabinet height
{'start': [-30, upper_y], 'end': [-30, upper_y + 30.0], 'text': "30.0", 'label': 'UPPER CAB HEIGHT', 'position': 'left'},
# Total height (example 84")
{'start': [-45, 0], 'end': [-45, kwargs.get('height', 84.0)], 'text': str(kwargs.get('height', 84.0)), 'label': 'TOTAL HEIGHT', 'position': 'left'},
])
# BOTTOM HORIZONTAL DIMENSIONS
dims.extend([
# Width
{'start': [0, -15], 'end': [width, -15], 'text': str(width), 'label': 'BASE DEPTH', 'position': 'below'},
# Toe kick inset (left front)
{'start': [0, -5], 'end': [3, -5], 'text': "3.0", 'label': 'INSET', 'position': 'below'}
])
# UPPER DEPTH
dims.extend([
# Upper cabinet depth
{'start': [width - 12, upper_y + 35], 'end': [width, upper_y + 35], 'text': "12.0", 'label': 'UPPER DEPTH', 'position': 'above'},
])
# APPLIANCE-SPECIFIC DIMENSIONS
if 'refrigerator' in section.get('type', '').lower():
dims.append({'start': [0, counter_y + 1.6], 'end': [28, counter_y + 1.6], 'text': "28.0", 'label': 'FRIDGE WIDTH', 'position': 'above'})
if 'sink' in section.get('type', '').lower() or 'vanity' in section.get('type', '').lower() or is_ada:
if is_ada:
# Knee clearance dimensions (side profile)
dims.extend([
{'start': [-1, toe_kick_y + 15], 'end': [18, toe_kick_y + 15], 'text': "19.0", 'label': 'KNEE DEPTH', 'position': 'above'},
])
geom['dimensions'].extend(dims)
@@ -0,0 +1,65 @@
from typing import Dict, List, Any
class SheetComposer:
"""Orchestrates the layout of multiple viewports onto a single PDF/DXF sheet."""
@staticmethod
def compose_sheet(sheet_id: str, viewports: List[Dict[str, Any]], title_block: Dict[str, Any]) -> Dict[str, List]:
"""Combines multiple viewports and the title block into a final single geometry dict."""
sheet_geom = {"lines": [], "blocks": [], "texts": []}
# Add title block
if title_block:
sheet_geom["lines"].extend(title_block.get("lines", []))
sheet_geom["blocks"].extend(title_block.get("blocks", []))
sheet_geom["texts"].extend(title_block.get("texts", []))
# Add each viewport
for vp in viewports:
geom = vp.get("geometry", {})
sheet_geom["lines"].extend(geom.get("lines", []))
sheet_geom["blocks"].extend(geom.get("blocks", []))
sheet_geom["texts"].extend(geom.get("texts", []))
return sheet_geom
@staticmethod
def place_floor_plan(floor_plan_geom: Dict[str, List], x_offset: float, y_offset: float, scale: float = 1.0) -> Dict[str, Any]:
"""Places the floor plan onto a specific coordinate on the sheet."""
# Typically requires scaling engine here, but for now just pass through
return {"id": "FLOOR_PLAN", "geometry": floor_plan_geom, "x": x_offset, "y": y_offset, "scale": scale}
@staticmethod
def place_elevation_A(elevation_geom: Dict[str, List], x_offset: float, y_offset: float, scale: float = 1.0) -> Dict[str, Any]:
"""Places Elevation A onto the sheet."""
return {"id": "ELEV_A", "geometry": elevation_geom, "x": x_offset, "y": y_offset, "scale": scale}
@staticmethod
def place_section_A(section_geom: Dict[str, List], x_offset: float, y_offset: float, scale: float = 1.0) -> Dict[str, Any]:
"""Places Section A onto the sheet."""
return {"id": "SECT_A", "geometry": section_geom, "x": x_offset, "y": y_offset, "scale": scale}
@staticmethod
def place_section_view(section_geom: Dict[str, List], x_offset: float, y_offset: float, scale: float = 1.0) -> Dict[str, Any]:
"""Places a generalized Section View."""
return {"id": "SECT_VIEW", "geometry": section_geom, "x": x_offset, "y": y_offset, "scale": scale}
@staticmethod
def place_general_notes(notes_geom: Dict[str, List], x_offset: float, y_offset: float, scale: float = 1.0) -> Dict[str, Any]:
"""Places general architectural notes onto the sheet."""
return {"id": "GENERAL_NOTES", "geometry": notes_geom, "x": x_offset, "y": y_offset, "scale": scale}
@staticmethod
def place_matrix_table(matrix_geom: Dict[str, List], x_offset: float, y_offset: float, scale: float = 1.0) -> Dict[str, Any]:
"""Places the project unit matrix table."""
return {"id": "MATRIX_TABLE", "geometry": matrix_geom, "x": x_offset, "y": y_offset, "scale": scale}
@staticmethod
def place_revision_clouds(clouds_geom: Dict[str, List], x_offset: float, y_offset: float, scale: float = 1.0) -> Dict[str, Any]:
"""Places revision clouds marking recent changes."""
return {"id": "REVISION_CLOUDS", "geometry": clouds_geom, "x": x_offset, "y": y_offset, "scale": scale}
@staticmethod
def place_title_block(title_block_geom: Dict[str, List]) -> Dict[str, Any]:
"""Positions the title block geometry (usually absolute coordinates)."""
return {"id": "TITLE_BLOCK", "geometry": title_block_geom, "x": 0.0, "y": 0.0, "scale": 1.0}
@@ -0,0 +1,112 @@
from typing import Dict, List, Any
import datetime
class TitleBlockEngine:
"""Generates standardized architectural title blocks."""
@staticmethod
def draw_vertical_strip(sheet_w: float, sheet_h: float, strip_width: float = 3.0) -> Dict[str, List]:
"""Draws the right-side vertical title strip boundary."""
geom = {"lines": [], "blocks": [], "texts": []}
x_start = sheet_w - strip_width
geom["lines"].append({"start": [x_start, 0], "end": [x_start, sheet_h], "layer": "TITLEBLOCK", "style": "solid"})
# Outer border
geom["blocks"].append({"type": "rect", "coords": [0, 0, sheet_w, sheet_h], "layer": "TITLEBLOCK", "style": "solid"})
return geom
@staticmethod
def add_project_metadata(x: float, y: float, project_name: str, client_name: str) -> Dict[str, List]:
"""Adds project text to the title block."""
geom = {"lines": [], "blocks": [], "texts": []}
geom["texts"].append({"pos": [x, y], "text": project_name, "size": 6.0, "layer": "TITLEBLOCK"})
geom["texts"].append({"pos": [x, y - 1.5], "text": client_name, "size": 4.0, "layer": "TITLEBLOCK"})
return geom
@staticmethod
def add_sheet_info(x: float, y: float, sheet_number: str, sheet_title: str, scale: str) -> Dict[str, List]:
"""Adds specific sheet data."""
geom = {"lines": [], "blocks": [], "texts": []}
geom["texts"].append({"pos": [x, y], "text": f"SHEET: {sheet_number}", "size": 8.0, "layer": "TITLEBLOCK"})
geom["texts"].append({"pos": [x, y - 2.0], "text": sheet_title, "size": 5.0, "layer": "TITLEBLOCK"})
geom["texts"].append({"pos": [x, y - 4.0], "text": f"SCALE: {scale}", "size": 4.0, "layer": "TITLEBLOCK"})
geom["texts"].append({"pos": [x, y - 6.0], "text": f"DATE: {datetime.date.today().isoformat()}", "size": 4.0, "layer": "TITLEBLOCK"})
return geom
@staticmethod
def add_revision_log(x: float, y: float, revisions: List[Dict[str, str]]) -> Dict[str, List]:
"""Adds a revision table."""
geom = {"lines": [], "blocks": [], "texts": []}
geom["texts"].append({"pos": [x, y], "text": "REVISIONS", "size": 4.5, "layer": "TITLEBLOCK"})
current_y = y - 1.5
for rev in revisions:
text = f"{rev.get('date', '')} - {rev.get('desc', '')}"
geom["texts"].append({"pos": [x, current_y], "text": text, "size": 3.0, "layer": "TITLEBLOCK"})
current_y -= 1.5
return geom
@staticmethod
def draw_issue_history(x: float, y: float, issues: List[Dict[str, str]]) -> Dict[str, List]:
"""Draws the formal issue/submittal history block."""
geom = {"lines": [], "blocks": [], "texts": []}
geom["texts"].append({"pos": [x, y], "text": "ISSUE HISTORY", "size": 4.5, "layer": "TITLEBLOCK"})
current_y = y - 1.5
for issue in issues:
text = f"ISSUED FOR {issue.get('purpose', 'REVIEW')} - {issue.get('date', '')}"
geom["texts"].append({"pos": [x, current_y], "text": text, "size": 3.0, "layer": "TITLEBLOCK"})
current_y -= 1.5
return geom
@staticmethod
def draw_consultant_block(x: float, y: float, consultants: List[str]) -> Dict[str, List]:
"""Draws the consultant and engineering stamp block."""
geom = {"lines": [], "blocks": [], "texts": []}
geom["texts"].append({"pos": [x, y], "text": "CONSULTANTS", "size": 4.5, "layer": "TITLEBLOCK"})
current_y = y - 1.5
for cons in consultants:
geom["texts"].append({"pos": [x, current_y], "text": cons, "size": 3.0, "layer": "TITLEBLOCK"})
current_y -= 1.5
return geom
@staticmethod
def draw_sheet_index(x: float, y: float, sheets: List[Dict[str, str]]) -> Dict[str, List]:
"""Draws the architectural sheet index."""
geom = {"lines": [], "blocks": [], "texts": []}
geom["texts"].append({"pos": [x, y], "text": "SHEET INDEX", "size": 5.0, "layer": "TITLEBLOCK"})
current_y = y - 2.0
for sheet in sheets:
text = f"{sheet.get('num', '')} - {sheet.get('title', '')}"
geom["texts"].append({"pos": [x, current_y], "text": text, "size": 3.5, "layer": "TITLEBLOCK"})
current_y -= 2.0
return geom
@staticmethod
def build_standard_title_block(sheet_size: str, project_name: str, sheet_num: str, sheet_title: str, scale: str) -> Dict[str, List]:
"""Composes a complete standard title block."""
sheet_w, sheet_h = (17.0, 11.0) if sheet_size == '11x17' else (36.0, 24.0)
strip_w = 3.0
geom = {"lines": [], "blocks": [], "texts": []}
# Merge strip
strip = TitleBlockEngine.draw_vertical_strip(sheet_w, sheet_h, strip_w)
geom["lines"].extend(strip["lines"])
geom["blocks"].extend(strip["blocks"])
# Center of strip
cx = sheet_w - (strip_w / 2.0)
# Top: Project Info
proj = TitleBlockEngine.add_project_metadata(cx, sheet_h - 2.0, project_name, "Client XYZ")
geom["texts"].extend(proj["texts"])
# Middle: Revisions
revs = TitleBlockEngine.add_revision_log(cx, sheet_h - 6.0, [{"date": "2024-01-01", "desc": "Initial Issue"}])
geom["texts"].extend(revs["texts"])
# Bottom: Sheet Info
info = TitleBlockEngine.add_sheet_info(cx, 8.0, sheet_num, sheet_title, scale)
geom["texts"].extend(info["texts"])
return geom
@@ -0,0 +1,204 @@
import json
import os
from typing import Dict, List, Any
from collections import defaultdict
from core.bimlite import (
ModelBuilder, ManufacturingRulesEngine, ValidationEngine, ReviewEngine,
FingerprintBuilder, NormalizationEngine, SimilarityEngine
)
class UnitMatrixBuilder:
@staticmethod
def save_version_store(signatures_map: Dict[str, Any], filepath: str):
os.makedirs(os.path.dirname(filepath), exist_ok=True)
with open(filepath, 'w') as f:
json.dump(signatures_map, f, indent=4)
@staticmethod
def load_version_store(filepath: str) -> Dict[str, Any]:
if os.path.exists(filepath):
with open(filepath, 'r') as f:
return json.load(f)
return {}
@staticmethod
def _stable_sort_and_assign(canonical_map: Dict[str, Any], prefix: str, existing_store: Dict[str, Any]) -> Dict[str, str]:
"""
Sorts the unique hashes by topology complexity (cabinet count, width)
to assign stable K1, K2, V1, V2 names.
Returns a mapping from Hash -> TypeName (e.g., 'hash123' -> 'K1')
"""
# Collect all unique canonicals
items = []
for h, data in canonical_map.items():
cab_count = len(data['canonical_geometry']['cabinets'])
total_w = sum(c['w'] for c in data['canonical_geometry']['cabinets'])
room_id = data['canonical_metadata']['id']
items.append((cab_count, total_w, room_id, h))
# Sort by Cabinet Count -> Total Width -> Room UUID (fallback)
items.sort(key=lambda x: (x[0], x[1], x[2]))
assigned = {}
# First pass: map any that already exist in the existing_store
# We need a reverse map from existing_store hash -> TypeName
existing_hash_to_type = {}
for type_name, history in existing_store.items():
# Get latest version hash
latest_v = max(history.keys(), key=lambda k: int(k.replace('v', '')))
latest_hash = history[latest_v]['hash']
existing_hash_to_type[latest_hash] = type_name
counter = len(existing_store) + 1
for _, _, _, h in items:
if h in existing_hash_to_type:
assigned[h] = existing_hash_to_type[h]
else:
assigned[h] = f"{prefix}{counter}"
counter += 1
return assigned
@staticmethod
def build_unit_matrix(unit_data: List[Dict[str, Any]], project_config: Dict[str, Any]) -> Dict[str, Any]:
"""Runs the entire BIM-lite pipeline to generate the K/V matrix."""
k_store = UnitMatrixBuilder.load_version_store("data/kitchen_signatures.json")
v_store = UnitMatrixBuilder.load_version_store("data/vanity_signatures.json")
# 1. Build Model
project = ModelBuilder.build_project(project_config.get('name', 'Project'), project_config, unit_data)
results = []
k_canonicals = {}
v_canonicals = {}
# 2. Process each room
for building in project.buildings:
for unit in building.units:
k_type = "NONE"
v_type = "NONE"
is_ada = False
for room in unit.rooms:
if room.is_ada:
is_ada = True
# 3. Manufacturing Rules
room = ManufacturingRulesEngine.apply_rules(room)
# 4. Validation & Review
report = ValidationEngine.validate_intent(room)
if not ReviewEngine.review(report):
continue # Skip invalid rooms
# 5. Fingerprint (Geometry vs Metadata)
canonical = FingerprintBuilder.build_canonical(room)
# 6. Normalize & Hash
norm_geom = NormalizationEngine.normalize(canonical['canonical_geometry'])
room_hash = SimilarityEngine.get_hash(norm_geom)
if room.name == "Kitchen":
k_canonicals[room_hash] = canonical
else:
v_canonicals[room_hash] = canonical
results.append({
"unit_name": unit.name,
"unit_qty": unit.quantity,
"kitchen_hash": list(k_canonicals.keys())[-1] if k_canonicals else None, # Temp reference
"vanity_hash": list(v_canonicals.keys())[-1] if v_canonicals else None,
"is_ada": is_ada
})
# 7. Stable Sorting and Assignment
k_assignments = UnitMatrixBuilder._stable_sort_and_assign(k_canonicals, "K", k_store)
v_assignments = UnitMatrixBuilder._stable_sort_and_assign(v_canonicals, "V", v_store)
# 8. Update Version Stores
for h, t_name in k_assignments.items():
if t_name not in k_store:
k_store[t_name] = {}
# Check if this hash is already in the history
hash_exists = any(v['hash'] == h for v in k_store[t_name].values())
if not hash_exists:
next_v = f"v{len(k_store[t_name]) + 1}"
k_store[t_name][next_v] = {
"hash": h,
"canonical_geometry": k_canonicals[h]['canonical_geometry'],
"canonical_metadata": k_canonicals[h]['canonical_metadata']
}
for h, t_name in v_assignments.items():
if t_name not in v_store:
v_store[t_name] = {}
hash_exists = any(v['hash'] == h for v in v_store[t_name].values())
if not hash_exists:
next_v = f"v{len(v_store[t_name]) + 1}"
v_store[t_name][next_v] = {
"hash": h,
"canonical_geometry": v_canonicals[h]['canonical_geometry'],
"canonical_metadata": v_canonicals[h]['canonical_metadata']
}
# 9. Finalize Results with assigned names
final_results = []
for r in results:
k_type = k_assignments.get(r['kitchen_hash'], "NONE") if r['kitchen_hash'] else "NONE"
v_type = v_assignments.get(r['vanity_hash'], "NONE") if r['vanity_hash'] else "NONE"
final_results.append({
"unit_name": r['unit_name'],
"unit_qty": r['unit_qty'],
"kitchen_type": k_type,
"vanity_type": v_type,
"is_ada": r['is_ada']
})
UnitMatrixBuilder.save_version_store(k_store, "data/kitchen_signatures.json")
UnitMatrixBuilder.save_version_store(v_store, "data/vanity_signatures.json")
return final_results
@staticmethod
def group_by_building(unit_matrix: List[Dict[str, Any]], project_config: Dict[str, Any]) -> Dict[str, List[Dict[str, Any]]]:
"""Splits the matrix by building defined in project_config."""
buildings_config = project_config.get('buildings', {})
if not buildings_config:
return {"PROJECT TOTALS": unit_matrix}
grouped = defaultdict(list)
unmapped = []
for row in unit_matrix:
unit_name = row['unit_name']
assigned = False
for bldg, units in buildings_config.items():
if unit_name in units:
grouped[bldg].append(row)
assigned = True
break
if not assigned:
unmapped.append(row)
if unmapped:
grouped["UNMAPPED"] = unmapped
return dict(grouped)
@staticmethod
def calculate_kitchen_totals(unit_matrix: List[Dict[str, Any]]) -> Dict[str, int]:
totals = defaultdict(int)
for row in unit_matrix:
k_type = row.get('kitchen_type', 'NONE')
if k_type != 'NONE':
totals[k_type] += row.get('unit_qty', 0)
return dict(totals)
@staticmethod
def calculate_vanity_totals(unit_matrix: List[Dict[str, Any]]) -> Dict[str, int]:
totals = defaultdict(int)
for row in unit_matrix:
v_type = row.get('vanity_type', 'NONE')
if v_type != 'NONE':
totals[v_type] += row.get('unit_qty', 0)
return dict(totals)
@@ -0,0 +1,112 @@
from typing import Dict, List, Tuple
class ViewportScalingEngine:
SHEET_SIZES = {
'11x17': {'w': 17.0, 'h': 11.0},
'24x36': {'w': 36.0, 'h': 24.0}
}
SCALES = {
"1/2\"=1'-0\"": 24.0,
"3/8\"=1'-0\"": 32.0,
"1/4\"=1'-0\"": 48.0,
"1/8\"=1'-0\"": 96.0
}
@staticmethod
def get_bounds(geometry: Dict[str, List]) -> Tuple[float, float, float, float]:
min_x, min_y = float('inf'), float('inf')
max_x, max_y = float('-inf'), float('-inf')
has_geometry = False
for rect in geometry.get('blocks', []):
if rect['type'] == 'rect':
x, y, w, h = rect['coords']
min_x, max_x = min(min_x, x), max(max_x, x + w)
min_y, max_y = min(min_y, y), max(max_y, y + h)
has_geometry = True
elif rect['type'] == 'circle':
x, y, r = rect['coords']
min_x, max_x = min(min_x, x - r), max(max_x, x + r)
min_y, max_y = min(min_y, y - r), max(max_y, y + r)
has_geometry = True
for line in geometry.get('lines', []):
x1, y1 = line['start']
x2, y2 = line['end']
min_x, max_x = min(min_x, x1, x2), max(max_x, x1, x2)
min_y, max_y = min(min_y, y1, y2), max(max_y, y1, y2)
has_geometry = True
if not has_geometry:
return 0.0, 0.0, 0.0, 0.0
return min_x, min_y, max_x, max_y
@staticmethod
def compute_scale(bbox: Tuple[float, float, float, float], sheet_bounds: Tuple[float, float], margins: float = 1.0) -> float:
min_x, min_y, max_x, max_y = bbox
geom_w = max_x - min_x
geom_h = max_y - min_y
if geom_w <= 0 or geom_h <= 0:
return 1.0
sheet_w, sheet_h = sheet_bounds
avail_w = sheet_w - (margins * 2)
avail_h = sheet_h - (margins * 2)
scale_x = avail_w / geom_w
scale_y = avail_h / geom_h
return min(scale_x, scale_y) * 0.9 # 90% to leave breathing room
@staticmethod
def center_geometry(geometry: Dict[str, List], dx: float, dy: float, scale: float = 1.0) -> Dict[str, List]:
centered = {'lines': [], 'blocks': [], 'texts': []}
for b in geometry.get('blocks', []):
nb = b.copy()
if b['type'] == 'rect':
x, y, w, h = b['coords']
nb['coords'] = [(x * scale) + dx, (y * scale) + dy, w * scale, h * scale]
elif b['type'] == 'circle':
x, y, r = b['coords']
nb['coords'] = [(x * scale) + dx, (y * scale) + dy, r * scale]
centered['blocks'].append(nb)
for l in geometry.get('lines', []):
nl = l.copy()
x1, y1 = l['start']
x2, y2 = l['end']
nl['start'] = [(x1 * scale) + dx, (y1 * scale) + dy]
nl['end'] = [(x2 * scale) + dx, (y2 * scale) + dy]
centered['lines'].append(nl)
for t in geometry.get('texts', []):
nt = t.copy()
x, y = t['pos']
nt['pos'] = [(x * scale) + dx, (y * scale) + dy]
nt['size'] = t.get('size', 4.5) * scale
centered['texts'].append(nt)
return centered
@staticmethod
def fit_to_sheet(geometry: Dict[str, List], sheet_size: str = '11x17') -> Dict[str, List]:
size = ViewportScalingEngine.SHEET_SIZES.get(sheet_size, ViewportScalingEngine.SHEET_SIZES['11x17'])
sheet_w, sheet_h = size['w'], size['h']
bbox = ViewportScalingEngine.get_bounds(geometry)
scale = ViewportScalingEngine.compute_scale(bbox, (sheet_w, sheet_h))
min_x, min_y, max_x, max_y = bbox
geom_center_x = (min_x + max_x) / 2.0 * scale
geom_center_y = (min_y + max_y) / 2.0 * scale
sheet_center_x = sheet_w / 2.0
sheet_center_y = sheet_h / 2.0
dx = sheet_center_x - geom_center_x
dy = sheet_center_y - geom_center_y
return ViewportScalingEngine.center_geometry(geometry, dx, dy, scale)
+109
View File
@@ -0,0 +1,109 @@
from typing import Dict, List, Tuple
class WallEngine:
"""Procedural generator for architectural walls, hatches, and openings."""
@staticmethod
def draw_wall_core(start: Tuple[float, float], end: Tuple[float, float], thickness: float = 4.5, scale: float = 1.0) -> Dict[str, List]:
"""Draws the core structure lines of a wall."""
geom = {"lines": [], "blocks": [], "texts": []}
x1, y1 = start
x2, y2 = end
# Simplified assumption for horizontal walls for MVP
if abs(y1 - y2) < 0.1: # Horizontal
geom["lines"].append({"start": [x1, y1], "end": [x2, y2], "layer": "WALLS", "style": "solid"})
geom["lines"].append({"start": [x1, y1 + thickness * scale], "end": [x2, y2 + thickness * scale], "layer": "WALLS", "style": "solid"})
else: # Vertical
geom["lines"].append({"start": [x1, y1], "end": [x2, y2], "layer": "WALLS", "style": "solid"})
geom["lines"].append({"start": [x1 + thickness * scale, y1], "end": [x2 + thickness * scale, y2], "layer": "WALLS", "style": "solid"})
return geom
@staticmethod
def draw_finish_face(start: Tuple[float, float], end: Tuple[float, float], offset: float = 0.5, scale: float = 1.0) -> Dict[str, List]:
"""Draws the drywall/finish line offset from the core."""
geom = {"lines": [], "blocks": [], "texts": []}
x1, y1 = start
x2, y2 = end
if abs(y1 - y2) < 0.1: # Horizontal
geom["lines"].append({"start": [x1, y1 - offset * scale], "end": [x2, y2 - offset * scale], "layer": "WALL_FINISH", "style": "solid"})
else: # Vertical
geom["lines"].append({"start": [x1 - offset * scale, y1], "end": [x2 - offset * scale, y2], "layer": "WALL_FINISH", "style": "solid"})
return geom
@staticmethod
def draw_wall_hatch(x: float, y: float, w: float, h: float, pattern: str = "ANSI31", scale: float = 1.0) -> Dict[str, List]:
"""Draws the architectural hatch pattern within the wall core."""
geom = {"lines": [], "blocks": [], "texts": []}
# A true hatch is complex; we'll simulate by returning a hatch polygon block
geom["blocks"].append({
"type": "rect",
"coords": [x, y, w, h],
"layer": "WALL_HATCH",
"style": "hatch_" + pattern.lower()
})
return geom
@staticmethod
def draw_opening(x: float, y: float, width: float, depth: float = 4.5, scale: float = 1.0) -> Dict[str, List]:
"""Draws a door or window opening interruption in the wall."""
geom = {"lines": [], "blocks": [], "texts": []}
# Opening lines usually cross the wall core
geom["lines"].append({"start": [x, y], "end": [x, y + depth * scale], "layer": "WALLS", "style": "solid"})
geom["lines"].append({"start": [x + width * scale, y], "end": [x + width * scale, y + depth * scale], "layer": "WALLS", "style": "solid"})
return geom
@staticmethod
def draw_centerline(start: Tuple[float, float], end: Tuple[float, float], scale: float = 1.0) -> Dict[str, List]:
"""Draws an architectural centerline."""
geom = {"lines": [], "blocks": [], "texts": []}
x1, y1 = start
x2, y2 = end
geom["lines"].append({"start": [x1, y1], "end": [x2, y2], "layer": "CENTERLINES", "style": "center"})
return geom
@staticmethod
def draw_hidden_wall(start: Tuple[float, float], end: Tuple[float, float], thickness: float = 4.5, scale: float = 1.0) -> Dict[str, List]:
"""Draws a hidden/below-grade wall."""
geom = {"lines": [], "blocks": [], "texts": []}
x1, y1 = start
x2, y2 = end
if abs(y1 - y2) < 0.1: # Horizontal
geom["lines"].append({"start": [x1, y1], "end": [x2, y2], "layer": "WALLS_HIDDEN", "style": "dashed"})
geom["lines"].append({"start": [x1, y1 + thickness * scale], "end": [x2, y2 + thickness * scale], "layer": "WALLS_HIDDEN", "style": "dashed"})
else: # Vertical
geom["lines"].append({"start": [x1, y1], "end": [x2, y2], "layer": "WALLS_HIDDEN", "style": "dashed"})
geom["lines"].append({"start": [x1 + thickness * scale, y1], "end": [x2 + thickness * scale, y2], "layer": "WALLS_HIDDEN", "style": "dashed"})
return geom
@staticmethod
def draw_demolition_wall(start: Tuple[float, float], end: Tuple[float, float], thickness: float = 4.5, scale: float = 1.0) -> Dict[str, List]:
"""Draws a wall marked for demolition."""
geom = {"lines": [], "blocks": [], "texts": []}
x1, y1 = start
x2, y2 = end
if abs(y1 - y2) < 0.1: # Horizontal
geom["lines"].append({"start": [x1, y1], "end": [x2, y2], "layer": "WALLS_DEMO", "style": "hidden"})
geom["lines"].append({"start": [x1, y1 + thickness * scale], "end": [x2, y2 + thickness * scale], "layer": "WALLS_DEMO", "style": "hidden"})
else: # Vertical
geom["lines"].append({"start": [x1, y1], "end": [x2, y2], "layer": "WALLS_DEMO", "style": "hidden"})
geom["lines"].append({"start": [x1 + thickness * scale, y1], "end": [x2 + thickness * scale, y2], "layer": "WALLS_DEMO", "style": "hidden"})
return geom
@staticmethod
def draw_soffit(start: Tuple[float, float], end: Tuple[float, float], depth: float = 12.0, scale: float = 1.0) -> Dict[str, List]:
"""Draws overhead soffit lines."""
geom = {"lines": [], "blocks": [], "texts": []}
x1, y1 = start
x2, y2 = end
if abs(y1 - y2) < 0.1: # Horizontal
geom["lines"].append({"start": [x1, y1 + depth * scale], "end": [x2, y2 + depth * scale], "layer": "SOFFIT", "style": "dashed"})
else: # Vertical
geom["lines"].append({"start": [x1 + depth * scale, y1], "end": [x2 + depth * scale, y2], "layer": "SOFFIT", "style": "dashed"})
return geom
@@ -0,0 +1,148 @@
import re
from pathlib import Path
from typing import List
from core.ai_vision_classifier import (
ElevationResult, WallIntent, ApplianceIntent, FixtureIntent
)
from core.pdf_extractor import PDFExtractor
from core.yolo_extractor import YOLOExtractor, YOLODetection
from core.dimension_parser import parse_imperial_mm, parse_metric_mm
class YoloIntentAdapter:
"""
Adapter that converts YOLO floor plan detections and native text dimensions
into the ElevationResult intent objects expected by the pipeline.
This provides a deterministic layout path without Gemini Vision.
"""
@staticmethod
def extract_from_floor_plan(pdf_path: Path, dpi: float = 300.0) -> List[ElevationResult]:
"""Run YOLO on the floor plan and combine with native text to produce intent objects."""
import fitz
doc = fitz.open(str(pdf_path))
page = doc[0]
pix = page.get_pixmap(dpi=int(dpi))
img_bytes = pix.tobytes("png")
import core.yolo_extractor
core.yolo_extractor.DETECTION_CONF = 0.30
yolo = YOLOExtractor()
yolo_res = yolo.detect_floor_plan(img_bytes, dpi=dpi)
all_appliances = yolo_res.get("appliances", [])
all_fixtures = yolo_res.get("fixtures", [])
# Get text spans and rects from PDF for deterministic region detection
with PDFExtractor(pdf_path) as ex:
spans = ex.extract_spans(0)
rects = ex.extract_rects(0)
from core.region_detector import RegionDetector
detector = RegionDetector(spans, rects, page.rect.width, page.rect.height)
detected_regions = detector.detect()
kitchens = [r for r in detected_regions if r.region_type == "KITCHEN"]
baths = [r for r in detected_regions if r.region_type in ("BATH", "VANITY")]
results: List[ElevationResult] = []
# Process each detected room region
for region_type, regions in [("KITCHEN", kitchens), ("BATH", baths)]:
for i, r in enumerate(regions):
label = f"{region_type} {i+1} (Deterministic)"
ev = ElevationResult(elevation_label=label, unit_type="UNKNOWN", project_name="Deterministic")
# r.crop_rect is (x0, y0, x1, y1) in PDF points
x0_pt, y0_pt, x1_pt, y1_pt = r.crop_rect
# Convert PDF points to pixels for YOLO symbol matching
x0_px = x0_pt * dpi / 72.0
y0_px = y0_pt * dpi / 72.0
x1_px = x1_pt * dpi / 72.0
y1_px = y1_pt * dpi / 72.0
# 1. Map Appliances inside this region
# YOLO appliances are dicts with x_in, width_in, type. But we need y_in to group walls.
# Actually, yolo_res["appliances"] only has x_in, width_in. It lost y_in.
# Wait, we can just use the room width as the wall length for a simple 1-wall approximation
# Calculate room's absolute coords
room_x_in = x0_px / dpi
room_y_in = y0_px / dpi
for app in all_appliances:
app_x_px = app["x_in"] * dpi
app_y_px = app.get("y_in", 0) * dpi
# Check if appliance center is within room bbox
if x0_px <= app_x_px <= x1_px and y0_px <= app_y_px <= y1_px:
# Relativize x_in to the room's left edge
rel_x = app["x_in"] - room_x_in
ev.appliances.append(ApplianceIntent(
type=app["type"],
width_in=app.get("width_in", 24.0),
height_in=36.0, # default base height
x_in=max(0.0, rel_x),
notes="source: yolo"
))
for fix in all_fixtures:
fix_x_px = fix["x_in"] * dpi
fix_y_px = fix.get("y_in", 0) * dpi
if x0_px <= fix_x_px <= x1_px and y0_px <= fix_y_px <= y1_px:
rel_x = fix["x_in"] - room_x_in
ev.fixtures.append(FixtureIntent(
type=fix["type"],
width_in=fix.get("width_in", 24.0),
x_in=max(0.0, rel_x),
notes="source: yolo"
))
# 2. Extract Native Text Dimensions for Wall length
# We already have x0_pt, y0_pt, x1_pt, y1_pt from crop_rect
# Expand search area slightly for dimensions that might sit just outside the bounding box
bx0_pt, by0_pt = x0_pt - 40.0, y0_pt - 40.0
bx1_pt, by1_pt = x1_pt + 40.0, y1_pt + 40.0
# Pixel-derived width is the ground-truth fallback.
# At the rendering DPI, (x1_px-x0_px)/dpi gives page-inches which
# must then be multiplied by the architectural scale.
# Standard residential scale: 1/4"=1'-0" → 1 paper-inch = 48 real inches.
# Typical kitchen region in a floor plan at 300 DPI: 100–400px → 0.3–1.3 paper-inches
# → 16–62 real feet (192–744 inches). Use that as a sanity window.
pixel_width_paper_in = (x1_px - x0_px) / dpi # paper inches
# Assume 1/4" = 1'-0" scale (48 real in per paper in) as safe default.
# Clamp architectural scale: if parsed dims suggest different scale, we'll use them.
ARCH_SCALE_FALLBACK = 24.0 # 1/2"=1'-0" is typical for kitchen details
pixel_derived_in = pixel_width_paper_in * ARCH_SCALE_FALLBACK
# Parse dimensions, but only accept plausible kitchen/vanity wall widths:
# Real kitchen walls: 48" (4') to 300" (25'). Reject outliers.
MIN_WALL_IN = 48.0
MAX_WALL_IN = 300.0
max_dim_in = 0.0
for s in spans:
if bx0_pt <= s.cx <= bx1_pt and by0_pt <= s.cy <= by1_pt:
mm_val = parse_imperial_mm(s.text) or parse_metric_mm(s.text)
if mm_val:
in_val = mm_val / 25.4
# Only accept dimensions in the plausible wall-length range
if MIN_WALL_IN <= in_val <= MAX_WALL_IN:
if in_val > max_dim_in:
max_dim_in = in_val
# If no plausible dimension was found, fall back to pixel-derived estimate.
# Clamp that too — if YOLO crops an unreasonably large region, pin to 168" (14').
if max_dim_in == 0.0:
max_dim_in = max(MIN_WALL_IN, min(pixel_derived_in, MAX_WALL_IN))
ev.walls.append(WallIntent(
name=label,
length_in=round(max_dim_in, 1),
notes="YOLO+NativeText length"
))
results.append(ev)
return results
+83
View File
@@ -0,0 +1,83 @@
"""
===========================================================================
core/geometry_engine.py — High-Fidelity 2D CAD Layouts Engine
===========================================================================
Translates sequenced cabinets, appliances, and openings into detailed
architectural 2D lines, dimensions, texts, and swing annotations.
===========================================================================
"""
from __future__ import annotations
from typing import List, Dict, Any
from core.engines.floor_plan_generator import FloorPlanGenerator
from core.engines.elevation_generator import ElevationGenerator
class GeometryEngine:
"""
Builds plan views and detailed elevation views coordinates.
All dimensions inside this engine use inches.
"""
def __init__(self):
pass
def generate_layout_geometry(
self,
walls: list[dict],
appliances: list[dict],
ceiling_height: float = 108.0,
soffit_height: float = 96.0,
unit_type: str = 'kitchen_standard'
) -> dict:
"""
Processes wall runs to generate plan and elevation geometries.
Returns:
{
"plan": { "lines": [], "dimensions": [], "blocks": [], "texts": [] },
"elevation": { "lines": [], "dimensions": [], "blocks": [], "texts": [] },
"side": { "lines": [], "dimensions": [], "blocks": [], "texts": [] }
}
"""
# Call the new modular engines
plan_geom = FloorPlanGenerator.generate(
walls=walls,
start_ox=0.0,
start_oy=0.0,
scale_factor=1.0
)
elev_geom = ElevationGenerator.generate(
walls=walls,
start_ox=0.0,
start_oy=0.0,
ceiling_height=ceiling_height,
scale_x=1.0,
scale_y=1.0
)
from core.engines.section_generator import SectionGenerator
try:
# Check if there are ADA cabinets in the walls
is_ada = False
for w in walls:
for cab in w.get("base_cfg", []):
if cab.get("is_ada"):
is_ada = True
break
if is_ada: break
actual_type = unit_type
if is_ada and not actual_type.endswith("_ada"):
actual_type = actual_type.replace("_standard", "_ada")
section_res = SectionGenerator.generate_section(actual_type, ada=is_ada)
side_geom = section_res['geometry']
except Exception as e:
# Fallback
side_geom = {"lines": [], "dimensions": [], "blocks": [], "texts": []}
return {
"plan": plan_geom,
"elevation": elev_geom,
"side": side_geom
}
+204
View File
@@ -0,0 +1,204 @@
"""
===========================================================================
core/legend_extractor.py — Keynote Legend Extractor
===========================================================================
Dynamically extracts the U-code keynotes legend (e.g., U1-U50) and their
descriptions from architectural drawing sheets. Works for both single-page
and multi-page PDFs, and handles multi-column legend layouts.
===========================================================================
"""
from __future__ import annotations
import re
from pathlib import Path
from typing import Optional, Dict
import fitz # PyMuPDF
from core.pdf_extractor import PDFExtractor, TextSpan
class LegendExtractor:
"""
Extracts U-code legends from architectural drawing pages.
"""
def __init__(self, spans: list[TextSpan], page_w: float, page_h: float):
self.spans = spans
self.page_w = page_w
self.page_h = page_h
def extract(self) -> dict[str, str]:
"""
Scan page text, find the legend area, and reconstruct keynote dictionary.
Returns a dictionary of { "U1": "Description...", "U2": "Description..." }
"""
# 1. Locate the legend header (e.g., "KEYNOTE LEGEND" or "SYMBOL LEGEND")
header_span = None
for s in self.spans:
t = s.upper
if "KEYNOTE" in t and "LEGEND" in t:
header_span = s
break
if not header_span:
# Fallback: search for first span containing "LEGEND" or "KEYNOTE"
for s in self.spans:
t = s.upper
if "LEGEND" in t:
header_span = s
break
# Define boundary of legend area
if header_span:
# Legend starts below the header and occupies the right portion of the sheet
lx0 = header_span.x0 - 200
ly0 = header_span.y1
# Extend to right edge of page
lx1 = self.page_w
ly1 = self.page_h
else:
# Fallback to rightmost 30% of the page
lx0 = self.page_w * 0.70
ly0 = 0
lx1 = self.page_w
ly1 = self.page_h
# 2. Filter spans within the legend area
legend_spans = [
s for s in self.spans
if lx0 <= s.x0 <= lx1 and ly0 <= s.y0 <= ly1 and len(s.text.strip()) > 0
]
if not legend_spans:
return {}
# 3. Detect column X coordinates for U-codes dynamically
# Look for spans matching U\d+ to identify U-code columns
u_pattern = re.compile(r'^U(\d+)$', re.IGNORECASE)
u_x_coords = []
for s in legend_spans:
if u_pattern.match(s.text.strip()):
u_x_coords.append(s.x0)
# Cluster U-code X coordinates to identify column starting points
columns = []
for x in sorted(u_x_coords):
# Group into existing column if close (within 40 pts)
matched = False
for col in columns:
if abs(col["start"] - x) < 40:
col["coords"].append(x)
col["start"] = sum(col["coords"]) / len(col["coords"])
matched = True
break
if not matched:
columns.append({"start": x, "coords": [x]})
columns.sort(key=lambda c: c["start"])
# Determine boundaries between columns
boundaries = []
for i in range(len(columns) - 1):
mid = (columns[i]["start"] + columns[i+1]["start"]) / 2
boundaries.append(mid)
# 4. Group legend spans by Y coordinate
lines_by_y: dict[float, list[TextSpan]] = {}
for s in legend_spans:
y = round(s.bbox[1], 1)
matched_y = None
for existing_y in lines_by_y:
if abs(existing_y - y) <= 3.0:
matched_y = existing_y
break
if matched_y is None:
lines_by_y[y] = [s]
else:
lines_by_y[matched_y].append(s)
# Sort lines top-to-bottom
sorted_ys = sorted(lines_by_y.keys())
# 5. Process each line and assign to columns
# We will track the current active U-code description for each column
col_active_key: dict[int, Optional[str]] = {i: None for i in range(len(columns) + 1)}
legend_dict: dict[str, list[str]] = {}
for y in sorted_ys:
line_spans = sorted(lines_by_y[y], key=lambda s: s.x0)
# Distribute spans on this line to columns based on boundaries
col_spans: dict[int, list[TextSpan]] = {i: [] for i in range(len(columns) + 1)}
for s in line_spans:
col_idx = 0
for b in boundaries:
if s.x0 > b:
col_idx += 1
else:
break
col_spans[col_idx].append(s)
# Process each column on this line
for col_idx in range(len(columns) + 1):
spans_in_col = col_spans[col_idx]
if not spans_in_col:
continue
# Check if first span is a U-code (starts a new description)
first_text = spans_in_col[0].text.strip()
m = u_pattern.match(first_text)
if m:
u_code = first_text.upper()
col_active_key[col_idx] = u_code
legend_dict[u_code] = []
# The rest of the spans in this column are part of the description
desc_parts = [s.text.strip() for s in spans_in_col[1:] if s.text.strip()]
if desc_parts:
legend_dict[u_code].append(" ".join(desc_parts))
else:
# Append to active keynote in this column if we have one
u_code = col_active_key[col_idx]
if u_code:
desc_parts = [s.text.strip() for s in spans_in_col if s.text.strip()]
if desc_parts:
legend_dict[u_code].append(" ".join(desc_parts))
# Join the list of text lines for each U-code into a single string
final_legend: dict[str, str] = {}
for u_code, lines in legend_dict.items():
full_desc = " ".join(lines).strip()
# Clean up double spaces or trailing periods/commas
full_desc = re.sub(r'\s+', ' ', full_desc)
final_legend[u_code] = full_desc
return final_legend
def extract_legend_from_pdf(pdf_path: str | Path) -> dict[str, str]:
"""Convenience wrapper to load PDF and extract keynote legend."""
pdf_path = Path(pdf_path)
if not pdf_path.exists():
return {}
with PDFExtractor(pdf_path) as ex:
# Keynotes are always on sheet 0 (first page of details)
page = ex.extract_page(0)
extractor = LegendExtractor(page.spans, page.page_w, page.page_h)
return extractor.extract()
# ══════════════════════════════════════════════════════════════════════════
# QUICK TEST
# ══════════════════════════════════════════════════════════════════════════
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python -m core.legend_extractor <path_to_pdf>")
sys.exit(1)
pdf = sys.argv[1]
legend = extract_legend_from_pdf(pdf)
print(f"\nExtracted {len(legend)} U-code legend keys:")
for k in sorted(legend.keys(), key=lambda x: int(x[1:]) if x[1:].isdigit() else 999):
print(f" {k:5s} -> {legend[k][:80]}...")
+78
View File
@@ -0,0 +1,78 @@
import numpy as np
from paddleocr import PaddleOCR
from typing import List
from core.pdf_extractor import TextSpan
import cv2
class OCREngine:
_instance = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
# Initialize PaddleOCR with English language
# use_angle_cls=True is vital for rotated architectural text
self.ocr = PaddleOCR(use_angle_cls=True, lang='en', show_log=False)
def extract_spans(self, img_bytes: bytes, dpi: int) -> List[TextSpan]:
"""
Takes raw PNG bytes, runs OCR, and returns TextSpans
mapped back to the 72 DPI PDF space.
"""
# Convert bytes to numpy array for OpenCV
nparr = np.frombuffer(img_bytes, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
# Run OCR
results = self.ocr.ocr(img, cls=True)
spans = []
if not results or not results[0]:
return spans
# PDF space scale factor
scale = 72.0 / dpi
for line in results[0]:
box, (text, score) = line
# PaddleOCR returns a 4-point polygon. Get bounding box.
xs = [pt[0] for pt in box]
ys = [pt[1] for pt in box]
x0, x1 = min(xs), max(xs)
y0, y1 = min(ys), max(ys)
# Map back to 72 DPI space
pdf_x0 = x0 * scale
pdf_y0 = y0 * scale
pdf_x1 = x1 * scale
pdf_y1 = y1 * scale
# Determine text direction (horizontal vs vertical)
width = x1 - x0
height = y1 - y0
is_vertical = height > (width * 1.5) # simple heuristic
dir_vec = (0.0, -1.0) if is_vertical else (1.0, 0.0)
origin = (pdf_x0, pdf_y1)
# Approximate font size in PDF points
size = (height * scale) if not is_vertical else (width * scale)
size = min(size, 24.0) # Cap to reasonable maximum
spans.append(TextSpan(
text=text.strip(),
bbox=(pdf_x0, pdf_y0, pdf_x1, pdf_y1),
origin=origin,
font="PaddleOCR",
size=size,
color=0,
dir=dir_vec
))
return spans
+228
View File
@@ -0,0 +1,228 @@
"""
===========================================================================
core/opening_extractor.py — Doors & Windows Extractor
===========================================================================
Extracts real structural openings from PDF vector geometry and text.
Strategy (in priority order):
1. Vector rect scan: Match VectorRect bounding boxes against typical
door/window aspect ratios and sizes.
2. Dimension proximity: Use nearby dimension text spans to get exact
width for each opening rect.
3. Keynote lookup: Resolve D\d+ / W\d+ tags against the legend_map
(passed in per project — Heritage uses 1-30 numbered scheme, Casa
Familia uses U# scheme — NOT a shared hard-coded vocabulary).
4. If real size cannot be determined, emit a NEEDS_REVIEW flag instead
of silently inventing a 36" opening.
This module NEVER emits a fixed-size opening solely because the word
"WINDOW" or "DOOR" appears anywhere in the page text (old stub behaviour
that fired on boilerplate legend text on nearly every sheet).
===========================================================================
"""
from __future__ import annotations
import re
from typing import Optional
from core.pdf_extractor import TextSpan, VectorRect
# ── Heuristic size ranges for opening classification ─────────────────────
# These are the ONLY criteria used for vector-rect classification.
DOOR_WIDTH_RANGE = (18.0, 72.0) # inches
DOOR_HEIGHT_RANGE = (76.0, 98.0) # inches
WIN_WIDTH_RANGE = (12.0, 84.0) # inches
WIN_HEIGHT_RANGE = (18.0, 72.0) # inches
# Approximate PDF scale: how many PDF user-units equal one inch.
# 72 DPI is the base. Drawings are typically 1/4" = 1' scale.
# This is calibrated against observed rect sizes — not assumed.
PDF_UNITS_PER_INCH = 72.0 / 96.0 # will be overridden by page dimensions if provided
def _rect_to_inches(rect: VectorRect, scale: float = 1.0) -> tuple[float, float]:
"""Return (width_in, height_in) for a VectorRect, applying scale."""
return rect.w / scale, rect.h / scale
def _parse_dim_text(text: str) -> float | None:
"""
Parse an architectural dimension string into inches.
Handles: '3\'-0"', '36"', '36 in', '914', '0.914' (metres treated as mm×1000).
Returns float inches or None.
"""
text = text.strip()
# Feet-inches: 3'-0" or 3'0"
m = re.match(r"(\d+)'[\-\s]*(\d+)(?:\"|\s*in)?", text)
if m:
return int(m.group(1)) * 12.0 + int(m.group(2))
# Inches only: 36"
m = re.match(r"(\d+(?:\.\d+)?)\s*\"", text)
if m:
return float(m.group(1))
# Millimetres: 914 or 914mm — if value > 100 it's probably mm
m = re.match(r"(\d{3,4})(?:\s*mm)?$", text)
if m:
val = float(m.group(1))
if val > 100:
return val / 25.4 # mm → inches
return None
def _nearest_dim(
cx: float,
cy: float,
spans: list[TextSpan],
search_radius: float = 60.0, # PDF units
) -> float | None:
"""
Find the nearest dimension-like text span within search_radius of (cx, cy).
Returns parsed inches or None.
"""
best_dist = search_radius
best_val = None
for s in spans:
dist = ((s.cx - cx) ** 2 + (s.cy - cy) ** 2) ** 0.5
if dist > best_dist:
continue
parsed = _parse_dim_text(s.text)
if parsed is not None and 6.0 < parsed < 120.0: # sanity: 6"–10'
best_val = parsed
best_dist = dist
return best_val
class OpeningExtractor:
"""
Identifies door/window openings from PDF vector geometry + text.
Call extract_openings() with the spans and rects from one PDF page.
Pass legend_map (from LegendExtractor) so keynote tags can be resolved
to real sizes for this specific project's drawing set.
"""
@staticmethod
def extract_openings(
spans: list[TextSpan],
rects: list[VectorRect],
legend_map: dict[str, str] | None = None,
page_scale: float = PDF_UNITS_PER_INCH,
) -> dict:
"""
Returns:
{
"doors": [{"width_in":…, "height_in":…, "x_in":…, "notes":…}],
"windows": [{"width_in":…, "height_in":…, "x_in":…, "sill_height_in":…, "notes":…}],
"review_flags": ["…"] # populated when sizes cannot be confirmed
}
"""
legend_map = legend_map or {}
doors: list[dict] = []
windows: list[dict] = []
review_flags: list[str] = []
# ── Step 1: Classify VectorRects by aspect ratio / size ──────────
candidate_doors: list[VectorRect] = []
candidate_windows: list[VectorRect] = []
for rect in rects:
if rect.w <= 0 or rect.h <= 0:
continue
w_in = rect.w / page_scale
h_in = rect.h / page_scale
# Doors are taller than wide, in typical door size range
if (DOOR_WIDTH_RANGE[0] <= w_in <= DOOR_WIDTH_RANGE[1]
and DOOR_HEIGHT_RANGE[0] <= h_in <= DOOR_HEIGHT_RANGE[1]
and h_in > w_in):
candidate_doors.append(rect)
# Windows are wider than tall (usually) and in window size range
elif (WIN_WIDTH_RANGE[0] <= w_in <= WIN_WIDTH_RANGE[1]
and WIN_HEIGHT_RANGE[0] <= h_in <= WIN_HEIGHT_RANGE[1]
and w_in >= h_in * 0.5):
candidate_windows.append(rect)
# ── Step 2: Resolve keynote tags D\d+ / W\d+ from text spans ─────
# Build a per-page tag→size map from legend_map for this project.
tag_dims: dict[str, float] = {}
for s in spans:
tag_match = re.search(r'\b([DW])(\d+)\b', s.text.upper())
if not tag_match:
continue
prefix, num = tag_match.group(1), tag_match.group(2)
full_tag = f"{prefix}{num}"
# Legend map may carry e.g. {"W7": "3'-0\" X 4'-0\""} or similar
legend_entry = legend_map.get(full_tag, "")
if legend_entry:
# Try to parse the first dimension as width
parts = re.split(r'[Xx×]', legend_entry)
if parts:
parsed = _parse_dim_text(parts[0])
if parsed:
tag_dims[full_tag] = parsed
# ── Step 3: Emit door records ─────────────────────────────────────
for rect in candidate_doors:
cx, cy = (rect.x0 + rect.x1) / 2.0, (rect.y0 + rect.y1) / 2.0
w_in = rect.w / page_scale
h_in = rect.h / page_scale
# Try to refine width from nearest dimension text
refined = _nearest_dim(cx, cy, spans)
if refined:
w_in = refined
doors.append({
"width_in": round(w_in, 1),
"height_in": round(h_in, 1),
"x_in": round(cx / page_scale, 1),
"notes": "Detected from vector geometry",
})
# ── Step 4: Emit window records ───────────────────────────────────
for rect in candidate_windows:
cx, cy = (rect.x0 + rect.x1) / 2.0, (rect.y0 + rect.y1) / 2.0
w_in = rect.w / page_scale
h_in = rect.h / page_scale
refined = _nearest_dim(cx, cy, spans)
if refined:
w_in = refined
windows.append({
"width_in": round(w_in, 1),
"height_in": round(h_in, 1),
"x_in": round(cx / page_scale, 1),
"sill_height_in": 36.0, # standard sill; override if extracted
"notes": "Detected from vector geometry",
})
# ── Step 5: Tag-only fallback — only when NO rect was detected ────
# If a keynote tag exists and no geometric rect was found, emit a
# NEEDS_REVIEW flag rather than inventing a fixed-size opening.
for tag, dim in tag_dims.items():
prefix = tag[0]
already_emitted = (
(prefix == "D" and doors) or
(prefix == "W" and windows)
)
if not already_emitted:
flag = (
f"Tag '{tag}' found in text (legend: dim={dim:.1f}\") "
f"but no matching vector rect detected — verify opening manually."
)
review_flags.append(flag)
return {
"doors": doors,
"windows": windows,
"review_flags": review_flags,
}
+17 -2
View File
@@ -251,16 +251,31 @@ class PDFExtractor:
# ── Full Page Extraction ──────────────────────────────────────────────
def extract_page(self, page_num: int = 0) -> PageData:
def extract_page(self, page_num: int = 0, force_ocr: bool = False) -> PageData:
"""Extract all text, geometry from a single page."""
self._ensure_open()
page = self._doc[page_num]
spans = self.extract_spans(page_num)
# OCR Fallback Heuristic
if force_ocr or len(spans) < 20:
try:
from core.ocr_engine import OCREngine
engine = OCREngine.get_instance()
# Render page at 400 DPI for OCR
img_bytes = self.render_full_page(page_num, dpi=400)
spans = engine.extract_spans(img_bytes, dpi=400)
print(f" [OCR] Extracted {len(spans)} text spans via PaddleOCR (Rasterized Page Fallback)")
except Exception as e:
print(f" [WARN] OCR Fallback failed: {e}")
return PageData(
pdf_path = str(self.pdf_path),
page_num = page_num,
page_w = page.rect.width,
page_h = page.rect.height,
spans = self.extract_spans(page_num),
spans = spans,
rects = self.extract_rects(page_num),
paths = self.extract_paths(page_num),
)

Some files were not shown because too many files have changed in this diff Show More