feat: Integrated PaddleOCR for rasterized PDF extraction, updated core processors and project analysis
@@ -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
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
## 📥 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.
|
||||
|
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.
|
||||
@@ -1,176 +0,0 @@
|
||||
# Architecture & Code-Quality Review
|
||||
|
||||
_Deep-dive analysis of the AI Cabinet Estimation pipeline. Generated 2026-07-06._
|
||||
|
||||
---
|
||||
|
||||
## 1. System Purpose
|
||||
|
||||
Automates cabinet estimation + shop-drawing production for Italian Kitchen & Bath, a
|
||||
supplier for large multi-family residential projects (FHA/ADA housing). Input is the
|
||||
architect's PDF set; output is priced shop drawings, an estimation workbook, a BOM, and
|
||||
JSON deliverables. Target: replace days of manual drafting/estimating with a <24h run.
|
||||
|
||||
---
|
||||
|
||||
## 2. Architecture
|
||||
|
||||
The system is a linear orchestration in [`pipeline.py`](../pipeline.py) with well-separated
|
||||
layers. The guiding design principle is sound: **the AI proposes, deterministic engines
|
||||
dispose** — vision output is treated as a hint, then re-derived from geometry + rules.
|
||||
|
||||
```
|
||||
PDF ─▶ extraction ─▶ AI vision ─▶ validation/QA ─▶ BIM-lite + placement ─▶ pricing/costing ─▶ generators
|
||||
```
|
||||
|
||||
| Layer | Modules | Role |
|
||||
|-------|---------|------|
|
||||
| Extraction | `pdf_extractor`, `drawing_classifier`, `region_detector`, `dimension_parser`, `ceiling_height_extractor`, `legend_extractor`, `opening_extractor` | PDF → typed geometry + text |
|
||||
| AI vision | `ai_vision_classifier` | Gemini 2.5 Flash/Pro (OpenRouter) → `CabinetItem` + architectural intent |
|
||||
| Validation | `cabinet_validator`, `confidence_engine` | Rule + confidence QA, auto-approve/flag |
|
||||
| Geometry/typing | `bimlite/*`, `engines/constraint_solver`, `engines/placement_engine`, `engines/layout_fingerprint_engine`, `engines/unit_matrix_builder` | Re-place cabinets, hash layouts into stable K#/V# types |
|
||||
| Costing | `price_matcher`, `job_costing`, `engines/material_takeoff_engine`, `engines/ada_engine` | EUR→USD match, selling price, BOM, ADA checks |
|
||||
| Output | `generators/*`, `engines/{elevation,floor_plan,section,sheet_composer,title_block,...}` | PDF / DXF / Excel / JSON |
|
||||
| Interface | `web_app/app.py` + static SPA | Project mgmt + live SSE pipeline runner |
|
||||
|
||||
**Strengths**
|
||||
- Clean layering and a defensible "hint vs. source-of-truth" split.
|
||||
- Fully config-driven and multi-project (`projects/<slug>/project_config.json`).
|
||||
- Cost-aware AI usage: DEMO_MODE (150 vs 400 DPI, compact prompt) + JSON caching (`--skip-ai`).
|
||||
- Good domain documentation in `_Project_Understanding/`.
|
||||
|
||||
---
|
||||
|
||||
## 3. Correctness Findings (audit)
|
||||
|
||||
### 3.1 🔴 HIGH — Placement engine is called with wrong signatures (crashes full AI runs)
|
||||
|
||||
In [`pipeline.py`](../pipeline.py) Step 2.5, the placement block calls:
|
||||
|
||||
```python
|
||||
constraints = ConstraintExtractor.extract(wall) # 1 arg
|
||||
runs = ConstraintSolver.solve(constraints)
|
||||
placed_cabs = PlacementEngine.place_wall(length_in=wall.length,
|
||||
available_runs=runs,
|
||||
is_ada=room.is_ada)
|
||||
```
|
||||
|
||||
But the actual APIs are:
|
||||
- `ConstraintExtractor.extract(wall_name, wall_length, openings, appliances, fixtures, structural, is_ada=False)` — **5 required positional args missing** → `TypeError`.
|
||||
- `PlacementEngine.place_wall(self, wc)` — an **instance method** taking a single
|
||||
`WallConstraints`; called unbound with `length_in=/available_runs=/is_ada=` kwargs that
|
||||
don't exist → `TypeError`.
|
||||
|
||||
**Why it hasn't surfaced:** the block only executes when `unit.rooms` has walls, and walls
|
||||
are only built when `ElevationResult.walls` is populated — which happens **only on a live AI
|
||||
run** (parsed at `ai_vision_classifier.py:511`). The cache serializer (`_save_schedule_json`)
|
||||
does **not** persist `walls/openings/fixtures/structural/clearances`, so `--skip-ai` runs
|
||||
have empty walls and the loop is a no-op. **All committed outputs were produced via
|
||||
`--skip-ai`.** A fresh full-AI run will crash at Step 2.5 because the block is **not**
|
||||
wrapped in try/except.
|
||||
|
||||
**Impact:** the "core IP" placement/constraint engine is effectively **not integrated** —
|
||||
in cache mode it never runs; in AI mode it throws. Downstream, cabinets in the shop drawings
|
||||
come from the AI output directly (or the re-mapping that never executes), not from the
|
||||
deterministic engine.
|
||||
|
||||
**Fix direction:** either (a) correct the call site to build a `WallConstraints` via
|
||||
`ConstraintExtractor.extract(wall.name, wall.length, wall.openings, wall.appliances,
|
||||
wall.fixtures, wall.structural, room.is_ada)`, instantiate `PlacementEngine()` and call
|
||||
`.place_wall(solved_wc)`; and (b) wrap Step 2.5 in try/except so a placement failure degrades
|
||||
gracefully instead of aborting the run. Add an integration test that runs one unit with
|
||||
`walls` present.
|
||||
|
||||
### 3.2 🟠 MEDIUM — Fallback pricing computes wrong cabinet codes (flat $100/cabinet)
|
||||
|
||||
In [`pipeline.py`](../pipeline.py) `compute_pricing()`, the no-price-list branch calls:
|
||||
|
||||
```python
|
||||
code = _generate_code(cab.cabinet_type, cab.width_in) # passes INCHES
|
||||
unit_cost += get_fallback_price_usd(code) * cab.quantity
|
||||
```
|
||||
|
||||
But [`price_matcher._generate_code(cabinet_type, width_mm)`](../core/price_matcher.py) treats
|
||||
its second arg as **millimeters**: `w_in = round(width_mm / 25.4)`. Passing inches (e.g. 36)
|
||||
yields `round(36/25.4)=1` → code `"B1"`, which is absent from `FALLBACK_USD_CATALOG` →
|
||||
`get_fallback_price_usd` returns its **$100 default for every cabinet**. So any project
|
||||
without a price list is priced at a flat $100/cabinet regardless of type/size.
|
||||
|
||||
**Not triggered for Casa Familia** (its price list exists), but latent for any new project
|
||||
run before a price list is attached. **Fix:** pass `cab.width_in * 25.4`, or add an
|
||||
inches-based code helper.
|
||||
|
||||
### 3.3 🟠 MEDIUM — `PriceMatcher.price_schedule()` is broken (unused, but a trap)
|
||||
|
||||
`price_schedule()` calls `self.match(cabinet_type=..., width_mm=item.width_mm, ...)`, but
|
||||
`match()`'s parameter is `width_in`, not `width_mm` → `TypeError` if ever called. The main
|
||||
path (`compute_pricing`) uses `matcher.match(...)` directly and is fine, so this is currently
|
||||
dead code — but it will bite whoever wires it up. **Fix:** rename to `width_in=` and convert,
|
||||
or delete the method.
|
||||
|
||||
### 3.4 🟡 LOW — Type-blind FALLBACK price matching can mis-price silently
|
||||
|
||||
In `PriceMatcher.match()`, if no type-keyword match is found, the final loop matches purely
|
||||
on **width**, ignoring cabinet type. A vanity with no vanity entry could be priced as a
|
||||
same-width base cabinet. It's tagged `match_quality="FALLBACK"` (visible), but nothing blocks
|
||||
it. Consider requiring a type match or flagging FALLBACK rows for review in the estimate.
|
||||
|
||||
### 3.5 🟢 Job costing math is correct
|
||||
|
||||
[`job_costing.calculate_selling_price`](../core/job_costing.py) is sound. Pre-margin =
|
||||
material + tax + freight + delivery + install + warehousing + protection + insurance + misc;
|
||||
`SP = pre_margin / (1 − GP% − commission% − bond%)`, with a guard for a non-positive
|
||||
denominator. Because commission/bond/GP are % of selling price, the algebraic (non-iterative)
|
||||
solve is valid; the `gp_check_pct` self-verification confirms it. No issues found.
|
||||
|
||||
### 3.6 🟢 Placement algorithm internals are reasonable
|
||||
|
||||
Within `placement_engine.py` the fill logic is coherent: exact-fit DP (fewest cabinets, then
|
||||
most balanced) with a largest-first greedy fallback that refuses widths leaving an
|
||||
un-fillable `< MIN_FILLER_WIDTH` gap, and end fillers absorbing slack. Minor nit: sink-base
|
||||
width selection (`sw <= anchor.width or sw == 36`) biases to 36" for most anchors — worth
|
||||
revisiting, but not a correctness bug. The engine just isn't reached (see 3.1).
|
||||
|
||||
---
|
||||
|
||||
## 4. Code-Quality / Structural Findings
|
||||
|
||||
| # | Area | Finding | Suggested action |
|
||||
|---|------|---------|------------------|
|
||||
| 4.1 | Repo hygiene | 157 generated artifacts (PDF/DXF/XLSX/CSV/PNG/JSON) + scratch scripts were tracked in git | **Done** — untracked (kept on disk) + `.gitignore` updated |
|
||||
| 4.2 | Duplication | `_Project_Understanding/` exists at both repo root and inside `Albert_Project/` | De-duplicate; keep one canonical copy |
|
||||
| 4.3 | Dead/legacy code | `config.py` keeps Claude/GPT-4o constants; `price_schedule()` broken; kitchen/vanity layout classifiers superseded by fingerprint engine but still imported | Prune or clearly mark legacy |
|
||||
| 4.4 | Config schema drift | Web `create_project` writes `client_name`/`cabinet_finish`/`project_address`; committed configs use `owner`/`finish`/`address`. Read defensively via `.get()` but inconsistent | Unify on one schema; add a loader that normalizes |
|
||||
| 4.5 | Empty signature store | `data/kitchen_signatures.json` is `{}`; fingerprint reuse only partially wired | Populate or document as future work |
|
||||
| 4.6 | Placeholder logic | `engines/ada_engine.py` has stub/partial checks | Flag outputs as provisional until complete |
|
||||
| 4.7 | Error handling | Step 2.5 unguarded (see 3.1); several `except Exception` swallow + `traceback.print_exc()` without failing the run | Make critical steps fail loud; keep generators soft-failing |
|
||||
| 4.8 | Testing | `test_*.py` are standalone scripts, not a pytest suite; no CI | Convert to pytest; add an integration test that exercises a full-AI unit |
|
||||
|
||||
---
|
||||
|
||||
## 5. Prioritized Recommendations
|
||||
|
||||
1. **Fix the placement-engine integration (3.1)** — it's the system's differentiator and is
|
||||
currently a no-op/crash. Correct the call site, guard the step, add an integration test.
|
||||
2. **Fix fallback pricing code generation (3.2)** — one-line unit bug that silently flattens
|
||||
pricing for any price-list-less project.
|
||||
3. **Decide cache contract** — either persist architectural-intent (`walls`, etc.) in the
|
||||
schedule JSON so `--skip-ai` and full runs behave identically, or explicitly scope the
|
||||
placement engine to full runs.
|
||||
4. **Unify config schema (4.4)** and prune legacy code (4.3, 3.3).
|
||||
5. **Add pytest + a CI smoke test** running `pipeline.py --skip-ai --dry-run` and a single
|
||||
unit end-to-end.
|
||||
6. **De-duplicate docs (4.2)** and keep generated outputs out of git (**done**).
|
||||
|
||||
---
|
||||
|
||||
## 6. Summary
|
||||
|
||||
Architecturally this is a well-conceived, cleanly layered system with a correct costing core
|
||||
and a sensible AI-as-hint design. The main gap between "looks complete" and "is complete" is
|
||||
the **placement/constraint engine**, which is wired into the pipeline with mismatched
|
||||
signatures and therefore never actually runs (no-op in cache mode, crash in AI mode). That
|
||||
plus the fallback-pricing unit bug are the two findings worth fixing before the next live run.
|
||||
Everything else is hygiene: untracking generated artifacts (done), unifying the config schema,
|
||||
pruning legacy modules, and standing up a real test suite.
|
||||
</content>
|
||||
@@ -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 and legend mappings
|
||||
3. Call: OpenRouter API (gemini-2.5-flash) with base64 image
|
||||
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-pro if JSON parse fails or confidence < 0.7
|
||||
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 ─────────────────────
|
||||
@@ -129,6 +129,8 @@ VALID_CABINET_TYPES = {
|
||||
}
|
||||
|
||||
|
||||
from core.units import Length
|
||||
|
||||
@dataclass
|
||||
class CabinetItem:
|
||||
"""One cabinet identified in an elevation drawing.
|
||||
@@ -139,9 +141,9 @@ class CabinetItem:
|
||||
"""
|
||||
item_num: int
|
||||
cabinet_type: str # from VALID_CABINET_TYPES
|
||||
width_in: float
|
||||
height_in: float
|
||||
depth_in: 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
|
||||
|
||||
@@ -42,7 +42,16 @@ class DiagnosticReport:
|
||||
|
||||
class ValidationEngine:
|
||||
@staticmethod
|
||||
def validate(room: RoomModel) -> DiagnosticReport:
|
||||
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
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
from core.units import Length
|
||||
import uuid
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
@@ -20,51 +21,52 @@ class Relationship(PersistentObject):
|
||||
}
|
||||
|
||||
class GeometryNode(PersistentObject):
|
||||
def __init__(self, node_type: str, width: float, height: float, depth: float, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
|
||||
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
|
||||
self.height = height
|
||||
self.depth = depth
|
||||
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, height: float, depth: float, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
|
||||
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, height: float, depth: float, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
|
||||
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, depth: float, overhang: Optional[float] = None, splash: Optional[bool] = None, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
|
||||
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
|
||||
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, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
|
||||
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, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
|
||||
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, depth: float, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
|
||||
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, metadata: Optional[Dict] = None, obj_id: Optional[str] = None):
|
||||
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, obj_id: Optional[str] = None):
|
||||
def __init__(self, name: str, length: float | Length, obj_id: Optional[str] = None):
|
||||
super().__init__(obj_id)
|
||||
self.name = name
|
||||
self.length = length
|
||||
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] = []
|
||||
@@ -73,12 +75,13 @@ class WallModel(PersistentObject):
|
||||
return {
|
||||
"id": self.id,
|
||||
"name": self.name,
|
||||
"length": self.length,
|
||||
"cabinets": [{"id": c.id, "type": c.node_type, "width": c.width, "height": c.height, "depth": c.depth, "metadata": c.metadata} for c in self.cabinets],
|
||||
"appliances": [{"id": a.id, "type": a.node_type, "width": a.width, "metadata": a.metadata} for a in self.appliances],
|
||||
"openings": [{"id": o.id, "type": o.node_type, "width": o.width, "metadata": o.metadata} for o in self.openings],
|
||||
"fixtures": [{"id": f.id, "type": f.node_type, "width": f.width, "metadata": f.metadata} for f in self.fixtures],
|
||||
"structural": [{"id": s.id, "type": s.node_type, "width": s.width, "depth": s.depth, "metadata": s.metadata} for s in self.structural],
|
||||
"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):
|
||||
@@ -90,13 +93,25 @@ class RoomModel(PersistentObject):
|
||||
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, "metadata": c.metadata} for c in self.clearances],
|
||||
"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]
|
||||
}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from typing import Dict, Any, List, Optional
|
||||
from .models import (
|
||||
ProjectModel, BuildingModel, FloorModel, UnitModel, KitchenModel, VanityModel,
|
||||
WallModel, OpeningNode, ApplianceNode, PlumbingFixtureNode, StructuralElementNode, ClearanceZoneNode, Relationship
|
||||
RoomModel, WallModel, OpeningNode, ApplianceNode, PlumbingFixtureNode, StructuralElementNode, ClearanceZoneNode, Relationship
|
||||
)
|
||||
|
||||
class GeometryParser:
|
||||
@@ -38,7 +38,7 @@ class ModelBuilder:
|
||||
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 = RoomModel(name="Bathroom", 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()
|
||||
|
||||
@@ -66,8 +66,9 @@ ROOM_WIDTH_TOLERANCE_IN = 2.0
|
||||
AUTO_APPROVE_CONFIDENCE = 0.90
|
||||
# Standard base cabinet height (non-ADA)
|
||||
BASE_CABINET_HEIGHT_STD_IN = 34.5
|
||||
# ADA base cabinet height (max 34" countertop)
|
||||
BASE_CABINET_HEIGHT_ADA_IN = 32.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 inches) ─────────────────────
|
||||
STANDARD_WIDTHS_IN = [
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
"""
|
||||
===========================================================================
|
||||
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, dict] = Field(default_factory=dict)
|
||||
|
||||
class Config:
|
||||
populate_by_name = True
|
||||
|
||||
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)
|
||||
@@ -23,35 +23,48 @@ class DrawingClassifier:
|
||||
"""
|
||||
|
||||
@staticmethod
|
||||
def classify_page(spans: list[TextSpan]) -> str:
|
||||
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)
|
||||
|
||||
# 1. RCP Check (Reflected Ceiling Plan)
|
||||
if "RCP" in text_content or "REFLECTED CEILING" in text_content:
|
||||
return "RCP"
|
||||
|
||||
# 2. Elevation Check
|
||||
if "ELEVATION" in text_content or "INT. ELEV" in text_content:
|
||||
return "ELEVATION"
|
||||
|
||||
# 3. Unit Plan Details Check
|
||||
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"
|
||||
|
||||
# 4. Overall Floor Plan Check
|
||||
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"
|
||||
|
||||
# 5. Section Check
|
||||
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"
|
||||
|
||||
# 6. Detail Check
|
||||
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
|
||||
return "UNIT PLAN" # Most details pages are unit plan/elevations
|
||||
|
||||
@@ -1,21 +1,190 @@
|
||||
"""
|
||||
===========================================================================
|
||||
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-inch turning radius and 30x48 clear floor spaces."""
|
||||
"""
|
||||
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 = []
|
||||
# Placeholder logic: scan bounding boxes for a 60" diameter circle
|
||||
|
||||
# Example validation:
|
||||
# if not has_60_inch_radius:
|
||||
# issues.append({"severity": "ERROR", "message": "Turning radius < 60 inches."})
|
||||
|
||||
|
||||
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 issues else "FAIL",
|
||||
"issues": issues
|
||||
"status": "PASS" if not any(i["severity"] == "ERROR" for i in issues) else "FAIL",
|
||||
"issues": issues,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
@@ -23,40 +192,81 @@ class ADAEngine:
|
||||
"""Validates that operable parts are within 15 to 48 inches AFF."""
|
||||
issues = []
|
||||
for cab in cabinets:
|
||||
if cab.get('family') == 'UPPER':
|
||||
# ADA Uppers often need to be mounted lower or have specialized pull-down hardware
|
||||
issues.append({"severity": "WARNING", "message": f"Upper cabinet {cab.get('id', '')} exceeds preferred ADA reach zone."})
|
||||
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
|
||||
"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 = []
|
||||
if sink_cabinet.get('render_style') != 'sink_base':
|
||||
issues.append({"severity": "ERROR", "message": "ADA Sink cabinet must be a compliant sink base with knee clearance."})
|
||||
# Ensure it has a removable front or knee clearance
|
||||
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
|
||||
"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):
|
||||
if not unit_data.get("is_ada", False):
|
||||
return {"status": "NOT_APPLICABLE"}
|
||||
|
||||
clearance_res = ADAEngine.validate_clearances(unit_data.get('geometry', {}))
|
||||
reach_res = ADAEngine.validate_reach_ranges(unit_data.get('cabinets', []))
|
||||
|
||||
# To get the sink cabinet, you'd find it in cabinets list. Assume empty for placeholder
|
||||
|
||||
all_issues = clearance_res['issues'] + reach_res['issues']
|
||||
|
||||
|
||||
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
|
||||
"status": "PASS" if not any(i["severity"] == "ERROR" for i in all_issues) else "FAIL",
|
||||
"issues": all_issues,
|
||||
}
|
||||
|
||||
@@ -163,6 +163,70 @@ class ApplianceDatabase:
|
||||
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"
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -1,35 +1,62 @@
|
||||
"""
|
||||
===========================================================================
|
||||
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 CAD blocks."""
|
||||
|
||||
"""Procedural generator for appliance and fixture CAD blocks."""
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────
|
||||
# KITCHEN APPLIANCES
|
||||
# ─────────────────────────────────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def draw_refrigerator_elevation(x0: float, y0: float, width: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
|
||||
"""Draws a refrigerator in elevation view."""
|
||||
geom = {"lines": [], "blocks": [], "texts": []}
|
||||
x1 = x0 + width * scale_x
|
||||
y1 = y0 + 72.0 * scale_y # Ref height is typically 72"
|
||||
|
||||
# Main body
|
||||
y1 = y0 + 72.0 * scale_y # Ref height typically 72"
|
||||
|
||||
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
|
||||
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"})
|
||||
geom["lines"].append({"start": [mid_x + 1.5, h_start_y], "end": [mid_x + 1.5, h_end_y], "layer": "HANDLES", "style": "solid"})
|
||||
|
||||
# Text
|
||||
|
||||
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "REF", "size": 4.5, "layer": "TEXT"})
|
||||
|
||||
return geom
|
||||
|
||||
@staticmethod
|
||||
@@ -37,18 +64,16 @@ class ApplianceLibrary:
|
||||
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"
|
||||
})
|
||||
|
||||
|
||||
# Control panel
|
||||
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 - 2.0 * scale_y], "text": "D/W\nS.S", "size": 4.5, "layer": "TEXT"})
|
||||
|
||||
return geom
|
||||
|
||||
@staticmethod
|
||||
@@ -56,7 +81,7 @@ class ApplianceLibrary:
|
||||
geom = {"lines": [], "blocks": [], "texts": []}
|
||||
x1 = x0 + width * scale_x
|
||||
y1_stove = y0 + 36.0 * scale_y
|
||||
|
||||
|
||||
# Main body
|
||||
geom["blocks"].append({
|
||||
"type": "rect",
|
||||
@@ -65,17 +90,17 @@ class ApplianceLibrary:
|
||||
})
|
||||
# Bottom warming drawer
|
||||
geom["lines"].append({"start": [x0, y0 + 8.0 * scale_y], "end": [x1, y0 + 8.0 * scale_y], "layer": "APPLIANCES", "style": "solid"})
|
||||
|
||||
|
||||
# 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"
|
||||
})
|
||||
|
||||
|
||||
# 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"})
|
||||
|
||||
|
||||
# Knobs
|
||||
for i in range(1, 5):
|
||||
kx = x0 + (width / 5.0 * i) * scale_x
|
||||
@@ -84,7 +109,7 @@ class ApplianceLibrary:
|
||||
"coords": [kx - 1.0, y1_stove - 3.0 * scale_y, 2.0, 2.0 * scale_y],
|
||||
"id": "", "layer": "APPLIANCES", "style": "solid"
|
||||
})
|
||||
|
||||
|
||||
return geom
|
||||
|
||||
@staticmethod
|
||||
@@ -92,7 +117,7 @@ class ApplianceLibrary:
|
||||
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],
|
||||
@@ -113,13 +138,54 @@ class ApplianceLibrary:
|
||||
})
|
||||
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 dashed sink bowl in elevation behind base cabinets."""
|
||||
"""Draws dashed kitchen sink bowl in elevation behind base cabinets."""
|
||||
geom = {"lines": [], "blocks": [], "texts": []}
|
||||
x1 = x0 + width * scale_x
|
||||
sink_d = 8.0 * scale_y
|
||||
|
||||
|
||||
geom["lines"].append({"start": [x0 + 3.0 * scale_x, y1], "end": [x0 + 3.0 * scale_x, y1 - sink_d], "layer": "SINK", "style": "dashed"})
|
||||
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"})
|
||||
geom["lines"].append({"start": [x1 - 3.0 * scale_x, y1 - sink_d], "end": [x1 - 3.0 * scale_x, y1], "layer": "SINK", "style": "dashed"})
|
||||
@@ -127,32 +193,29 @@ class ApplianceLibrary:
|
||||
|
||||
@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 sink symbol in floor plan."""
|
||||
"""Draws kitchen sink symbol in floor plan."""
|
||||
geom = {"lines": [], "blocks": [], "texts": []}
|
||||
x1 = x0 + width * scale_x
|
||||
|
||||
# Center of sink
|
||||
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 for now)
|
||||
|
||||
# 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
|
||||
@@ -161,23 +224,234 @@ class ApplianceLibrary:
|
||||
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
|
||||
margin_x = 4.0 * scale_x
|
||||
margin_y = 4.0 * scale_y
|
||||
spacing_x = (width * scale_x - 2*margin_x)
|
||||
spacing_y = (depth * scale_y - 2*margin_y)
|
||||
|
||||
for bx in [x0 + margin_x, x1 - margin_x]:
|
||||
for by in [y0 + margin_y, y1 - margin_y]:
|
||||
# Draw burner as a small box or cross
|
||||
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_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},
|
||||
}
|
||||
|
||||
@@ -42,7 +42,8 @@ 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"
|
||||
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 = ""
|
||||
@@ -60,7 +61,8 @@ class Anchor:
|
||||
@dataclass
|
||||
class ApplianceSlot:
|
||||
"""A fixed-width slot reserved for an appliance."""
|
||||
type: str # "REF", "RANGE", "DW", "MIC", "HOOD", "OVEN"
|
||||
type: str # Kitchen: "REF" | "RANGE" | "DW" | "MIC" | "HOOD" | "OVEN"
|
||||
# Bathroom: "MED_CAB" | "LINEN"
|
||||
x_start: float
|
||||
width: float
|
||||
notes: str = ""
|
||||
@@ -94,6 +96,14 @@ class WallConstraints:
|
||||
windows: List[Obstruction] = field(default_factory=list)
|
||||
is_ada: bool = False
|
||||
|
||||
# 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:
|
||||
"""
|
||||
@@ -117,13 +127,15 @@ class ConstraintExtractor:
|
||||
is_ada=is_ada,
|
||||
)
|
||||
|
||||
# Openings → Obstructions (Skip windows since base cabinets go under them)
|
||||
# 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,
|
||||
@@ -132,7 +144,17 @@ class ConstraintExtractor:
|
||||
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,
|
||||
@@ -153,14 +175,17 @@ class ConstraintExtractor:
|
||||
notes=notes,
|
||||
))
|
||||
|
||||
# Fixtures → Anchors (sink center, etc.)
|
||||
# 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=f"{f_type}_center",
|
||||
type=anchor_type,
|
||||
x_center=x_in,
|
||||
width=w_in,
|
||||
notes=notes,
|
||||
|
||||
@@ -38,6 +38,24 @@ 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:
|
||||
|
||||
@@ -35,6 +35,7 @@ from core.engines.constraint_solver import (
|
||||
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
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════
|
||||
@@ -46,9 +47,10 @@ 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 = 34.0 # inches (ADA max)
|
||||
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))
|
||||
@@ -82,6 +84,7 @@ class PlacedCabinet:
|
||||
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 = ""
|
||||
@@ -134,8 +137,10 @@ class PlacementEngine:
|
||||
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)
|
||||
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
|
||||
@@ -152,6 +157,15 @@ class PlacementEngine:
|
||||
|
||||
# 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(
|
||||
@@ -162,20 +176,20 @@ class PlacementEngine:
|
||||
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, notes="Over fridge (deep)"
|
||||
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, notes="Over range"
|
||||
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
|
||||
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, notes="Over sink"
|
||||
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:
|
||||
@@ -183,6 +197,7 @@ class PlacementEngine:
|
||||
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
|
||||
))
|
||||
@@ -190,7 +205,7 @@ class PlacementEngine:
|
||||
all_placed.extend(uppers)
|
||||
return all_placed
|
||||
|
||||
def _place_run(self, run: AvailableRun, is_ada: bool = False) -> List[PlacedCabinet]:
|
||||
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
|
||||
@@ -203,17 +218,68 @@ class PlacementEngine:
|
||||
return []
|
||||
|
||||
# Check for a sink anchor in this run
|
||||
sink_anchor = None
|
||||
for a in run.anchors:
|
||||
if "sink" in a.type.lower():
|
||||
sink_anchor = a
|
||||
break
|
||||
sink_anchors = [a for a in run.anchors if "sink" in a.type.lower()]
|
||||
|
||||
if sink_anchor and self.design.center_sink_on_anchor:
|
||||
return self._place_with_centered_sink(run, sink_anchor, is_ada)
|
||||
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,
|
||||
|
||||
@@ -88,7 +88,7 @@ class UnitMatrixBuilder:
|
||||
room = ManufacturingRulesEngine.apply_rules(room)
|
||||
|
||||
# 4. Validation & Review
|
||||
report = ValidationEngine.validate(room)
|
||||
report = ValidationEngine.validate_intent(room)
|
||||
if not ReviewEngine.review(report):
|
||||
continue # Skip invalid rooms
|
||||
|
||||
|
||||
@@ -1,74 +0,0 @@
|
||||
"""
|
||||
===========================================================================
|
||||
core/kitchen_layout_classifier.py — Kitchen Type Classifier
|
||||
===========================================================================
|
||||
Generates a layout signature for a kitchen and maps it to a canonical
|
||||
kitchen type (e.g., K1, K2).
|
||||
===========================================================================
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
class KitchenLayoutClassifier:
|
||||
"""
|
||||
Classifies kitchen layouts and maps them to K-types.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Maps signature -> type name (e.g., "K1")
|
||||
self.signature_to_type: dict[str, str] = {}
|
||||
self.type_counter = 0
|
||||
|
||||
def get_kitchen_type(self, walls: list[dict], appliances: list[dict], layout_shape: str) -> str:
|
||||
"""
|
||||
Generate a unique signature and return the K-type (e.g. "K1").
|
||||
"""
|
||||
# 1. Build appliance sequence
|
||||
# Group appliances and sink cabinets by wall and sort horizontally
|
||||
appliance_seqs = []
|
||||
for wall in walls:
|
||||
wall_name = wall["name"]
|
||||
wall_items = []
|
||||
|
||||
# Find appliances on this wall
|
||||
for app in appliances:
|
||||
if app["wall"] == wall_name:
|
||||
wall_items.append((app["x"], app["type"]))
|
||||
|
||||
# Find sink base or range cabinets on this wall from cabinets
|
||||
for cab in wall.get("cabinets", []):
|
||||
# Check if it has a sink/range keyword or ID mapping
|
||||
cid = cab.get("id", "").upper()
|
||||
c_type = cab.get("type", "").lower()
|
||||
# Some cabinets are mapped to keynotes representing sinks/ranges
|
||||
if "SINK" in c_type or cid in ("U9", "U2"): # U9/U2 are often sink/range in keynotes
|
||||
wall_items.append((cab["x"], "SINK"))
|
||||
|
||||
# Sort by x coordinate
|
||||
wall_items.sort(key=lambda item: item[0])
|
||||
seq = "-".join(item[1] for item in wall_items)
|
||||
if seq:
|
||||
appliance_seqs.append(f"Wall_{wall_name}:{seq}")
|
||||
|
||||
appliance_seq_str = "; ".join(appliance_seqs) if appliance_seqs else "NONE"
|
||||
|
||||
# 2. Wall lengths string
|
||||
lengths = []
|
||||
for wall in sorted(walls, key=lambda w: w["name"]):
|
||||
length_in = wall.get("length", 0)
|
||||
lengths.append(f"{wall['name']}:{length_in:.0f}\"")
|
||||
lengths_str = ", ".join(lengths)
|
||||
|
||||
# 3. Form final signature
|
||||
signature = f"{appliance_seq_str} | {layout_shape} | {lengths_str}"
|
||||
|
||||
# 4. Check/register signature
|
||||
if signature in self.signature_to_type:
|
||||
return self.signature_to_type[signature]
|
||||
else:
|
||||
self.type_counter += 1
|
||||
type_name = f"K{self.type_counter}"
|
||||
self.signature_to_type[signature] = type_name
|
||||
return type_name
|
||||
@@ -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
|
||||
@@ -2,55 +2,227 @@
|
||||
===========================================================================
|
||||
core/opening_extractor.py — Doors & Windows Extractor
|
||||
===========================================================================
|
||||
Locates structural openings like door passages and window sills.
|
||||
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, List, Dict, Any
|
||||
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 dimensions, wall positions, and alignment interruptions.
|
||||
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]) -> dict:
|
||||
def extract_openings(
|
||||
spans: list[TextSpan],
|
||||
rects: list[VectorRect],
|
||||
legend_map: dict[str, str] | None = None,
|
||||
page_scale: float = PDF_UNITS_PER_INCH,
|
||||
) -> dict:
|
||||
"""
|
||||
Parses text and geometry bounding boxes to identify doors and windows.
|
||||
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
|
||||
}
|
||||
"""
|
||||
doors = []
|
||||
windows = []
|
||||
legend_map = legend_map or {}
|
||||
doors: list[dict] = []
|
||||
windows: list[dict] = []
|
||||
review_flags: list[str] = []
|
||||
|
||||
# Parse text spans looking for window/door callouts (e.g. Window W1, W7, Door D1)
|
||||
text_content = " ".join(s.text.upper() for s in spans)
|
||||
|
||||
# Check window coordinates/dimensions if indicated
|
||||
# e.g., "WINDOW ABOVE SINK", "W7"
|
||||
w_matches = re.findall(r'\bW(\d+)\b', text_content)
|
||||
d_matches = re.findall(r'\bD(\d+)\b', text_content)
|
||||
# ── Step 1: Classify VectorRects by aspect ratio / size ──────────
|
||||
candidate_doors: list[VectorRect] = []
|
||||
candidate_windows: list[VectorRect] = []
|
||||
|
||||
# Standard window width is typically 36" wide, 48" high, 36" sill
|
||||
if "WINDOW" in text_content or w_matches:
|
||||
windows.append({
|
||||
"width_in": 36.0,
|
||||
"height_in": 48.0,
|
||||
"x_in": 60.0,
|
||||
"sill_height_in": 36.0,
|
||||
"notes": "Window found on wall"
|
||||
})
|
||||
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
|
||||
|
||||
if "DOOR" in text_content or d_matches:
|
||||
doors.append({
|
||||
"width_in": 36.0,
|
||||
"height_in": 80.0,
|
||||
"x_in": 120.0,
|
||||
"notes": "Door opening"
|
||||
"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
|
||||
"doors": doors,
|
||||
"windows": windows,
|
||||
"review_flags": review_flags,
|
||||
}
|
||||
|
||||
@@ -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),
|
||||
)
|
||||
|
||||
@@ -29,6 +29,7 @@ from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
from core.config import EUR_USD_RATE, CABINET_WIDTH_TOLERANCE_IN
|
||||
from core.units import Length
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════
|
||||
@@ -40,9 +41,9 @@ class PriceListEntry:
|
||||
"""One line item from the vendor price list."""
|
||||
description: str
|
||||
cabinet_type: str # mapped type: "base" | "upper_wall" | "pantry" | "vanity" | ...
|
||||
width_mm: float
|
||||
height_mm: float
|
||||
depth_mm: float
|
||||
width: Length
|
||||
height: Length
|
||||
depth: Length
|
||||
price_eur_tier1: float
|
||||
price_eur_tier2: Optional[float]
|
||||
price_eur_tier3: Optional[float]
|
||||
@@ -62,11 +63,11 @@ class MatchResult:
|
||||
"""Result of matching a cabinet to the price list."""
|
||||
cabinet_code: str
|
||||
cabinet_type: str
|
||||
width_mm: float
|
||||
width: Length
|
||||
matched_entry: Optional[PriceListEntry]
|
||||
price_usd: float
|
||||
price_eur: float
|
||||
match_delta_mm: float # how far the matched width is from requested
|
||||
match_delta_in: float # how far the matched width is from requested in inches
|
||||
match_quality: str # "EXACT" | "FUZZY" | "FALLBACK" | "NOT_FOUND"
|
||||
quantity: int = 1
|
||||
|
||||
@@ -171,14 +172,14 @@ class PriceMatcher:
|
||||
continue
|
||||
|
||||
# Map description to cabinet type
|
||||
cab_type = _infer_type_from_description(desc_str)
|
||||
mapped_type = _infer_type_from_description(desc_str)
|
||||
|
||||
entries.append(PriceListEntry(
|
||||
description = desc_str,
|
||||
cabinet_type = cab_type,
|
||||
width_mm = width_mm,
|
||||
height_mm = height_mm,
|
||||
depth_mm = depth_mm,
|
||||
cabinet_type = mapped_type,
|
||||
width = Length.from_mm(width_mm),
|
||||
height = Length.from_mm(height_mm),
|
||||
depth = Length.from_mm(depth_mm),
|
||||
price_eur_tier1 = price1,
|
||||
price_eur_tier2 = price2,
|
||||
price_eur_tier3 = price3,
|
||||
@@ -220,9 +221,6 @@ class PriceMatcher:
|
||||
tier = tier or self.tier
|
||||
kw_list = _map_type_to_price_category(cabinet_type)
|
||||
|
||||
width_mm = width_in * 25.4
|
||||
tolerance_mm = tolerance_in * 25.4
|
||||
|
||||
best_entry: Optional[PriceListEntry] = None
|
||||
best_delta: float = math.inf
|
||||
match_quality = "NOT_FOUND"
|
||||
@@ -234,58 +232,49 @@ class PriceMatcher:
|
||||
if not type_match:
|
||||
continue
|
||||
|
||||
delta = abs(entry.width_mm - width_mm)
|
||||
if delta <= 1.0: # exact
|
||||
delta = abs(entry.width.inches - width_in)
|
||||
if delta <= 1.0 / 25.4: # exact (1mm tolerance)
|
||||
best_entry = entry
|
||||
best_delta = delta
|
||||
match_quality = "EXACT"
|
||||
break
|
||||
elif delta <= tolerance_mm and delta < best_delta:
|
||||
elif delta <= tolerance_in and delta < best_delta:
|
||||
best_entry = entry
|
||||
best_delta = delta
|
||||
match_quality = "FUZZY"
|
||||
|
||||
# If no match, try broader search by width only
|
||||
if best_entry is None:
|
||||
for entry in self._entries:
|
||||
delta = abs(entry.width_mm - width_mm)
|
||||
if delta <= tolerance_mm * 1.5 and delta < best_delta:
|
||||
best_entry = entry
|
||||
best_delta = delta
|
||||
match_quality = "FALLBACK"
|
||||
|
||||
if best_entry is None:
|
||||
# Return zero price with NOT_FOUND flag
|
||||
# Fallback logic would typically go here
|
||||
return MatchResult(
|
||||
cabinet_code = f"{cabinet_type.upper()}-{width_mm:.0f}mm",
|
||||
cabinet_code = _generate_code(cabinet_type, width_in * 25.4),
|
||||
cabinet_type = cabinet_type,
|
||||
width_mm = width_mm,
|
||||
width = Length.from_inches(width_in),
|
||||
matched_entry = None,
|
||||
price_usd = 0.0,
|
||||
price_eur = 0.0,
|
||||
match_delta_mm = 0.0,
|
||||
match_delta_in = 0.0,
|
||||
match_quality = "NOT_FOUND",
|
||||
quantity = quantity,
|
||||
)
|
||||
|
||||
price_eur = best_entry.price_eur_tier1 # default
|
||||
eur = best_entry.price_eur_tier1
|
||||
if tier == 2 and best_entry.price_eur_tier2:
|
||||
price_eur = best_entry.price_eur_tier2
|
||||
eur = best_entry.price_eur_tier2
|
||||
elif tier == 3 and best_entry.price_eur_tier3:
|
||||
price_eur = best_entry.price_eur_tier3
|
||||
|
||||
price_usd = (price_eur or 0.0) * self.eur_usd
|
||||
eur = best_entry.price_eur_tier3
|
||||
|
||||
usd = (eur or 0.0) * self.eur_usd
|
||||
|
||||
return MatchResult(
|
||||
cabinet_code = _generate_code(cabinet_type, width_mm),
|
||||
cabinet_type = cabinet_type,
|
||||
width_mm = width_mm,
|
||||
matched_entry = best_entry,
|
||||
price_usd = price_usd,
|
||||
price_eur = price_eur or 0.0,
|
||||
match_delta_mm = best_delta,
|
||||
match_quality = match_quality,
|
||||
quantity = quantity,
|
||||
cabinet_code = _generate_code(cabinet_type, best_entry.width.mm),
|
||||
cabinet_type = cabinet_type,
|
||||
width = Length.from_inches(width_in),
|
||||
matched_entry = best_entry,
|
||||
price_usd = usd,
|
||||
price_eur = eur,
|
||||
match_delta_in = best_delta,
|
||||
match_quality = match_quality,
|
||||
quantity = quantity,
|
||||
)
|
||||
|
||||
def price_schedule(
|
||||
@@ -324,7 +313,7 @@ class PriceMatcher:
|
||||
if r.match_quality == "NOT_FOUND":
|
||||
not_found += 1
|
||||
line = (f" {r.cabinet_code:25s} {r.cabinet_type:20s} "
|
||||
f"{r.width_mm:8.0f} {r.quantity:5d} "
|
||||
f"{r.width.mm:8.0f} {r.quantity:5d} "
|
||||
f"${r.price_usd:9.2f} ${r.total_usd:11.2f} [{status}]")
|
||||
print(line)
|
||||
total += r.total_usd
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
from dataclasses import dataclass
|
||||
import math
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Length:
|
||||
inches: float
|
||||
|
||||
@staticmethod
|
||||
def from_mm(mm: float) -> "Length":
|
||||
return Length(inches=mm / 25.4)
|
||||
|
||||
@staticmethod
|
||||
def from_cm(cm: float) -> "Length":
|
||||
return Length(inches=cm / 2.54)
|
||||
|
||||
@staticmethod
|
||||
def from_inches(inches: float) -> "Length":
|
||||
return Length(inches=inches)
|
||||
|
||||
@property
|
||||
def mm(self) -> float:
|
||||
return self.inches * 25.4
|
||||
|
||||
@property
|
||||
def cm(self) -> float:
|
||||
return self.inches * 2.54
|
||||
|
||||
def __add__(self, other):
|
||||
if isinstance(other, Length):
|
||||
return Length(inches=self.inches + other.inches)
|
||||
if isinstance(other, (int, float)):
|
||||
return Length(inches=self.inches + other)
|
||||
return NotImplemented
|
||||
|
||||
def __sub__(self, other):
|
||||
if isinstance(other, Length):
|
||||
return Length(inches=self.inches - other.inches)
|
||||
if isinstance(other, (int, float)):
|
||||
return Length(inches=self.inches - other)
|
||||
return NotImplemented
|
||||
|
||||
def __mul__(self, scalar):
|
||||
return Length(inches=self.inches * scalar)
|
||||
|
||||
def __rmul__(self, scalar):
|
||||
return self.__mul__(scalar)
|
||||
|
||||
def __eq__(self, other):
|
||||
if isinstance(other, Length):
|
||||
return math.isclose(self.inches, other.inches, abs_tol=1e-5)
|
||||
return False
|
||||
|
||||
def __lt__(self, other):
|
||||
if isinstance(other, Length):
|
||||
return self.inches < other.inches
|
||||
return NotImplemented
|
||||
|
||||
def __le__(self, other):
|
||||
if isinstance(other, Length):
|
||||
return self.inches <= other.inches
|
||||
return NotImplemented
|
||||
|
||||
def __float__(self):
|
||||
return float(self.inches)
|
||||
|
||||
def __round__(self, ndigits=None):
|
||||
return round(self.inches, ndigits)
|
||||
|
||||
def __repr__(self):
|
||||
return f"Length({self.inches:.2f}\")"
|
||||
@@ -1,60 +0,0 @@
|
||||
"""
|
||||
===========================================================================
|
||||
core/vanity_layout_classifier.py — Vanity Type Classifier
|
||||
===========================================================================
|
||||
Generates a layout signature for a bathroom vanity and maps it to a
|
||||
canonical bathroom type (e.g., V1, V2).
|
||||
===========================================================================
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
class VanityLayoutClassifier:
|
||||
"""
|
||||
Classifies vanity layouts and maps them to V-types.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
# Maps signature -> type name (e.g., "V1")
|
||||
self.signature_to_type: dict[str, str] = {}
|
||||
self.type_counter = 0
|
||||
|
||||
def get_vanity_type(self, cabinets: list[dict], room_width_mm: float = 0.0) -> str:
|
||||
"""
|
||||
Generate a unique signature and return the V-type (e.g. "V1").
|
||||
"""
|
||||
# Find vanity cabinets and sum their widths
|
||||
vanity_cabs = [
|
||||
c for c in cabinets
|
||||
if c.get("type") == "vanity" or "vanity" in c.get("type", "").lower()
|
||||
]
|
||||
|
||||
vanity_width_in = 0.0
|
||||
num_sinks = 0
|
||||
is_ada = False
|
||||
|
||||
for vc in vanity_cabs:
|
||||
w_in = vc.get("width_mm", vc.get("width", 0) * 25.4) / 25.4
|
||||
vanity_width_in += w_in
|
||||
if vc.get("is_ada"):
|
||||
is_ada = True
|
||||
# Double vanity check from keynote or notes
|
||||
if "double" in vc.get("notes", "").lower() or "double" in vc.get("location", "").lower():
|
||||
num_sinks = 2
|
||||
|
||||
if not vanity_cabs:
|
||||
# Fallback if no explicit vanity cabinets are detected
|
||||
signature = "NO_VANITY"
|
||||
else:
|
||||
if num_sinks == 0:
|
||||
num_sinks = 2 if vanity_width_in >= 48 else 1
|
||||
ada_str = "ADA" if is_ada else "STD"
|
||||
signature = f"VANITY | {vanity_width_in:.0f}\" | {num_sinks}SINK | {ada_str}"
|
||||
|
||||
if signature in self.signature_to_type:
|
||||
return self.signature_to_type[signature]
|
||||
else:
|
||||
self.type_counter += 1
|
||||
type_name = f"V{self.type_counter}"
|
||||
self.signature_to_type[signature] = type_name
|
||||
return type_name
|
||||
@@ -0,0 +1,404 @@
|
||||
"""
|
||||
===========================================================================
|
||||
core/yolo_extractor.py — YOLO-based Architectural Element Detector
|
||||
===========================================================================
|
||||
Drop-in augmentation for the extraction pipeline.
|
||||
Runs after PyMuPDF page render, before ConstraintExtractor.
|
||||
|
||||
Outputs the same dict shape that OpeningExtractor and RegionDetector
|
||||
produce today, so downstream code needs zero changes when YOLO is absent.
|
||||
|
||||
Pixel → inch conversion (two-step):
|
||||
Step 1 (pixels → PDF points): pt = px / (dpi / 72.0)
|
||||
i.e. pt = px * 72 / dpi
|
||||
Step 2 (PDF points → real-world inches): in = pt / 72.0
|
||||
Combined: in = px / dpi
|
||||
(At 1:1 drawing scale. Elevation views need an additional
|
||||
architectural-scale multiplier — see detect_elevation().)
|
||||
|
||||
IMPORTANT: models are lazy-loaded. If the .pt file is absent the module
|
||||
silently returns {"yolo_used": False} so the pipeline falls back to its
|
||||
existing heuristic extractor without crashing.
|
||||
===========================================================================
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
try:
|
||||
from ultralytics import YOLO as _YOLO
|
||||
_YOLO_AVAILABLE = True
|
||||
except ImportError:
|
||||
_YOLO_AVAILABLE = False
|
||||
|
||||
try:
|
||||
import numpy as np
|
||||
_NUMPY_AVAILABLE = True
|
||||
except ImportError:
|
||||
_NUMPY_AVAILABLE = False
|
||||
|
||||
|
||||
# Model weight paths — relative to project root.
|
||||
# Set these to wherever you place the trained best.pt files.
|
||||
FLOOR_PLAN_MODEL_PATH = Path("models/yolo_floor_plan/weights/best.pt")
|
||||
ELEVATION_MODEL_PATH = Path("models/yolo_elevation/weights/best.pt")
|
||||
|
||||
# Detection confidence threshold.
|
||||
# Lower than typical (0.5) because we always cross-check with PyMuPDF text.
|
||||
DETECTION_CONF = 0.40
|
||||
|
||||
# ── YOLO class names for each model ──────────────────────────────────────
|
||||
|
||||
# Floor plan model classes (must match data.yaml used during training)
|
||||
FLOOR_PLAN_CLASSES = [
|
||||
"kitchen_region", # 0
|
||||
"bath_region", # 1
|
||||
"sink_symbol", # 2 kitchen sink
|
||||
"range_symbol", # 3 stove/cooktop
|
||||
"dw_symbol", # 4 dishwasher
|
||||
"fridge_symbol", # 5 refrigerator
|
||||
"oven_symbol", # 6 wall oven
|
||||
"microwave_symbol", # 7
|
||||
"hood_symbol", # 8
|
||||
"pantry_symbol", # 9
|
||||
"vanity_sink_symbol", # 10 bathroom vanity sink
|
||||
"toilet_symbol", # 11
|
||||
"bathtub_symbol", # 12
|
||||
"shower_symbol", # 13
|
||||
"shower_door_symbol", # 14
|
||||
"medicine_cabinet_symbol", # 15
|
||||
"linen_closet_symbol", # 16
|
||||
"bidet_symbol", # 17
|
||||
"door_swing", # 18
|
||||
"window_symbol", # 19
|
||||
"structural_column", # 20
|
||||
"soffit_hatch", # 21
|
||||
]
|
||||
|
||||
# Elevation model classes
|
||||
ELEVATION_CLASSES = [
|
||||
"wall_span", # 0
|
||||
"door_opening", # 1
|
||||
"window_opening", # 2
|
||||
"soffit_line", # 3
|
||||
"countertop_line", # 4
|
||||
"appliance_outline", # 5
|
||||
]
|
||||
|
||||
|
||||
@dataclass
|
||||
class YOLODetection:
|
||||
"""One detected element from YOLO inference."""
|
||||
class_name: str
|
||||
bbox_px: tuple[float, float, float, float] # (x0, y0, x1, y1) in pixels
|
||||
confidence: float
|
||||
x_in: float = 0.0 # left edge in real-world inches from page origin
|
||||
width_in: float = 0.0 # real-world width in inches
|
||||
height_in: float = 0.0 # real-world height in inches
|
||||
|
||||
|
||||
class YOLOExtractor:
|
||||
"""
|
||||
Runs YOLO inference on a rendered page image and converts detections
|
||||
to the architectural parameter dict shape the pipeline expects.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
self._floor_model: Optional[object] = None
|
||||
self._elev_model: Optional[object] = None
|
||||
|
||||
# ── Private helpers ───────────────────────────────────────────────────
|
||||
|
||||
def _load_model(self, path: Path, slot_name: str):
|
||||
if not _YOLO_AVAILABLE:
|
||||
return None
|
||||
if not path.exists():
|
||||
return None
|
||||
current = getattr(self, slot_name)
|
||||
if current is None:
|
||||
setattr(self, slot_name, _YOLO(str(path)))
|
||||
return getattr(self, slot_name)
|
||||
|
||||
@staticmethod
|
||||
def _px_to_inches_flat(px: float, dpi: float) -> float:
|
||||
"""
|
||||
Convert a pixel measurement to real-world inches at 1:1 scale.
|
||||
Pixel → PDF points: pt = px * 72 / dpi
|
||||
PDF points → inches: in_ = pt / 72
|
||||
Combined: in_ = px / dpi
|
||||
|
||||
This is correct for floor plan renders where the page fills the
|
||||
rendered image at the given DPI.
|
||||
"""
|
||||
return px / dpi
|
||||
|
||||
@staticmethod
|
||||
def _px_to_inches_elevation(
|
||||
px: float,
|
||||
dpi: float,
|
||||
arch_scale_in_per_pt: float,
|
||||
) -> float:
|
||||
"""
|
||||
Convert a pixel measurement to real-world inches in an elevation crop.
|
||||
|
||||
arch_scale_in_per_pt is the architectural drawing scale expressed as
|
||||
(real-world inches) / (PDF point), e.g.:
|
||||
1/2" = 1'-0" → 1 paper-inch = 24 real-world inches
|
||||
→ 24 real-world in / 72 PDF pts = 0.333 in/pt
|
||||
1/4" = 1'-0" → 1 paper-inch = 48 real-world inches
|
||||
→ 48 / 72 = 0.667 in/pt
|
||||
|
||||
This value must be parsed from the drawing's "SCALE" annotation text
|
||||
(which pipeline already extracts in DimensionParser) — do NOT hardcode it.
|
||||
|
||||
Two-step conversion:
|
||||
Step 1: pixels → PDF points: pt = px * 72 / dpi
|
||||
Step 2: PDF points → real-world inches: in_ = pt * arch_scale_in_per_pt
|
||||
Combined: in_ = (px / dpi) * arch_scale_in_per_pt * 72
|
||||
"""
|
||||
pt = px * 72.0 / dpi # pixels → PDF points
|
||||
return pt * arch_scale_in_per_pt # PDF points → real-world inches
|
||||
|
||||
# ── Public API ────────────────────────────────────────────────────────
|
||||
|
||||
def detect_floor_plan(
|
||||
self,
|
||||
page_image_bytes: bytes,
|
||||
dpi: float,
|
||||
) -> dict:
|
||||
"""
|
||||
Detect kitchen/bath room regions and all fixture symbols from a floor plan image.
|
||||
|
||||
Returns a dict compatible with the existing pipeline:
|
||||
{
|
||||
"kitchen_regions": [YOLODetection, ...],
|
||||
"bath_regions": [YOLODetection, ...],
|
||||
"appliances": [{"type": "RANGE"|"REF"|"SINK"|"DW"|"OVEN"|"MIC",
|
||||
"x_in": float, "width_in": float, "confidence": float}],
|
||||
"fixtures": [{"type": "TOILET"|"BATHTUB"|"SHOWER"|"VANITY_SINK"|"BIDET",
|
||||
"x_in": float, "width_in": float, "confidence": float}],
|
||||
"doors": [{"x_in": float, "width_in": float, "height_in": 80.0, "notes": str}],
|
||||
"windows": [{"x_in": float, "width_in": float, "sill_height_in": 36.0, "notes": str}],
|
||||
"columns": [{"x_in": float, "width_in": float, "notes": str}],
|
||||
"yolo_used": True | False
|
||||
}
|
||||
"""
|
||||
model = self._load_model(FLOOR_PLAN_MODEL_PATH, "_floor_model")
|
||||
if model is None:
|
||||
return {"yolo_used": False}
|
||||
|
||||
img = _bytes_to_array(page_image_bytes)
|
||||
results = model(img, conf=DETECTION_CONF, verbose=False)[0]
|
||||
|
||||
KITCHEN_APPLIANCE_MAP = {
|
||||
"sink_symbol": "SINK",
|
||||
"range_symbol": "RANGE",
|
||||
"dw_symbol": "DW",
|
||||
"fridge_symbol": "REF",
|
||||
"oven_symbol": "OVEN",
|
||||
"microwave_symbol": "MIC",
|
||||
}
|
||||
BATH_FIXTURE_MAP = {
|
||||
"vanity_sink_symbol": "VANITY_SINK",
|
||||
"toilet_symbol": "TOILET",
|
||||
"bathtub_symbol": "BATHTUB",
|
||||
"shower_symbol": "SHOWER",
|
||||
"bidet_symbol": "BIDET",
|
||||
"medicine_cabinet_symbol": "MED_CAB",
|
||||
"linen_closet_symbol": "LINEN",
|
||||
}
|
||||
|
||||
out: dict = {
|
||||
"kitchen_regions": [], "bath_regions": [],
|
||||
"appliances": [], "fixtures": [],
|
||||
"doors": [], "windows": [], "columns": [],
|
||||
"yolo_used": True,
|
||||
}
|
||||
|
||||
for box in results.boxes:
|
||||
cls = results.names[int(box.cls)]
|
||||
conf = float(box.conf)
|
||||
x0, y0, x1, y1 = (float(v) for v in box.xyxy[0])
|
||||
w_px = x1 - x0
|
||||
h_px = y1 - y0
|
||||
|
||||
# Correct pixel → inch conversion (flat 1:1 floor plan scale)
|
||||
x_in = self._px_to_inches_flat(x0, dpi)
|
||||
width_in = self._px_to_inches_flat(w_px, dpi)
|
||||
height_in= self._px_to_inches_flat(h_px, dpi)
|
||||
|
||||
det = YOLODetection(
|
||||
class_name=cls,
|
||||
bbox_px=(x0, y0, x1, y1),
|
||||
confidence=conf,
|
||||
x_in=x_in,
|
||||
width_in=width_in,
|
||||
height_in=height_in,
|
||||
)
|
||||
|
||||
if cls == "kitchen_region":
|
||||
out["kitchen_regions"].append(det)
|
||||
elif cls == "bath_region":
|
||||
out["bath_regions"].append(det)
|
||||
elif cls in KITCHEN_APPLIANCE_MAP:
|
||||
out["appliances"].append({
|
||||
"type": KITCHEN_APPLIANCE_MAP[cls],
|
||||
"x_in": x_in,
|
||||
"width_in": width_in,
|
||||
"confidence": conf,
|
||||
"notes": f"YOLO {cls} conf={conf:.2f}",
|
||||
})
|
||||
elif cls in BATH_FIXTURE_MAP:
|
||||
out["fixtures"].append({
|
||||
"type": BATH_FIXTURE_MAP[cls],
|
||||
"x_in": x_in,
|
||||
"width_in": width_in,
|
||||
"height_in": height_in,
|
||||
"confidence": conf,
|
||||
"notes": f"YOLO {cls} conf={conf:.2f}",
|
||||
})
|
||||
elif cls == "door_swing":
|
||||
out["doors"].append({
|
||||
"type": "door",
|
||||
"width_in": width_in,
|
||||
"x_in": x_in,
|
||||
"height_in": 80.0,
|
||||
"notes": f"YOLO door swing conf={conf:.2f}",
|
||||
})
|
||||
elif cls == "window_symbol":
|
||||
out["windows"].append({
|
||||
"type": "window",
|
||||
"width_in": width_in,
|
||||
"x_in": x_in,
|
||||
"sill_height_in": 36.0,
|
||||
"height_in": 48.0,
|
||||
"notes": f"YOLO window conf={conf:.2f}",
|
||||
})
|
||||
elif cls == "structural_column":
|
||||
out["columns"].append({
|
||||
"type": "column",
|
||||
"width_in": width_in,
|
||||
"x_in": x_in,
|
||||
"notes": f"YOLO column conf={conf:.2f}",
|
||||
})
|
||||
|
||||
return out
|
||||
|
||||
def detect_elevation(
|
||||
self,
|
||||
elevation_image_bytes: bytes,
|
||||
dpi: float,
|
||||
arch_scale_in_per_pt: float,
|
||||
) -> dict:
|
||||
"""
|
||||
Detect wall spans, openings, and appliances from an elevation crop.
|
||||
|
||||
arch_scale_in_per_pt — MUST be derived from the "SCALE" annotation
|
||||
already parsed from the drawing. Common values:
|
||||
1/2"=1'-0" → 24 in / 72 pt = 0.333
|
||||
1/4"=1'-0" → 48 in / 72 pt = 0.667
|
||||
3/8"=1'-0" → 32 in / 72 pt = 0.444
|
||||
|
||||
Casa Familia elevations are confirmed 1/2"=1'-0" → use 0.333.
|
||||
Heritage elevations: verify from "SCALE" text before setting.
|
||||
|
||||
Returns:
|
||||
{
|
||||
"wall_length_in": float | None,
|
||||
"doors": [...],
|
||||
"windows": [...],
|
||||
"soffit_height_in": float | None,
|
||||
"yolo_used": True | False,
|
||||
}
|
||||
"""
|
||||
model = self._load_model(ELEVATION_MODEL_PATH, "_elev_model")
|
||||
if model is None:
|
||||
return {"yolo_used": False}
|
||||
|
||||
img = _bytes_to_array(elevation_image_bytes)
|
||||
results = model(img, conf=DETECTION_CONF, verbose=False)[0]
|
||||
|
||||
out: dict = {
|
||||
"wall_length_in": None,
|
||||
"doors": [], "windows": [],
|
||||
"soffit_height_in": None,
|
||||
"yolo_used": True,
|
||||
}
|
||||
|
||||
for box in results.boxes:
|
||||
cls = results.names[int(box.cls)]
|
||||
conf = float(box.conf)
|
||||
x0, y0, x1, y1 = (float(v) for v in box.xyxy[0])
|
||||
w_px = x1 - x0
|
||||
h_px = y1 - y0
|
||||
|
||||
# Correct pixel → real-world-inch conversion for elevation drawings
|
||||
width_in = self._px_to_inches_elevation(w_px, dpi, arch_scale_in_per_pt)
|
||||
height_in = self._px_to_inches_elevation(h_px, dpi, arch_scale_in_per_pt)
|
||||
x_in = self._px_to_inches_elevation(x0, dpi, arch_scale_in_per_pt)
|
||||
|
||||
if cls == "wall_span":
|
||||
out["wall_length_in"] = width_in
|
||||
elif cls == "door_opening":
|
||||
out["doors"].append({
|
||||
"type": "door", "width_in": width_in,
|
||||
"x_in": x_in, "height_in": height_in,
|
||||
"notes": f"YOLO door conf={conf:.2f}",
|
||||
})
|
||||
elif cls == "window_opening":
|
||||
out["windows"].append({
|
||||
"type": "window", "width_in": width_in,
|
||||
"x_in": x_in, "sill_height_in": 36.0, "height_in": height_in,
|
||||
"notes": f"YOLO window conf={conf:.2f}",
|
||||
})
|
||||
elif cls == "soffit_line":
|
||||
out["soffit_height_in"] = height_in
|
||||
|
||||
return out
|
||||
|
||||
|
||||
# ── Module-level helpers ──────────────────────────────────────────────────
|
||||
|
||||
def _bytes_to_array(image_bytes: bytes):
|
||||
"""Decode PNG bytes to a numpy array for YOLO inference."""
|
||||
if not _NUMPY_AVAILABLE:
|
||||
raise ImportError("numpy is required for YOLO inference: pip install numpy")
|
||||
import io
|
||||
from PIL import Image
|
||||
img = Image.open(io.BytesIO(image_bytes)).convert("RGB")
|
||||
return np.array(img)
|
||||
|
||||
|
||||
def arch_scale_from_text(scale_text: str) -> float:
|
||||
"""
|
||||
Parse an architectural scale annotation string to arch_scale_in_per_pt.
|
||||
|
||||
Examples:
|
||||
'1/2"=1\'-0"' → 0.333 (24 real-world in / 72 PDF pts)
|
||||
'1/4"=1\'-0"' → 0.667 (48 / 72)
|
||||
'3/8"=1\'-0"' → 0.444 (32 / 72)
|
||||
'1"=1\'-0"' → 0.167 (12 / 72)
|
||||
'3/4"=1\'-0"' → 0.222 (16 / 72)
|
||||
'1 1/2"=1\'-0"' → 0.111 (8 / 72)
|
||||
|
||||
Returns 0.333 (1/2"=1'-0") as the default if parsing fails.
|
||||
"""
|
||||
import re, fractions
|
||||
# Try to parse N/D"=1'-0" or N"=1'-0"
|
||||
m = re.search(r'(\d+(?:/\d+)?)\s*"?\s*=\s*1\'-?0"', scale_text, re.IGNORECASE)
|
||||
if not m:
|
||||
return 0.333 # default: 1/2"=1'-0" (most common for residential elevations)
|
||||
paper_in_str = m.group(1)
|
||||
try:
|
||||
paper_in = float(fractions.Fraction(paper_in_str))
|
||||
except Exception:
|
||||
return 0.333
|
||||
|
||||
# N paper-inches = 1 real foot = 12 real inches
|
||||
# real_in_per_paper_in = 12 / paper_in
|
||||
# 1 paper-inch = 72 PDF points
|
||||
# arch_scale_in_per_pt = real_in_per_paper_in / 72
|
||||
real_in_per_paper_in = 12.0 / paper_in
|
||||
return real_in_per_paper_in / 72.0
|
||||
@@ -0,0 +1,27 @@
|
||||
path: C:/Users/abhil/Desktop/Cabinetries/Cabinets/Albert_Project/datasets/floor_plan_annotated
|
||||
train: images
|
||||
val: images
|
||||
|
||||
names:
|
||||
0: kitchen_region
|
||||
1: bath_region
|
||||
2: sink_symbol
|
||||
3: range_symbol
|
||||
4: dw_symbol
|
||||
5: fridge_symbol
|
||||
6: oven_symbol
|
||||
7: microwave_symbol
|
||||
8: hood_symbol
|
||||
9: pantry_symbol
|
||||
10: vanity_sink_symbol
|
||||
11: toilet_symbol
|
||||
12: bathtub_symbol
|
||||
13: shower_symbol
|
||||
14: shower_door_symbol
|
||||
15: medicine_cabinet_symbol
|
||||
16: linen_closet_symbol
|
||||
17: bidet_symbol
|
||||
18: door_swing
|
||||
19: window_symbol
|
||||
20: structural_column
|
||||
21: soffit_hatch
|
||||
@@ -0,0 +1,22 @@
|
||||
kitchen_region
|
||||
bath_region
|
||||
sink_symbol
|
||||
range_symbol
|
||||
dw_symbol
|
||||
fridge_symbol
|
||||
oven_symbol
|
||||
microwave_symbol
|
||||
hood_symbol
|
||||
pantry_symbol
|
||||
vanity_sink_symbol
|
||||
toilet_symbol
|
||||
bathtub_symbol
|
||||
shower_symbol
|
||||
shower_door_symbol
|
||||
medicine_cabinet_symbol
|
||||
linen_closet_symbol
|
||||
bidet_symbol
|
||||
door_swing
|
||||
window_symbol
|
||||
structural_column
|
||||
soffit_hatch
|
||||
|
After Width: | Height: | Size: 2.8 MiB |
|
After Width: | Height: | Size: 3.4 MiB |
|
After Width: | Height: | Size: 4.3 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 3.5 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 3.4 MiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 3.4 MiB |
|
After Width: | Height: | Size: 2.9 MiB |
|
After Width: | Height: | Size: 2.8 MiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 3.9 MiB |
|
After Width: | Height: | Size: 2.8 MiB |
|
After Width: | Height: | Size: 1.2 MiB |
|
After Width: | Height: | Size: 1.1 MiB |
|
After Width: | Height: | Size: 2.7 MiB |
|
After Width: | Height: | Size: 2.6 MiB |
|
After Width: | Height: | Size: 2.6 MiB |
@@ -0,0 +1 @@
|
||||
0 0.610887 0.749086 0.615139 0.490254
|
||||
@@ -0,0 +1,3 @@
|
||||
1 0.709838 0.564676 0.139244 0.859074
|
||||
0 0.845100 0.732697 0.146713 0.399977
|
||||
0 0.845100 0.948982 0.146713 0.090463
|
||||
@@ -0,0 +1,2 @@
|
||||
1 0.669524 0.765500 0.231481 0.268519
|
||||
0 0.475522 0.797213 0.886310 0.038537
|
||||
@@ -0,0 +1,3 @@
|
||||
1 0.709838 0.564676 0.139244 0.859074
|
||||
0 0.845100 0.732697 0.146713 0.399977
|
||||
0 0.845100 0.948982 0.146713 0.090463
|
||||
@@ -0,0 +1,2 @@
|
||||
1 0.416865 0.511435 0.107725 0.967870
|
||||
0 0.674722 1.149565 0.231481 -0.299130
|
||||
@@ -0,0 +1,3 @@
|
||||
1 0.709838 0.564676 0.139244 0.859074
|
||||
0 0.845100 0.732697 0.146713 0.399977
|
||||
0 0.845100 0.948982 0.146713 0.090463
|
||||
@@ -0,0 +1,2 @@
|
||||
1 0.416647 0.511435 0.108161 0.967870
|
||||
0 0.674722 1.149565 0.231481 -0.299130
|
||||
@@ -0,0 +1,3 @@
|
||||
1 0.714189 0.564676 0.139244 0.859074
|
||||
0 0.847276 0.732697 0.142362 0.399977
|
||||
0 0.847276 0.948982 0.142362 0.090463
|
||||
@@ -0,0 +1,3 @@
|
||||
1 0.715926 0.564676 0.139290 0.859074
|
||||
0 0.848156 0.732697 0.140602 0.399977
|
||||
0 0.848156 0.948982 0.140602 0.090463
|
||||
@@ -0,0 +1,3 @@
|
||||
1 0.715486 0.564676 0.139244 0.859074
|
||||
0 0.847924 0.732697 0.141065 0.399977
|
||||
0 0.847924 0.948982 0.141065 0.090463
|
||||
@@ -0,0 +1,4 @@
|
||||
1 0.771389 0.291389 0.270062 0.335648
|
||||
0 0.628426 0.693808 0.302068 0.600810
|
||||
0 0.843171 0.688959 0.150571 0.335648
|
||||
0 0.843171 0.946088 0.150571 0.107824
|
||||
@@ -0,0 +1,5 @@
|
||||
1 0.840602 0.364306 0.155710 0.335648
|
||||
1 0.844074 0.582778 0.148765 0.335648
|
||||
0 0.729305 0.594514 0.270062 0.335648
|
||||
1 0.209165 0.648252 0.356971 0.258171
|
||||
1 0.649196 0.889016 0.538523 0.210393
|
||||
@@ -0,0 +1 @@
|
||||
1 0.253750 0.850961 0.370308 0.286505
|
||||
@@ -0,0 +1 @@
|
||||
1 0.720957 0.762454 0.373148 0.463518
|
||||
@@ -0,0 +1,2 @@
|
||||
0 0.822315 0.410695 0.192283 0.335648
|
||||
1 0.845509 0.867407 0.145895 0.265185
|
||||
@@ -0,0 +1,2 @@
|
||||
0 0.822246 0.408750 0.192422 0.335648
|
||||
1 0.845440 0.866435 0.146034 0.267130
|
||||
@@ -0,0 +1,3 @@
|
||||
0 0.812940 0.290209 0.211034 0.335648
|
||||
0 0.812940 0.760208 0.211034 0.335648
|
||||
0 0.625509 0.772986 0.270062 0.335648
|
||||
@@ -0,0 +1,50 @@
|
||||
import os
|
||||
|
||||
# Fix test_core.py
|
||||
core_path = "tests/test_core.py"
|
||||
if os.path.exists(core_path):
|
||||
with open(core_path, "r", encoding="utf-8") as f:
|
||||
lines = f.readlines()
|
||||
|
||||
new_lines = [
|
||||
"def test_all_legacy():\n",
|
||||
" all_ok = True\n",
|
||||
" def check(name, condition, info=\"\"):\n",
|
||||
" nonlocal all_ok\n",
|
||||
" status = \"[PASS]\" if condition else \"[FAIL]\"\n",
|
||||
" print(f\" {status} {name} {info}\")\n",
|
||||
" if not condition:\n",
|
||||
" all_ok = False\n\n"
|
||||
]
|
||||
|
||||
skip = False
|
||||
for line in lines:
|
||||
if line.startswith("def check"):
|
||||
skip = True
|
||||
elif skip and not line.startswith(" ") and line.strip() != "":
|
||||
skip = False
|
||||
|
||||
if line.startswith("all_ok ="):
|
||||
continue
|
||||
|
||||
if not skip:
|
||||
if "sys.exit" in line or "test_all_core_functions()" in line or "if __name__" in line or "assert all_ok" in line:
|
||||
continue
|
||||
new_lines.append(" " + line)
|
||||
|
||||
new_lines.append(" assert all_ok, \"Some core tests failed\"\n")
|
||||
|
||||
with open(core_path, "w", encoding="utf-8") as f:
|
||||
f.writelines(new_lines)
|
||||
|
||||
# Fix test_placement.py
|
||||
place_path = "tests/test_placement.py"
|
||||
if os.path.exists(place_path):
|
||||
with open(place_path, "r", encoding="utf-8") as f:
|
||||
content = f.read()
|
||||
|
||||
content = content.replace("sys.exit(1)", "assert False, 'Some tests failed'")
|
||||
with open(place_path, "w", encoding="utf-8") as f:
|
||||
f.write(content)
|
||||
|
||||
print("Fixed tests.")
|
||||
@@ -344,6 +344,49 @@ def _build_job_costing(ws, config: dict, jc: JobCostingResult, st: dict):
|
||||
# SHOP DRAWING SCHEDULE SHEETS
|
||||
# ══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
|
||||
def _build_location_note(cab) -> str:
|
||||
"""
|
||||
Build a keynote-traced location note for one cabinet, matching the
|
||||
04_Shop_Drawing_Unit_D1_Heritage_Village.xlsx template format:
|
||||
"Elev. A \u2014 Microwave above range U3"
|
||||
|
||||
Data sources (in priority order):
|
||||
1. cab.cabinet_id — keynote tag (e.g. "U3", "U10", "14") from AI extraction
|
||||
2. cab.notes — descriptive AI note (e.g. "Microwave above range")
|
||||
3. cab.elevation_ref — which elevation this cabinet lives on
|
||||
4. cab.location — raw fallback location string
|
||||
|
||||
Returns a string ≤60 chars, suitable for one Excel cell.
|
||||
"""
|
||||
parts = []
|
||||
|
||||
# Elevation reference: normalise "ELEVATION A" -> "Elev. A"
|
||||
elev = (cab.elevation_ref or "").strip()
|
||||
if elev:
|
||||
elev = elev.replace("ELEVATION ", "Elev. ").replace("ELEV. ", "Elev. ").replace("ELEV ", "Elev. ")
|
||||
parts.append(elev)
|
||||
|
||||
# Descriptive note
|
||||
note = (cab.notes or "").strip().rstrip(".")
|
||||
|
||||
# Keynote tag
|
||||
tag = (cab.cabinet_id or "").strip()
|
||||
|
||||
if note and tag:
|
||||
parts.append(f"{note} {tag}")
|
||||
elif note:
|
||||
parts.append(note)
|
||||
elif tag:
|
||||
parts.append(tag)
|
||||
elif cab.location:
|
||||
# Fallback: abbreviated raw location
|
||||
loc = cab.location.strip()
|
||||
parts.append(loc[:40] if len(loc) > 40 else loc)
|
||||
|
||||
return " — ".join(parts)[:60] # hard cap at 60 chars for readability
|
||||
|
||||
|
||||
def _build_shop_drawing_sheet(ws, unit_type: str, config: dict, schedule, st: dict):
|
||||
"""One sheet per unit type — full cabinet schedule with pricing."""
|
||||
thin = _thin_border(st)
|
||||
@@ -403,11 +446,12 @@ def _build_shop_drawing_sheet(ws, unit_type: str, config: dict, schedule, st: di
|
||||
for cab in kitchen_cabs:
|
||||
w_in = round(cab.width_in, 1)
|
||||
h_in = round(cab.height_in, 1)
|
||||
d_in = round(cab.depth_in / 25.4, 1)
|
||||
vals = [item_num, cab.code, f"{cab.cabinet_type} {w_in}\"W × {h_in}\"H",
|
||||
d_in = round(cab.depth_in, 1)
|
||||
loc_note = _build_location_note(cab)
|
||||
vals = [item_num, cab.code, f"{cab.cabinet_type} {w_in}\"W \u00d7 {h_in}\"H",
|
||||
cab.cabinet_type.replace("_", " ").title(),
|
||||
w_in, h_in, d_in, cab.quantity,
|
||||
cab.elevation_ref, cab.location[:30] if cab.location else ""]
|
||||
cab.elevation_ref, loc_note]
|
||||
for col, v in enumerate(vals, 1):
|
||||
c = ws.cell(row_idx, col, v)
|
||||
c.font = st["bold"] if col == 2 else st["reg"]
|
||||
@@ -435,12 +479,13 @@ def _build_shop_drawing_sheet(ws, unit_type: str, config: dict, schedule, st: di
|
||||
for cab in bath_cabs:
|
||||
w_in = round(cab.width_in, 1)
|
||||
h_in = round(cab.height_in, 1)
|
||||
d_in = round(cab.depth_in / 25.4, 1)
|
||||
d_in = round(cab.depth_in, 1)
|
||||
loc_note = _build_location_note(cab)
|
||||
vals = [item_num_bath, cab.code,
|
||||
f"{cab.cabinet_type} {w_in}\"W × {h_in}\"H",
|
||||
f"{cab.cabinet_type} {w_in}\"W \u00d7 {h_in}\"H",
|
||||
cab.cabinet_type.replace("_", " ").title(),
|
||||
w_in, h_in, d_in, cab.quantity,
|
||||
cab.elevation_ref, cab.location[:30] if cab.location else ""]
|
||||
cab.elevation_ref, loc_note]
|
||||
for col, v in enumerate(vals, 1):
|
||||
c = ws.cell(row_idx, col, v)
|
||||
c.font = st["bold"] if col == 2 else st["reg"]
|
||||
|
||||
@@ -64,6 +64,10 @@ class UnitSchedule:
|
||||
auto_approved: bool = False
|
||||
review_flags: list[str] = field(default_factory=list)
|
||||
legend_map: dict[str, str] = field(default_factory=dict)
|
||||
appliance_anchors: list[dict] = field(default_factory=list)
|
||||
floor_plan_doors: list[dict] = field(default_factory=list)
|
||||
floor_plan_windows: list[dict] = field(default_factory=list)
|
||||
kitchen_bbox: list[dict] = field(default_factory=list)
|
||||
|
||||
@property
|
||||
def all_cabinets(self):
|
||||
@@ -97,6 +101,7 @@ class PipelineResult:
|
||||
output_xlsx: Optional[str] = None
|
||||
duration_seconds: float = 0.0
|
||||
warnings: list[str] = field(default_factory=list)
|
||||
errors: list[str] = field(default_factory=list)
|
||||
|
||||
|
||||
# ══════════════════════════════════════════════════════════════════════════
|
||||
@@ -105,26 +110,15 @@ class PipelineResult:
|
||||
|
||||
def load_project_config(config_path: str | Path) -> dict:
|
||||
"""Load and validate project configuration JSON."""
|
||||
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:
|
||||
config = json.load(f)
|
||||
|
||||
required = ["project_id", "project_name", "unit_plan_pdfs"]
|
||||
for key in required:
|
||||
if key not in config:
|
||||
raise ValueError(f"Missing required field '{key}' in {config_path}")
|
||||
from core.config_loader import load_project_config as pydantic_load
|
||||
|
||||
config = pydantic_load(config_path)
|
||||
|
||||
# Validate appliances using ApplianceDatabase
|
||||
try:
|
||||
from core.engines.appliance_database import ApplianceDatabase
|
||||
appliance_schedule = ApplianceDatabase.get_appliance_schedule(config)
|
||||
|
||||
# Log any missing appliances (or empty arrays) if expected
|
||||
# if not appliance_schedule['regular']:
|
||||
# print(" [WARN] No regular appliances found in database")
|
||||
|
||||
config['appliance_schedule'] = appliance_schedule
|
||||
except ImportError:
|
||||
pass # If the database doesn't exist yet, just continue
|
||||
@@ -146,6 +140,7 @@ def process_unit(
|
||||
validator: CabinetValidator,
|
||||
skip_ai: bool = False,
|
||||
demo_mode: bool = False,
|
||||
force_ocr: bool = False,
|
||||
) -> UnitSchedule:
|
||||
"""
|
||||
Process one unit type PDF: extract → detect → crop → AI → validate.
|
||||
@@ -180,55 +175,7 @@ def process_unit(
|
||||
return out
|
||||
|
||||
for ev_data in cached.get("elevations", []):
|
||||
from core.ai_vision_classifier import (
|
||||
CabinetItem, ElevationResult,
|
||||
WallIntent, OpeningIntent, FixtureIntent,
|
||||
StructuralIntent, ApplianceIntent, ClearanceIntent,
|
||||
)
|
||||
cabs = []
|
||||
for c in ev_data.get("cabinets", []):
|
||||
if "cabinet_id" not in c:
|
||||
c["cabinet_id"] = ""
|
||||
if "source" not in c:
|
||||
c["source"] = "gemini"
|
||||
cabs.append(CabinetItem(**c))
|
||||
ev = ElevationResult(
|
||||
elevation_label = ev_data["elevation_label"],
|
||||
unit_type = unit_type,
|
||||
project_name = project_name,
|
||||
cabinets = cabs,
|
||||
is_ada = is_ada,
|
||||
walls = _dicts_to_intents(WallIntent, ev_data.get("walls", [])),
|
||||
openings = _dicts_to_intents(OpeningIntent, ev_data.get("openings", [])),
|
||||
fixtures = _dicts_to_intents(FixtureIntent, ev_data.get("fixtures", [])),
|
||||
structural = _dicts_to_intents(StructuralIntent, ev_data.get("structural", [])),
|
||||
clearances = _dicts_to_intents(ClearanceIntent, ev_data.get("clearances", [])),
|
||||
appliances = _dicts_to_intents(ApplianceIntent, ev_data.get("appliances", [])),
|
||||
doors = ev_data.get("doors", []),
|
||||
windows = ev_data.get("windows", []),
|
||||
fillers = ev_data.get("fillers", []),
|
||||
panels = ev_data.get("panels", []),
|
||||
moldings = ev_data.get("moldings", []),
|
||||
relationships = ev_data.get("relationships", []),
|
||||
ceiling_height_in = ev_data.get("ceiling_height_in", None),
|
||||
soffit_present = ev_data.get("soffit_present", False),
|
||||
backsplash = ev_data.get("backsplash", ""),
|
||||
counter_material = ev_data.get("counter_material", ""),
|
||||
)
|
||||
|
||||
# Load Architectural Intents (Phase 4)
|
||||
from core.ai_vision_classifier import WallIntent, OpeningIntent, FixtureIntent, StructuralIntent, ClearanceIntent
|
||||
|
||||
def _dicts_to_intents(data_list, cls):
|
||||
return [cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__}) for d in data_list] if data_list else []
|
||||
|
||||
ev.walls = _dicts_to_intents(ev_data.get("walls", []), WallIntent)
|
||||
ev.openings = _dicts_to_intents(ev_data.get("openings", []), OpeningIntent)
|
||||
ev.fixtures = _dicts_to_intents(ev_data.get("fixtures", []), FixtureIntent)
|
||||
ev.structural = _dicts_to_intents(ev_data.get("structural", []), StructuralIntent)
|
||||
ev.clearances = _dicts_to_intents(ev_data.get("clearances", []), ClearanceIntent)
|
||||
|
||||
schedule.elevations.append(ev)
|
||||
schedule.elevations.append(_dict_to_elevation_result(ev_data, unit_type, project_name, is_ada))
|
||||
return schedule
|
||||
|
||||
if not pdf_path.exists():
|
||||
@@ -238,6 +185,10 @@ def process_unit(
|
||||
|
||||
print(f"\n [{unit_type}] Processing: {pdf_path.name}")
|
||||
|
||||
# Initialize YOLO once per unit
|
||||
from core.yolo_extractor import YOLOExtractor
|
||||
yolo = YOLOExtractor()
|
||||
|
||||
with PDFExtractor(pdf_path) as ex:
|
||||
for page_idx in range(ex.page_count):
|
||||
page = ex.extract_page(page_idx)
|
||||
@@ -246,13 +197,21 @@ def process_unit(
|
||||
sheet_type = DrawingClassifier.classify_page(page.spans)
|
||||
print(f" [Page {page_idx + 1}] Class: {sheet_type}")
|
||||
|
||||
# If the PDF contains only 1 page, do not skip it even if classified as RCP/Detail,
|
||||
# as it is the only source drawing for this unit type.
|
||||
is_single_page = (ex.page_count == 1)
|
||||
if not is_single_page and sheet_type not in ("UNIT PLAN", "ELEVATION"):
|
||||
print(f" Skipping page {page_idx + 1} ({sheet_type})")
|
||||
continue
|
||||
|
||||
# --- Stage 1: YOLO Floor Plan Detection ---
|
||||
if sheet_type in ("UNIT PLAN", "FLOOR PLAN"):
|
||||
yolo_result = yolo.detect_floor_plan(ex.render_full_page(page_idx, dpi=200), dpi=200)
|
||||
if yolo_result.get("yolo_used"):
|
||||
schedule.appliance_anchors = yolo_result.get("appliances", [])
|
||||
schedule.floor_plan_doors = yolo_result.get("doors", [])
|
||||
schedule.floor_plan_windows = yolo_result.get("windows", [])
|
||||
schedule.kitchen_bbox = yolo_result.get("kitchen_regions", [])
|
||||
print(f" [YOLO] Extracted {len(schedule.appliance_anchors)} appliances")
|
||||
|
||||
# Extract legend mapping if not already done
|
||||
if not schedule.legend_map:
|
||||
from core.legend_extractor import LegendExtractor
|
||||
@@ -261,9 +220,34 @@ def process_unit(
|
||||
if schedule.legend_map:
|
||||
print(f" Extracted {len(schedule.legend_map)} keynotes from drawing legend")
|
||||
|
||||
# --- Model Fingerprint Check ---
|
||||
import re
|
||||
extracted_model = None
|
||||
for s in page.spans:
|
||||
m = re.search(r"MODEL\s*([0-9A-Za-z\-]+)", s.text, re.IGNORECASE)
|
||||
if m:
|
||||
extracted_model = m.group(1).upper()
|
||||
break
|
||||
|
||||
if extracted_model:
|
||||
clean_unit = re.sub(r'[^0-9A-Za-z]', '', unit_type.upper())
|
||||
clean_extracted = re.sub(r'[^0-9A-Za-z]', '', extracted_model)
|
||||
if clean_extracted not in clean_unit and clean_unit not in clean_extracted:
|
||||
msg = f"Model Mismatch: PDF says '{extracted_model}' but target generation is '{unit_type}'."
|
||||
print(f" [WARNING] {msg}")
|
||||
schedule.review_flags.append(msg)
|
||||
|
||||
# --- Physical Parameter Extractions ---
|
||||
clg_data = CeilingHeightExtractor.extract_heights(page.spans)
|
||||
openings_data = OpeningExtractor.extract_openings(page.spans, page.rects)
|
||||
openings_data = OpeningExtractor.extract_openings(
|
||||
spans = page.spans,
|
||||
rects = page.rects,
|
||||
legend_map = schedule.legend_map, # per-project keynote scheme
|
||||
)
|
||||
# Surface any opening extraction flags immediately
|
||||
for flag in openings_data.get("review_flags", []):
|
||||
print(f" [OPENING REVIEW] {flag}")
|
||||
schedule.review_flags.append(flag)
|
||||
|
||||
detector = RegionDetector(page.spans, page.rects, page.page_w, page.page_h)
|
||||
regions = detector.detect()
|
||||
@@ -310,44 +294,86 @@ def process_unit(
|
||||
print(f" [SKIP AI] Region {region.region_type} — AI disabled")
|
||||
continue
|
||||
|
||||
# Call Gemini Vision API
|
||||
mode_tag = "DEMO (low-token)" if demo_mode else "FULL"
|
||||
print(f" Sending {region.region_type} crop to Gemini Vision [{mode_tag}]...")
|
||||
elevation_result = classifier.classify_elevation(
|
||||
image_bytes = img_bytes,
|
||||
unit_type = unit_type,
|
||||
elevation_label = region.region_type,
|
||||
project_name = project_name,
|
||||
pre_extracted_dims = pre_dims,
|
||||
pre_extracted_rects = pre_rects,
|
||||
is_ada = is_ada,
|
||||
legend_map = schedule.legend_map,
|
||||
demo_mode = demo_mode,
|
||||
)
|
||||
from core.engines.layout_fingerprint_engine import LayoutFingerprintEngine
|
||||
input_fp = LayoutFingerprintEngine.generate_input_fingerprint(region.region_type, pre_dims, is_ada)
|
||||
|
||||
# Load signature cache
|
||||
sig_cache_path = output_dir.parent / "data" / "kitchen_signatures.json"
|
||||
sig_cache = {}
|
||||
if sig_cache_path.exists():
|
||||
with open(sig_cache_path, "r", encoding="utf-8") as f:
|
||||
try:
|
||||
sig_cache = json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if input_fp in sig_cache and not skip_ai:
|
||||
print(f" [CACHE HIT] Identical physical footprint found for {region.region_type}! Bypassing AI.")
|
||||
cached_ev = sig_cache[input_fp]
|
||||
elevation_result = _dict_to_elevation_result(cached_ev, unit_type, project_name, is_ada)
|
||||
else:
|
||||
# Call Gemini Vision API
|
||||
mode_tag = "DEMO (low-token)" if demo_mode else "FULL"
|
||||
print(f" Sending {region.region_type} crop to Gemini Vision [{mode_tag}]...")
|
||||
elevation_result = classifier.classify_elevation(
|
||||
image_bytes = img_bytes,
|
||||
unit_type = unit_type,
|
||||
elevation_label = region.region_type,
|
||||
project_name = project_name,
|
||||
pre_extracted_dims = pre_dims,
|
||||
pre_extracted_rects = pre_rects,
|
||||
is_ada = is_ada,
|
||||
legend_map = schedule.legend_map,
|
||||
demo_mode = demo_mode,
|
||||
)
|
||||
|
||||
# Fallback logic: inject legacy text-extracted dimensions ONLY if AI omits them
|
||||
# This prevents overwriting accurate Gemini Vision extractions while providing a safety net.
|
||||
if not elevation_result.windows and openings_data.get("windows"):
|
||||
elevation_result.windows = openings_data["windows"]
|
||||
if not elevation_result.doors and openings_data.get("doors"):
|
||||
elevation_result.doors = openings_data["doors"]
|
||||
if not elevation_result.ceiling_height_in and clg_data:
|
||||
elevation_result.ceiling_height_in = clg_data
|
||||
# Fallback logic: inject legacy text-extracted dimensions ONLY if AI omits them
|
||||
if not elevation_result.windows and openings_data.get("windows"):
|
||||
elevation_result.windows = openings_data["windows"]
|
||||
if not elevation_result.doors and openings_data.get("doors"):
|
||||
elevation_result.doors = openings_data["doors"]
|
||||
if not elevation_result.ceiling_height_in and clg_data:
|
||||
elevation_result.ceiling_height_in = clg_data
|
||||
|
||||
# Merge YOLO-sourced appliance anchors
|
||||
# YOLO appliance positions take priority over AI-vision-guessed positions
|
||||
if hasattr(schedule, "appliance_anchors") and schedule.appliance_anchors:
|
||||
from core.ai_vision_classifier import ApplianceIntent
|
||||
# Clear Gemini's guesses if YOLO found anything
|
||||
elevation_result.appliances = []
|
||||
for anchor in schedule.appliance_anchors:
|
||||
elevation_result.appliances.append(ApplianceIntent(
|
||||
type=anchor["type"],
|
||||
width_in=anchor.get("width_in", 24.0),
|
||||
height_in=anchor.get("height_in", 36.0),
|
||||
x_in=anchor.get("x_in", 0.0),
|
||||
notes="source: yolo"
|
||||
))
|
||||
|
||||
# Validate — basic structural rules
|
||||
validator.validate(
|
||||
elevation_result.cabinets,
|
||||
is_ada = is_ada,
|
||||
location = f"{unit_type} / {region.region_type}",
|
||||
)
|
||||
|
||||
|
||||
# Confidence Evaluation
|
||||
qa_res = ConfidenceEngine.evaluate(elevation_result)
|
||||
elevation_result.review_flags.extend(qa_res["warnings"])
|
||||
if qa_res["needs_review"]:
|
||||
print(f" [QA review flagged] {region.region_type}: {qa_res['warnings']}")
|
||||
elevation_result.auto_approved = False
|
||||
elevation_result.avg_confidence = min(elevation_result.avg_confidence, qa_res["confidence_score"])
|
||||
|
||||
# Cache the result in the signatures file for future identically-dimensioned units
|
||||
ev_dict = _elevation_result_to_dict(elevation_result)
|
||||
sig_cache[input_fp] = ev_dict
|
||||
sig_cache_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(sig_cache_path, "w", encoding="utf-8") as f:
|
||||
json.dump(sig_cache, f, indent=2)
|
||||
|
||||
# Validate
|
||||
validator.validate(
|
||||
elevation_result.cabinets,
|
||||
is_ada = is_ada,
|
||||
location = f"{unit_type} / {region.region_type}",
|
||||
)
|
||||
|
||||
# Confidence Evaluation
|
||||
qa_res = ConfidenceEngine.evaluate(elevation_result)
|
||||
elevation_result.review_flags.extend(qa_res["warnings"])
|
||||
if qa_res["needs_review"]:
|
||||
print(f" [QA review flagged] {region.region_type}: {qa_res['warnings']}")
|
||||
elevation_result.auto_approved = False
|
||||
elevation_result.avg_confidence = min(elevation_result.avg_confidence, qa_res["confidence_score"])
|
||||
|
||||
schedule.elevations.append(elevation_result)
|
||||
|
||||
@@ -373,6 +399,77 @@ def _intent_to_dict(obj):
|
||||
return asdict(obj)
|
||||
return obj
|
||||
|
||||
def _dict_to_elevation_result(ev_data: dict, unit_type: str, project_name: str, is_ada: bool):
|
||||
from core.ai_vision_classifier import (
|
||||
CabinetItem, ElevationResult,
|
||||
WallIntent, OpeningIntent, FixtureIntent,
|
||||
StructuralIntent, ApplianceIntent, ClearanceIntent,
|
||||
)
|
||||
|
||||
def _dicts_to_intents(data_list, cls):
|
||||
return [cls(**{k: v for k, v in d.items() if k in cls.__dataclass_fields__}) for d in data_list] if data_list else []
|
||||
|
||||
cabs = []
|
||||
for c in ev_data.get("cabinets", []):
|
||||
if "cabinet_id" not in c:
|
||||
c["cabinet_id"] = ""
|
||||
if "source" not in c:
|
||||
c["source"] = "gemini"
|
||||
cabs.append(CabinetItem(**c))
|
||||
|
||||
ev = ElevationResult(
|
||||
elevation_label = ev_data.get("elevation_label", "ELEVATION A"),
|
||||
unit_type = unit_type,
|
||||
project_name = project_name,
|
||||
cabinets = cabs,
|
||||
is_ada = is_ada,
|
||||
walls = _dicts_to_intents(ev_data.get("walls", []), WallIntent),
|
||||
openings = _dicts_to_intents(ev_data.get("openings", []), OpeningIntent),
|
||||
fixtures = _dicts_to_intents(ev_data.get("fixtures", []), FixtureIntent),
|
||||
structural = _dicts_to_intents(ev_data.get("structural", []), StructuralIntent),
|
||||
clearances = _dicts_to_intents(ev_data.get("clearances", []), ClearanceIntent),
|
||||
appliances = _dicts_to_intents(ev_data.get("appliances", []), ApplianceIntent),
|
||||
doors = ev_data.get("doors", []),
|
||||
windows = ev_data.get("windows", []),
|
||||
fillers = ev_data.get("fillers", []),
|
||||
panels = ev_data.get("panels", []),
|
||||
moldings = ev_data.get("moldings", []),
|
||||
relationships = ev_data.get("relationships", []),
|
||||
ceiling_height_in = ev_data.get("ceiling_height_in", None),
|
||||
soffit_present = ev_data.get("soffit_present", False),
|
||||
backsplash = ev_data.get("backsplash", ""),
|
||||
counter_material = ev_data.get("counter_material", ""),
|
||||
)
|
||||
return ev
|
||||
|
||||
|
||||
def _elevation_result_to_dict(ev) -> dict:
|
||||
return {
|
||||
"elevation_label": ev.elevation_label,
|
||||
"unit_type": ev.unit_type,
|
||||
"is_ada": ev.is_ada,
|
||||
"auto_approved": ev.auto_approved,
|
||||
"avg_confidence": ev.avg_confidence,
|
||||
"review_flags": ev.review_flags,
|
||||
"cabinets": [c.to_dict() for c in ev.cabinets],
|
||||
"walls": [_intent_to_dict(w) for w in ev.walls],
|
||||
"openings": [_intent_to_dict(o) for o in ev.openings],
|
||||
"fixtures": [_intent_to_dict(f) for f in ev.fixtures],
|
||||
"structural": [_intent_to_dict(s) for s in ev.structural],
|
||||
"clearances": [_intent_to_dict(c) for c in ev.clearances],
|
||||
"appliances": [_intent_to_dict(a) for a in ev.appliances],
|
||||
"doors": ev.doors,
|
||||
"windows": ev.windows,
|
||||
"fillers": ev.fillers,
|
||||
"panels": ev.panels,
|
||||
"moldings": ev.moldings,
|
||||
"relationships": ev.relationships,
|
||||
"ceiling_height_in": ev.ceiling_height_in,
|
||||
"soffit_present": ev.soffit_present,
|
||||
"backsplash": ev.backsplash,
|
||||
"counter_material": ev.counter_material,
|
||||
}
|
||||
|
||||
|
||||
def _save_schedule_json(schedule: UnitSchedule, out_path: Path):
|
||||
"""Save UnitSchedule to JSON for caching."""
|
||||
@@ -382,34 +479,7 @@ def _save_schedule_json(schedule: UnitSchedule, out_path: Path):
|
||||
"auto_approved": schedule.auto_approved,
|
||||
"review_flags": schedule.review_flags,
|
||||
"legend_map": schedule.legend_map,
|
||||
"elevations": [
|
||||
{
|
||||
"elevation_label": ev.elevation_label,
|
||||
"unit_type": ev.unit_type,
|
||||
"is_ada": ev.is_ada,
|
||||
"auto_approved": ev.auto_approved,
|
||||
"avg_confidence": ev.avg_confidence,
|
||||
"review_flags": ev.review_flags,
|
||||
"cabinets": [c.to_dict() for c in ev.cabinets],
|
||||
"walls": [_intent_to_dict(w) for w in ev.walls],
|
||||
"openings": [_intent_to_dict(o) for o in ev.openings],
|
||||
"fixtures": [_intent_to_dict(f) for f in ev.fixtures],
|
||||
"structural": [_intent_to_dict(s) for s in ev.structural],
|
||||
"clearances": [_intent_to_dict(c) for c in ev.clearances],
|
||||
"appliances": [_intent_to_dict(a) for a in ev.appliances],
|
||||
"doors": ev.doors,
|
||||
"windows": ev.windows,
|
||||
"fillers": ev.fillers,
|
||||
"panels": ev.panels,
|
||||
"moldings": ev.moldings,
|
||||
"relationships": ev.relationships,
|
||||
"ceiling_height_in": ev.ceiling_height_in,
|
||||
"soffit_present": ev.soffit_present,
|
||||
"backsplash": ev.backsplash,
|
||||
"counter_material": ev.counter_material,
|
||||
}
|
||||
for ev in schedule.elevations
|
||||
],
|
||||
"elevations": [_elevation_result_to_dict(ev) for ev in schedule.elevations],
|
||||
}
|
||||
out_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_path.write_text(json.dumps(data, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
@@ -484,6 +554,7 @@ def run_pipeline(
|
||||
unit_filter: Optional[str] = None,
|
||||
dry_run: bool = False,
|
||||
demo_mode: bool = False,
|
||||
force_ocr: bool = False,
|
||||
) -> PipelineResult:
|
||||
"""
|
||||
Run the complete cabinet estimation pipeline.
|
||||
@@ -497,6 +568,7 @@ def run_pipeline(
|
||||
start_time = time.time()
|
||||
config_path = Path(config_path)
|
||||
project_root = Path.cwd() # resolve PDF paths relative to CWD
|
||||
pipeline_errors: list[str] = [] # accumulate soft generation failures
|
||||
|
||||
print(f"\n{'=' * 60}")
|
||||
print(f" AI Cabinet Estimation Pipeline"
|
||||
@@ -530,12 +602,12 @@ def run_pipeline(
|
||||
try:
|
||||
classifier = CabinetVisionClassifier()
|
||||
print(" [OK] OpenRouter vision classifier ready")
|
||||
print(" [OK] Primary: google/gemini-2.5-flash")
|
||||
print(" [OK] Primary: google/gemini-2.5-pro")
|
||||
if demo_mode:
|
||||
print(" [OK] Demo mode: 150 DPI image, compact prompt, 1 retry")
|
||||
print(" (Est. cost: ~$0.0002/call vs $0.0015 in full mode)")
|
||||
else:
|
||||
print(" [OK] Fallback: google/gemini-2.5-pro")
|
||||
print(" [OK] Fallback: google/gemini-2.5-flash")
|
||||
except EnvironmentError as e:
|
||||
print(f" [FAIL] {e}")
|
||||
skip_ai = True
|
||||
@@ -571,6 +643,7 @@ def run_pipeline(
|
||||
validator = validator,
|
||||
skip_ai = skip_ai,
|
||||
demo_mode = demo_mode,
|
||||
force_ocr = force_ocr,
|
||||
)
|
||||
if combined_schedule is None:
|
||||
combined_schedule = schedule
|
||||
@@ -617,13 +690,21 @@ def run_pipeline(
|
||||
type_map = {} # unit_type -> {'kitchen_type': K#, 'vanity_type': V#}
|
||||
|
||||
def _nodes_to_constraint_dicts(nodes) -> list[dict]:
|
||||
"""Convert BIM-lite geometry nodes → the dict shape ConstraintExtractor reads."""
|
||||
"""Convert BIM-lite geometry nodes → the dict shape ConstraintExtractor reads.
|
||||
|
||||
Explicitly calls .inches on Length fields so ConstraintExtractor always
|
||||
receives plain Python floats, never Length objects (Phase 2 regression fix).
|
||||
"""
|
||||
out = []
|
||||
for n in nodes:
|
||||
md = getattr(n, "metadata", {}) or {}
|
||||
raw_width = getattr(n, "width", 0.0) or 0.0
|
||||
# Unwrap Length objects introduced in Phase 2 — ConstraintExtractor
|
||||
# expects plain float inches throughout.
|
||||
width_in = float(raw_width) if hasattr(raw_width, "inches") else float(raw_width or 0.0)
|
||||
out.append({
|
||||
"type": getattr(n, "node_type", ""),
|
||||
"width_in": getattr(n, "width", 0.0) or 0.0,
|
||||
"width_in": width_in,
|
||||
"x_in": md.get("x_in", 0.0) or 0.0,
|
||||
"notes": md.get("notes", ""),
|
||||
})
|
||||
@@ -647,7 +728,9 @@ def run_pipeline(
|
||||
# Extract → solve → place (deterministic)
|
||||
constraints = ConstraintExtractor.extract(
|
||||
wall_name = wall.name,
|
||||
wall_length = wall.length,
|
||||
# wall.length is always a Length object (WallModel.__init__ coerces it).
|
||||
# ConstraintExtractor and ConstraintSolver expect a plain float (inches).
|
||||
wall_length = float(wall.length.inches),
|
||||
openings = _nodes_to_constraint_dicts(wall.openings),
|
||||
appliances = _nodes_to_constraint_dicts(wall.appliances),
|
||||
fixtures = _nodes_to_constraint_dicts(wall.fixtures),
|
||||
@@ -657,13 +740,27 @@ def run_pipeline(
|
||||
solved = ConstraintSolver.solve(constraints)
|
||||
placed_cabs = placement_engine.place_wall(solved)
|
||||
except Exception as e:
|
||||
print(f" [WARN] Placement failed for {unit.name}/{wall.name}: {e}")
|
||||
continue
|
||||
print(f" [ERROR] Critical placement failure for {unit.name}/{wall.name}: {e}")
|
||||
raise RuntimeError(f"Placement Engine failed on {wall.name}") from e
|
||||
|
||||
if not placed_cabs:
|
||||
continue
|
||||
|
||||
if room.name.lower() == "bathroom":
|
||||
# Populate wall.cabinets so BIM-Lite post-placement engines can process them
|
||||
from core.bimlite.models import CabinetNode
|
||||
wall.cabinets = []
|
||||
for pc in placed_cabs:
|
||||
cab = CabinetNode(
|
||||
cab_type=pc.cabinet_type,
|
||||
width=pc.filler_width if pc.is_filler else float(pc.width),
|
||||
height=mfg.ada_base_height if room.is_ada else mfg.base_height,
|
||||
depth=mfg.base_depth,
|
||||
metadata={"notes": pc.notes, "is_filler": pc.is_filler, "x_start": pc.x_start}
|
||||
)
|
||||
cab.id = pc.code
|
||||
wall.cabinets.append(cab)
|
||||
|
||||
if isinstance(room, VanityModel):
|
||||
vanity_placed.extend(placed_cabs)
|
||||
else:
|
||||
kitchen_placed.extend(placed_cabs)
|
||||
@@ -678,6 +775,9 @@ def run_pipeline(
|
||||
continue
|
||||
|
||||
base_height = mfg.ada_base_height if room.is_ada else mfg.base_height
|
||||
# Reset elevation cabinets before writing deterministic placement output.
|
||||
# Without this, AI-extracted cabinets and placement-engine cabinets
|
||||
# accumulate in the same list — corrupting counts and shop drawing output.
|
||||
matching_elev.cabinets = []
|
||||
for idx, pc in enumerate(placed_cabs, start=1):
|
||||
width_in = pc.filler_width if pc.is_filler else float(pc.width)
|
||||
@@ -696,6 +796,20 @@ def run_pipeline(
|
||||
cabinet_id = pc.code,
|
||||
))
|
||||
|
||||
# Run BIM-Lite validation engine now that the room is fully populated
|
||||
try:
|
||||
from core.bimlite.engines import ValidationEngine
|
||||
val_report = ValidationEngine.validate_placement(room)
|
||||
for diag in val_report.diagnostics:
|
||||
msg = f"[BIM-LITE {diag['level']}] {unit.name} / {room.name}: {diag['message']}"
|
||||
if diag['level'] == "ERROR":
|
||||
print(f" {msg}")
|
||||
pipeline_errors.append(msg)
|
||||
elif diag['level'] == "WARN":
|
||||
print(f" {msg}")
|
||||
except Exception as e:
|
||||
print(f" [WARN] ValidationEngine failed: {e}")
|
||||
|
||||
# Fingerprint the placed layout to assign a stable kitchen and vanity type
|
||||
fp_height = mfg.ada_base_height if schedule.is_ada else mfg.base_height
|
||||
|
||||
@@ -763,7 +877,9 @@ def run_pipeline(
|
||||
bom_df.to_csv(bom_path, index=False)
|
||||
print(f" [SUCCESS] BOM Takeoff saved: {bom_path}")
|
||||
except Exception as e:
|
||||
print(f" [WARN] Failed to generate BOM: {e}")
|
||||
msg = f"BOM generation failed: {e}"
|
||||
print(f" [WARN] {msg}")
|
||||
pipeline_errors.append(msg)
|
||||
|
||||
# Build matrix list for schemas
|
||||
unit_matrix_list = []
|
||||
@@ -844,8 +960,10 @@ def run_pipeline(
|
||||
)
|
||||
print(f" [SUCCESS] Excel saved (backup): {excel_path_backup}")
|
||||
except Exception as e:
|
||||
print(f" [ERROR] Excel generation failed: {e}")
|
||||
msg = f"Excel generation failed: {e}"
|
||||
print(f" [ERROR] {msg}")
|
||||
import traceback; traceback.print_exc()
|
||||
pipeline_errors.append(msg)
|
||||
|
||||
# ── Step 5.5: Execute Phase 1-3 Architectural Engines ────────────────
|
||||
print(f"\n STEP 5.5: Executing Architectural Validation")
|
||||
@@ -856,16 +974,54 @@ def run_pipeline(
|
||||
|
||||
for ut, schedule in unit_schedules.items():
|
||||
if schedule.is_ada:
|
||||
# Build walls_info for geometry-based ADA clearance check.
|
||||
# room_depth: use the per-unit depth from config if present,
|
||||
# otherwise fall back to a standard 96" kitchen depth.
|
||||
room_depth = float(config.get("room_depth_in", 96.0))
|
||||
ada_walls = []
|
||||
for ev in schedule.elevations:
|
||||
wall_cabs = [
|
||||
{
|
||||
"x": float(getattr(c, "x_in", 0) or 0),
|
||||
"width": float(getattr(c, "width_in", 0) or 0),
|
||||
"height_in": float(getattr(c, "height_in", 0) or 0),
|
||||
"depth": float(getattr(c, "depth_in", 24) or 24),
|
||||
"cabinet_type": c.cabinet_type,
|
||||
"id": getattr(c, "cabinet_id", "") or "",
|
||||
}
|
||||
for c in ev.cabinets
|
||||
]
|
||||
if wall_cabs:
|
||||
ada_walls.append({
|
||||
"name": ev.elevation_label,
|
||||
"length": sum(c["width"] for c in wall_cabs),
|
||||
"cabinets": wall_cabs,
|
||||
})
|
||||
|
||||
unit_data = {
|
||||
"is_ada": True,
|
||||
"geometry": {},
|
||||
"cabinets": [vars(c) if hasattr(c, '__dict__') else c for c in schedule.all_cabinets]
|
||||
"is_ada": True,
|
||||
"geometry": {"walls": ada_walls, "room_depth": room_depth},
|
||||
"cabinets": [
|
||||
{
|
||||
"cabinet_type": c.cabinet_type,
|
||||
"height_in": float(getattr(c, "height_in", 0) or 0),
|
||||
"id": getattr(c, "cabinet_id", "") or "",
|
||||
}
|
||||
for c in schedule.all_cabinets
|
||||
],
|
||||
}
|
||||
ada_res = ADAEngine.run_full_validation(unit_data)
|
||||
if ada_res.get("status") == "FAIL":
|
||||
for issue in ada_res.get("issues", []):
|
||||
schedule.review_flags.append(f"[ADA] {issue['message']}")
|
||||
print(f" [OK] ADA validation run for {ut}")
|
||||
status = ada_res.get("status", "UNKNOWN")
|
||||
issues = ada_res.get("issues", [])
|
||||
for issue in issues:
|
||||
sev = issue.get("severity", "INFO")
|
||||
msg = issue.get("message", "")
|
||||
schedule.review_flags.append(f"[ADA-{sev}] {msg}")
|
||||
if sev == "ERROR":
|
||||
print(f" [ADA FAIL] {ut}: {msg}")
|
||||
else:
|
||||
print(f" [ADA WARN] {ut}: {msg}")
|
||||
print(f" [OK] ADA validation {status} for {ut} ({len(issues)} issue(s))")
|
||||
except ImportError as e:
|
||||
print(f" [WARN] Could not load ADA Engine: {e}")
|
||||
|
||||
@@ -904,9 +1060,17 @@ def run_pipeline(
|
||||
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
|
||||
# Ensure we keep the actual name (e.g. KITCHEN, BATHROOM) instead of renaming everything to A
|
||||
|
||||
# Guard: if no cabinets were placed (extraction failure), flag it.
|
||||
if base_x < 30.0:
|
||||
msg = (f"[{ut}] Wall '{wall_name}' accumulated length {base_x:.1f}"
|
||||
f' — no real cabinets placed, defaulting to 90". Mark for REVIEW.')
|
||||
print(f" [WARN] {msg}")
|
||||
result.warnings.append(msg)
|
||||
base_x = 90.0
|
||||
|
||||
walls_info.append({
|
||||
"name": wall_name,
|
||||
"length": max(90.0, base_x),
|
||||
"length": base_x,
|
||||
"cabinets": cabs_list
|
||||
})
|
||||
|
||||
@@ -917,11 +1081,18 @@ def run_pipeline(
|
||||
"cabinets": []
|
||||
})
|
||||
|
||||
ceiling_height = 108.0
|
||||
ceiling_height = None
|
||||
for ev in schedule.elevations:
|
||||
if ev.ceiling_height_in is not None:
|
||||
ceiling_height = ev.ceiling_height_in
|
||||
break
|
||||
|
||||
if ceiling_height is None:
|
||||
ceiling_height = 108.0
|
||||
msg = (f"[{ut}] Ceiling height not extracted from drawings "
|
||||
f'— defaulting to 108". Mark for REVIEW.')
|
||||
print(f" [WARN] {msg}")
|
||||
result.warnings.append(msg)
|
||||
|
||||
geom_data = geom_engine.generate_layout_geometry(
|
||||
walls = walls_info,
|
||||
@@ -933,8 +1104,10 @@ def run_pipeline(
|
||||
dxf_path = dxf_dir / f"{ut.replace(' ', '_')}.dxf"
|
||||
dxf_generator.generate(geom_data, dxf_path)
|
||||
except Exception as e:
|
||||
print(f" [ERROR] DXF generation failed: {e}")
|
||||
msg = f"DXF generation failed: {e}"
|
||||
print(f" [ERROR] {msg}")
|
||||
import traceback; traceback.print_exc()
|
||||
pipeline_errors.append(msg)
|
||||
|
||||
# ── Step 6: Generate Shop Drawing PDF ─────────────────────────────────
|
||||
print(f"\n STEP 6: Generating Shop Drawing PDF")
|
||||
@@ -963,18 +1136,18 @@ def run_pipeline(
|
||||
)
|
||||
print(f" [SUCCESS] PDF saved (backup): {pdf_out_backup}")
|
||||
except Exception as e:
|
||||
print(f" [ERROR] PDF generation failed: {e}")
|
||||
msg = f"PDF generation failed: {e}"
|
||||
print(f" [ERROR] {msg}")
|
||||
import traceback; traceback.print_exc()
|
||||
pipeline_errors.append(msg)
|
||||
|
||||
# ── Step 7: Output Final Deliverable Schemas ───────────────────────────
|
||||
print(f"\n STEP 7: Generating Target Deliverables JSON Schemas")
|
||||
print(f" {'-' * 50}")
|
||||
|
||||
from core.kitchen_layout_classifier import KitchenLayoutClassifier
|
||||
from core.vanity_layout_classifier import VanityLayoutClassifier
|
||||
from core.cabinet_graph_builder import CabinetGraphBuilder
|
||||
|
||||
# We can remove kitchen_classifier and vanity_classifier entirely since we rely on LayoutFingerprintEngine now.
|
||||
|
||||
# Using LayoutFingerprintEngine for classifications
|
||||
graph_builder = CabinetGraphBuilder()
|
||||
|
||||
for ut, schedule in unit_schedules.items():
|
||||
@@ -1045,6 +1218,7 @@ def run_pipeline(
|
||||
material_cost_usd = material_cost_usd,
|
||||
selling_price_usd = jc_result.selling_price,
|
||||
duration_seconds = duration,
|
||||
errors = pipeline_errors,
|
||||
)
|
||||
|
||||
|
||||
@@ -1084,6 +1258,10 @@ Examples:
|
||||
"--demo", action="store_true",
|
||||
help="Demo mode: lower image DPI + compact prompt — saves ~85%% Vision API tokens"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--ocr", action="store_true",
|
||||
help="Force OCR text extraction on all pages using PaddleOCR"
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
@@ -1095,4 +1273,5 @@ if __name__ == "__main__":
|
||||
unit_filter = args.unit,
|
||||
dry_run = args.dry_run,
|
||||
demo_mode = args.demo,
|
||||
force_ocr = args.ocr,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
import os
|
||||
import re
|
||||
import fitz
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# --- DIRECTORIES ---
|
||||
CASA_ARCH = r"C:\Users\abhil\Desktop\AI services for Cabinetries\Casa familia\Architectural"
|
||||
CASA_SHOP = r"C:\Users\abhil\Desktop\AI services for Cabinetries\Casa familia\ITALIANKB SHOP DRAWINGS - 23-033 CASA FAMILIA - 03.04.2025 hatch corregido.pdf"
|
||||
|
||||
HERITAGE_ARCH = r"C:\Users\abhil\Desktop\AI services for Cabinetries\Heritage\ARCHITECTURAL"
|
||||
HERITAGE_SHOP = r"C:\Users\abhil\Desktop\Cabinetries\Cabinets\Albert_Project\Heritage\03_Shop_Drawings\05_Cabinet_Estimation_Shop_Drawings_Heritage_Village.pdf"
|
||||
|
||||
ALBERT_ARCH = r"C:\Users\abhil\Downloads\22-51.pdf"
|
||||
ALBERT_SHOP = r"C:\Users\abhil\Downloads\1609.pdf"
|
||||
|
||||
def filter_architectural_pdfs(directory: str, prefix_filters: list[str]) -> list[str]:
|
||||
"""Return a list of paths to PDFs that match the prefix filters (e.g. A-6)."""
|
||||
if not os.path.exists(directory):
|
||||
return []
|
||||
filtered = []
|
||||
for f in os.listdir(directory):
|
||||
if not f.lower().endswith(".pdf"):
|
||||
continue
|
||||
# Check if matches any filter
|
||||
if any(filt.lower() in f.lower() for filt in prefix_filters):
|
||||
filtered.append(os.path.join(directory, f))
|
||||
return filtered
|
||||
|
||||
def extract_kitchen_vanity_data(pdf_path: str) -> dict:
|
||||
"""Extracts text blocks and tries to identify Kitchen / Vanity cabinet tags."""
|
||||
if not os.path.exists(pdf_path):
|
||||
return {}
|
||||
|
||||
doc = fitz.open(pdf_path)
|
||||
extracted = {"KITCHEN": [], "VANITY": []}
|
||||
|
||||
current_unit = "UNKNOWN_UNIT"
|
||||
current_room = None
|
||||
|
||||
# Simple regex for typical cabinet codes (e.g., W3030, B24, SB36, V3021)
|
||||
cabinet_regex = re.compile(r'\b([WBV]\d{2,4}|SB\d{2}|DB\d{2}|WDC\d{2})\b', re.IGNORECASE)
|
||||
|
||||
for page_num in range(doc.page_count):
|
||||
page = doc[page_num]
|
||||
blocks = page.get_text("blocks")
|
||||
|
||||
full_text = "\n".join([b[4] for b in blocks])
|
||||
|
||||
# Determine unit
|
||||
unit_match = re.search(r'(?:UNIT\s+)?([A-D](?:-\d+[A-Za-z]*)?|ST-\d+[A-Za-z]*)\s*(?:TYP|FHA|ADA|ACC)?', full_text, re.IGNORECASE)
|
||||
if unit_match:
|
||||
current_unit = unit_match.group(1).upper()
|
||||
|
||||
if "KITCHEN" in full_text.upper():
|
||||
current_room = "KITCHEN"
|
||||
elif "VANITY" in full_text.upper() or "BATH" in full_text.upper():
|
||||
current_room = "VANITY"
|
||||
|
||||
# Extract cabinets
|
||||
cabs = cabinet_regex.findall(full_text)
|
||||
if cabs and current_room:
|
||||
if current_unit not in extracted:
|
||||
extracted[current_unit] = {"KITCHEN": [], "VANITY": []}
|
||||
extracted[current_unit][current_room].extend([c.upper() for c in cabs])
|
||||
|
||||
doc.close()
|
||||
|
||||
# Deduplicate and sort
|
||||
for u in extracted:
|
||||
if isinstance(extracted[u], dict):
|
||||
extracted[u]["KITCHEN"] = sorted(list(set(extracted[u]["KITCHEN"])))
|
||||
extracted[u]["VANITY"] = sorted(list(set(extracted[u]["VANITY"])))
|
||||
|
||||
return extracted
|
||||
|
||||
def main():
|
||||
print("="*60)
|
||||
print(" BULK GAP ANALYSIS : ARCHITECTURAL VS SHOP DRAWINGS")
|
||||
print("="*60)
|
||||
|
||||
# 1. Filter Casa Familia
|
||||
casa_arch_pdfs = filter_architectural_pdfs(CASA_ARCH, ["A-6.", "A-5.08"])
|
||||
print(f"\n[Casa Familia] Filtered down to {len(casa_arch_pdfs)} Architectural Unit PDFs.")
|
||||
|
||||
# 2. Filter Heritage
|
||||
heritage_arch_pdfs = filter_architectural_pdfs(HERITAGE_ARCH, ["A-6.", "UNIT"])
|
||||
print(f"[Heritage] Filtered down to {len(heritage_arch_pdfs)} Architectural Unit PDFs.")
|
||||
|
||||
# 3. Albert
|
||||
albert_arch_pdfs = [ALBERT_ARCH] if os.path.exists(ALBERT_ARCH) else []
|
||||
|
||||
results = {
|
||||
"Casa Familia": {"Arch": {}, "Shop": {}},
|
||||
"Heritage": {"Arch": {}, "Shop": {}},
|
||||
"Albert": {"Arch": {}, "Shop": {}},
|
||||
}
|
||||
|
||||
# Extract Casa Familia Arch
|
||||
for pdf in casa_arch_pdfs:
|
||||
data = extract_kitchen_vanity_data(pdf)
|
||||
for unit, rooms in data.items():
|
||||
if unit not in ["KITCHEN", "VANITY"]:
|
||||
results["Casa Familia"]["Arch"][unit] = rooms
|
||||
|
||||
# Extract Casa Familia Shop
|
||||
casa_shop_data = extract_kitchen_vanity_data(CASA_SHOP)
|
||||
for unit, rooms in casa_shop_data.items():
|
||||
if unit not in ["KITCHEN", "VANITY"]:
|
||||
results["Casa Familia"]["Shop"][unit] = rooms
|
||||
|
||||
# Extract Heritage Arch
|
||||
for pdf in heritage_arch_pdfs:
|
||||
data = extract_kitchen_vanity_data(pdf)
|
||||
for unit, rooms in data.items():
|
||||
if unit not in ["KITCHEN", "VANITY"]:
|
||||
results["Heritage"]["Arch"][unit] = rooms
|
||||
|
||||
# Extract Heritage Shop
|
||||
heritage_shop_data = extract_kitchen_vanity_data(HERITAGE_SHOP)
|
||||
for unit, rooms in heritage_shop_data.items():
|
||||
if unit not in ["KITCHEN", "VANITY"]:
|
||||
results["Heritage"]["Shop"][unit] = rooms
|
||||
|
||||
# Extract Albert Arch
|
||||
if albert_arch_pdfs:
|
||||
data = extract_kitchen_vanity_data(albert_arch_pdfs[0])
|
||||
for unit, rooms in data.items():
|
||||
if unit not in ["KITCHEN", "VANITY"]:
|
||||
results["Albert"]["Arch"][unit] = rooms
|
||||
|
||||
# Extract Albert Shop
|
||||
albert_shop_data = extract_kitchen_vanity_data(ALBERT_SHOP)
|
||||
for unit, rooms in albert_shop_data.items():
|
||||
if unit not in ["KITCHEN", "VANITY"]:
|
||||
results["Albert"]["Shop"][unit] = rooms
|
||||
|
||||
# Output Results
|
||||
out_path = Path("outputs/gap_analysis_raw.json")
|
||||
out_path.parent.mkdir(exist_ok=True)
|
||||
out_path.write_text(json.dumps(results, indent=2))
|
||||
|
||||
# Print summary
|
||||
for project, pdata in results.items():
|
||||
print(f"\n--- {project} ---")
|
||||
arch_units = set(pdata["Arch"].keys())
|
||||
shop_units = set(pdata["Shop"].keys())
|
||||
all_units = sorted(list(arch_units | shop_units))
|
||||
|
||||
for u in all_units:
|
||||
print(f" Unit {u}:")
|
||||
arch_k = pdata["Arch"].get(u, {}).get("KITCHEN", [])
|
||||
shop_k = pdata["Shop"].get(u, {}).get("KITCHEN", [])
|
||||
print(f" Arch Kitchen: {arch_k}")
|
||||
print(f" Shop Kitchen: {shop_k}")
|
||||
if set(arch_k) != set(shop_k):
|
||||
print(f" -> MISMATCH in Kitchen Cabinets!")
|
||||
|
||||
arch_v = pdata["Arch"].get(u, {}).get("VANITY", [])
|
||||
shop_v = pdata["Shop"].get(u, {}).get("VANITY", [])
|
||||
print(f" Arch Vanity: {arch_v}")
|
||||
print(f" Shop Vanity: {shop_v}")
|
||||
if set(arch_v) != set(shop_v):
|
||||
print(f" -> MISMATCH in Vanity Cabinets!")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,116 @@
|
||||
task: detect
|
||||
mode: train
|
||||
model: yolov8n.pt
|
||||
data: datasets/floor_plan.yaml
|
||||
epochs: 100
|
||||
time: null
|
||||
patience: 100
|
||||
batch: 8
|
||||
imgsz: 1280
|
||||
save: true
|
||||
save_period: -1
|
||||
cache: false
|
||||
device: ''
|
||||
workers: 8
|
||||
project: models/yolo_floor_plan
|
||||
name: train
|
||||
exist_ok: false
|
||||
pretrained: true
|
||||
cls_remap: true
|
||||
optimizer: auto
|
||||
verbose: true
|
||||
seed: 0
|
||||
deterministic: true
|
||||
single_cls: false
|
||||
rect: false
|
||||
cos_lr: false
|
||||
close_mosaic: 10
|
||||
resume: false
|
||||
amp: true
|
||||
fraction: 1.0
|
||||
profile: false
|
||||
freeze: null
|
||||
multi_scale: 0.0
|
||||
compile: false
|
||||
channels_last: false
|
||||
overlap_mask: true
|
||||
mask_ratio: 4
|
||||
dropout: 0.0
|
||||
val: true
|
||||
split: val
|
||||
save_json: false
|
||||
conf: null
|
||||
iou: 0.7
|
||||
max_det: 300
|
||||
quantize: null
|
||||
dnn: false
|
||||
plots: true
|
||||
end2end: null
|
||||
source: null
|
||||
vid_stride: 1
|
||||
stream_buffer: false
|
||||
visualize: false
|
||||
augment: false
|
||||
agnostic_nms: false
|
||||
classes: null
|
||||
retina_masks: false
|
||||
embed: null
|
||||
show: false
|
||||
save_frames: false
|
||||
save_txt: false
|
||||
save_conf: false
|
||||
save_crop: false
|
||||
show_labels: true
|
||||
show_conf: true
|
||||
show_boxes: true
|
||||
line_width: null
|
||||
format: torchscript
|
||||
keras: false
|
||||
optimize: false
|
||||
dynamic: false
|
||||
simplify: true
|
||||
opset: null
|
||||
workspace: null
|
||||
nms: false
|
||||
lr0: 0.01
|
||||
lrf: 0.01
|
||||
momentum: 0.937
|
||||
weight_decay: 0.0005
|
||||
warmup_epochs: 3.0
|
||||
warmup_momentum: 0.8
|
||||
warmup_bias_lr: 0.1
|
||||
distill_model: null
|
||||
dis: 6.0
|
||||
box: 7.5
|
||||
cls: 0.5
|
||||
cls_pw: 0.0
|
||||
dfl: 1.5
|
||||
pose: 12.0
|
||||
kobj: 1.0
|
||||
rle: 1.0
|
||||
angle: 1.0
|
||||
dlog: 1.0
|
||||
dgrad: 0.5
|
||||
dlam: 1.0
|
||||
nbs: 64
|
||||
hsv_h: 0.015
|
||||
hsv_s: 0.7
|
||||
hsv_v: 0.4
|
||||
degrees: 0.0
|
||||
translate: 0.1
|
||||
scale: 0.5
|
||||
shear: 0.0
|
||||
perspective: 0.0
|
||||
flipud: 0.0
|
||||
fliplr: 0.5
|
||||
bgr: 0.0
|
||||
mosaic: 1.0
|
||||
mixup: 0.0
|
||||
cutmix: 0.0
|
||||
copy_paste: 0.0
|
||||
copy_paste_mode: flip
|
||||
auto_augment: randaugment
|
||||
erasing: 0.4
|
||||
cfg: null
|
||||
tracker: tracktrack.yaml
|
||||
save_dir: C:\Users\abhil\Desktop\Cabinetries\Cabinets\Albert_Project\runs\detect\models\yolo_floor_plan\train
|
||||
|
After Width: | Height: | Size: 132 KiB |
|
After Width: | Height: | Size: 431 KiB |
|
After Width: | Height: | Size: 499 KiB |
|
After Width: | Height: | Size: 181 KiB |
@@ -1,261 +0,0 @@
|
||||
"""
|
||||
Validation tests for all core modules.
|
||||
Run: python test_all.py
|
||||
"""
|
||||
import sys
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
PASS = "[PASS]"
|
||||
FAIL = "[FAIL]"
|
||||
|
||||
def check(label, condition, info=""):
|
||||
status = PASS if condition else FAIL
|
||||
print(f" {status} {label} {info}")
|
||||
return condition
|
||||
|
||||
all_ok = True
|
||||
|
||||
# ════════════════════════════════════════════════════
|
||||
print("=" * 55)
|
||||
print(" Albert Project — Core Module Validation Tests")
|
||||
print("=" * 55)
|
||||
|
||||
# ── Test 1: Config ───────────────────────────────────
|
||||
print("\n[1] Config")
|
||||
try:
|
||||
from core.config import PROJECT_ROOT, EUR_USD_RATE, ANTHROPIC_API_KEY, STANDARD_WIDTHS_IN
|
||||
|
||||
check("Project Root valid", PROJECT_ROOT.exists(), "OK")
|
||||
check("EUR_USD_RATE valid", EUR_USD_RATE > 0.5, "OK")
|
||||
check("Anthropic Key loaded", len(ANTHROPIC_API_KEY) > 10 if ANTHROPIC_API_KEY else True, "OK")
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} Config import failed: {e}")
|
||||
all_ok = False
|
||||
|
||||
# ── Test 2: Dimension Parser ─────────────────────────
|
||||
print("\n[2] Dimension Parser")
|
||||
try:
|
||||
from core.dimension_parser import parse_metric_mm, parse_imperial_mm, cross_validate
|
||||
|
||||
# Metric
|
||||
tests_m = [
|
||||
("76.20", 762.0),
|
||||
("90.00", 900.0),
|
||||
("228.60", 2286.0),
|
||||
("30", 300.0),
|
||||
("1", None),
|
||||
("9999", None),
|
||||
]
|
||||
for txt, expected in tests_m:
|
||||
result = parse_metric_mm(txt)
|
||||
ok = (result == expected) or (result is None and expected is None)
|
||||
check(f"metric({txt!r})", ok, f"-> {result} (exp {expected})")
|
||||
all_ok = all_ok and ok
|
||||
|
||||
# Imperial
|
||||
tests_i = [
|
||||
("36\"", 914.4),
|
||||
("3'-0\"", 914.4),
|
||||
("[14']", 4267.2),
|
||||
]
|
||||
for txt, expected in tests_i:
|
||||
result = parse_imperial_mm(txt)
|
||||
result_str = f"{result:.1f}" if result is not None else "None"
|
||||
ok = result is not None and abs(result - expected) < 1.5
|
||||
check(f"imperial({txt!r})", ok, f"-> {result_str} (exp {expected})")
|
||||
all_ok = all_ok and ok
|
||||
|
||||
# Cross-validation
|
||||
pair = cross_validate(762.0, 762.0)
|
||||
check("cross_validate(762,762)", pair.confidence == "HIGH", pair.confidence)
|
||||
|
||||
pair_mis = cross_validate(762.0, 914.4)
|
||||
check("cross_validate mismatch", pair_mis.confidence == "MISMATCH", pair_mis.confidence)
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} dimension_parser error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 3: Job Costing ──────────────────────────────
|
||||
print("\n[3] Job Costing")
|
||||
try:
|
||||
from core.job_costing import JobCostingInput, calculate_selling_price
|
||||
|
||||
inp = JobCostingInput(total_cabinet_count=630, material_cost_usd=95_000.0)
|
||||
res = calculate_selling_price(inp)
|
||||
|
||||
ok_gp = abs(res.gp_check_pct - 0.35) < 0.001
|
||||
ok_pos = res.selling_price > 0
|
||||
ok_math = abs(res.pre_margin_total / (1 - 0.35 - 0.05 - 0.015) - res.selling_price) < 1.0
|
||||
|
||||
check("GP% verification", ok_gp, f"{res.gp_check_pct:.4f} (exp 0.35)")
|
||||
check("Selling price > 0", ok_pos, f"${res.selling_price:,.2f}")
|
||||
check("Algebraic formula", ok_math, f"pre-margin/denom = ${res.selling_price:,.2f}")
|
||||
check("Containers needed", res.containers_needed == 3, f"{res.containers_needed} containers")
|
||||
|
||||
all_ok = all_ok and ok_gp and ok_pos and ok_math
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} job_costing error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 4: AI Vision JSON Parser ────────────────────
|
||||
print("\n[4] AI Vision Classifier (JSON parser, no API key needed)")
|
||||
try:
|
||||
from core.ai_vision_classifier import CabinetVisionClassifier, _normalize_cabinet_type, _default_height
|
||||
|
||||
# Test JSON parsing without creating full object
|
||||
c = object.__new__(CabinetVisionClassifier)
|
||||
sample_json = '''{ "cabinets": [
|
||||
{"item_num": 1, "cabinet_type": "upper_wall", "width_mm": 762, "height_mm": 762,
|
||||
"depth_mm": 330, "location": "Left of range", "elevation_ref": "ELEV A",
|
||||
"confidence": 0.92, "quantity": 1, "is_ada": false, "notes": ""},
|
||||
{"item_num": 2, "cabinet_type": "base", "width_mm": 914.4, "height_mm": 720,
|
||||
"depth_mm": 600, "location": "Sink base", "elevation_ref": "ELEV A",
|
||||
"confidence": 0.88, "quantity": 1, "is_ada": false, "notes": "sink base"},
|
||||
{"item_num": 3, "cabinet_type": "appliance_space", "width_mm": 610, "height_mm": 720,
|
||||
"depth_mm": 600, "location": "DW", "elevation_ref": "ELEV A",
|
||||
"confidence": 0.98, "quantity": 1, "is_ada": false, "notes": "dishwasher"}
|
||||
]}'''
|
||||
cabs_data = c._parse_cabinet_json(sample_json, "ELEV A")
|
||||
from core.ai_vision_classifier import CabinetItem, _normalize_cabinet_type, _default_height, _default_depth, VALID_CABINET_TYPES
|
||||
cabs = []
|
||||
for i, item in enumerate(cabs_data.get("cabinets", []), 1):
|
||||
cab_type = item.get("cabinet_type", "unknown").lower().strip()
|
||||
if cab_type not in VALID_CABINET_TYPES:
|
||||
cab_type = _normalize_cabinet_type(cab_type)
|
||||
width_in = float(item.get("width_mm", 0) or 0) / 25.4
|
||||
height_in = float(item.get("height_mm", 0) or 0) / 25.4
|
||||
depth_in = float(item.get("depth_mm", 0) or 0) / 25.4
|
||||
if height_in == 0:
|
||||
height_in = _default_height(cab_type) / 25.4
|
||||
if depth_in == 0:
|
||||
depth_in = _default_depth(cab_type) / 25.4
|
||||
cabs.append(CabinetItem(
|
||||
item_num = i,
|
||||
cabinet_type = cab_type,
|
||||
width_in = width_in,
|
||||
height_in = height_in,
|
||||
depth_in = depth_in,
|
||||
location = item.get("location", ""),
|
||||
elevation_ref = "ELEV A",
|
||||
confidence = item.get("confidence", 0.9),
|
||||
quantity = item.get("quantity", 1),
|
||||
is_ada = item.get("is_ada", False),
|
||||
notes = item.get("notes", "")
|
||||
))
|
||||
|
||||
check("Parsed 3 items", len(cabs) == 3, f"{len(cabs)} items")
|
||||
check("First item width=30in", abs(cabs[0].width_in - 30) < 0.1, str(cabs[0].width_in))
|
||||
check("First item code contains W30", "W30" in cabs[0].code, cabs[0].code)
|
||||
check("Third item = appliance_space", cabs[2].cabinet_type == "appliance_space", cabs[2].cabinet_type)
|
||||
|
||||
# Test type normalization
|
||||
check("normalize 'wall'", _normalize_cabinet_type("wall") == "upper_wall")
|
||||
check("normalize 'dishwasher'", _normalize_cabinet_type("dishwasher") == "appliance_space")
|
||||
|
||||
# Test default heights
|
||||
check("pantry height=2130", _default_height("pantry") == 2130.0)
|
||||
check("base height=720", _default_height("base") == 720.0)
|
||||
|
||||
all_ok = all_ok and len(cabs) == 3
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} ai_vision_classifier error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 5: Cabinet Validator ────────────────────────
|
||||
print("\n[5] Cabinet Validator")
|
||||
try:
|
||||
from core.cabinet_validator import CabinetValidator
|
||||
from core.ai_vision_classifier import CabinetItem
|
||||
|
||||
test_cabs = [
|
||||
CabinetItem(1, "upper_wall", 762.0/25.4, 300.0/25.4, 330.0/25.4, "Left", "ELEV A", 0.92),
|
||||
CabinetItem(2, "base", 900.0/25.4, 720.0/25.4, 600.0/25.4, "Base", "ELEV A", 0.88),
|
||||
CabinetItem(3, "appliance_space", 610.0/25.4, 720.0/25.4, 600.0/25.4, "DW", "ELEV A", 0.98),
|
||||
]
|
||||
validator = CabinetValidator()
|
||||
result = validator.get_validation_result(test_cabs, room_width_in=None, is_ada=False)
|
||||
|
||||
check("Score > 0.8", result.overall_score > 0.8, f"{result.overall_score:.2f}")
|
||||
check("No critical flags", len(result.flags) == 0, f"{len(result.flags)} flags")
|
||||
|
||||
# ADA test
|
||||
ada_cabs = [
|
||||
CabinetItem(1, "base", 900.0/25.4, 1000.0/25.4, 600.0/25.4, "ADA Base", "ELEV A", 0.9),
|
||||
]
|
||||
ada_result = validator.get_validation_result(ada_cabs, is_ada=True)
|
||||
check("ADA height flag detected", len(ada_result.flags) > 0, f"{ada_result.flags}")
|
||||
|
||||
all_ok = all_ok and result.overall_score > 0.8
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} cabinet_validator error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 6: Price Matcher Fallback ───────────────────
|
||||
print("\n[6] Price Matcher (fallback catalog)")
|
||||
try:
|
||||
from core.price_matcher import get_fallback_price_usd, _generate_code
|
||||
|
||||
check("B36 fallback", get_fallback_price_usd("B36") == 149.0, str(get_fallback_price_usd("B36")))
|
||||
check("VAN60 fallback", get_fallback_price_usd("VAN60") == 310.0, str(get_fallback_price_usd("VAN60")))
|
||||
check("unknown fallback", get_fallback_price_usd("XYZ999") == 2048.0, str(get_fallback_price_usd("XYZ999")))
|
||||
|
||||
code = _generate_code("base", 914.0)
|
||||
check("base 914mm code = B36", code == "B36", code)
|
||||
code2 = _generate_code("vanity", 762.0)
|
||||
check("vanity 762mm code = VAN30", code2 == "VAN30", code2)
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} price_matcher error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 7: Unit Counter (manual mode) ───────────────
|
||||
print("\n[7] Unit Counter (manual override)")
|
||||
try:
|
||||
from core.unit_matrix_extractor import load_matrix_from_config
|
||||
matrix = load_matrix_from_config({"A1": 14, "B1": 6}, "Test Project")
|
||||
check("Totals loaded", matrix.totals == {"A1": 14, "B1": 6})
|
||||
check("Confidence = 1.0", matrix.confidence == 1.0)
|
||||
check("Needs review = False", not matrix.needs_review)
|
||||
except Exception as e:
|
||||
print(f" {FAIL} unit_matrix_extractor error: {e}")
|
||||
all_ok = False
|
||||
|
||||
# ── Test 8: PDF Extractor (basic import) ─────────────
|
||||
print("\n[8] PDF Extractor (import test)")
|
||||
try:
|
||||
from core.pdf_extractor import PDFExtractor, TextSpan, VectorRect, PageData
|
||||
check("PDFExtractor imported", True)
|
||||
check("TextSpan imported", True)
|
||||
check("VectorRect imported", True)
|
||||
except Exception as e:
|
||||
print(f" {FAIL} pdf_extractor import error: {e}")
|
||||
all_ok = False
|
||||
|
||||
# ── Test 9: Region Detector (basic import) ───────────
|
||||
print("\n[9] Region Detector (import test)")
|
||||
try:
|
||||
from core.region_detector import RegionDetector, DetectedRegion
|
||||
check("RegionDetector imported", True)
|
||||
check("DetectedRegion imported", True)
|
||||
except Exception as e:
|
||||
print(f" {FAIL} region_detector import error: {e}")
|
||||
all_ok = False
|
||||
|
||||
# ── Summary ───────────────────────────────────────────
|
||||
print("\n" + "=" * 55)
|
||||
if all_ok:
|
||||
print(" ALL TESTS PASSED")
|
||||
else:
|
||||
print(" SOME TESTS FAILED - see above")
|
||||
print("=" * 55)
|
||||
sys.exit(0 if all_ok else 1)
|
||||
@@ -0,0 +1,83 @@
|
||||
import pytest
|
||||
from core.bimlite.models import UnitModel, KitchenModel, VanityModel, RoomModel, WallModel, CabinetNode
|
||||
from core.bimlite.parser import ModelBuilder
|
||||
from core.bimlite.engines import ValidationEngine
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
def test_model_builder_no_crash():
|
||||
# Setup dummy schedule
|
||||
class DummyElevation:
|
||||
def __init__(self, label):
|
||||
self.elevation_label = label
|
||||
|
||||
class DummyWall:
|
||||
def __init__(self):
|
||||
self.name = "Wall"
|
||||
self.length_in = 100.0
|
||||
|
||||
self.walls = [DummyWall()]
|
||||
self.openings = []
|
||||
self.appliances = []
|
||||
self.fixtures = []
|
||||
self.structural = []
|
||||
self.clearances = []
|
||||
|
||||
class DummySchedule:
|
||||
def __init__(self):
|
||||
self.is_ada = False
|
||||
self.elevations = [
|
||||
DummyElevation("KITCHEN ELEVATION A"),
|
||||
DummyElevation("BATH ELEVATION B")
|
||||
]
|
||||
|
||||
# Create dummy unit data
|
||||
units_schedules = {"UnitA": DummySchedule()}
|
||||
config = {"buildings": {"Bldg1": ["UnitA"]}}
|
||||
unit_totals = {"UnitA": 1}
|
||||
|
||||
# Should not raise NameError for RoomModel
|
||||
project = ModelBuilder.build_project("Test", config, units_schedules, unit_totals)
|
||||
|
||||
assert len(project.buildings) == 1
|
||||
assert len(project.buildings[0].floors[0].units) == 1
|
||||
unit = project.buildings[0].floors[0].units[0]
|
||||
|
||||
assert len(unit.rooms) == 2
|
||||
room_types = [type(r) for r in unit.rooms]
|
||||
assert KitchenModel in room_types
|
||||
assert VanityModel in room_types
|
||||
assert RoomModel not in room_types
|
||||
|
||||
def test_room_model_properties():
|
||||
room = VanityModel()
|
||||
wall = WallModel("Wall A", 100.0)
|
||||
|
||||
cab1 = CabinetNode("Base", 24.0, 34.5, 24.0)
|
||||
cab2 = CabinetNode("Upper", 24.0, 30.0, 12.0)
|
||||
|
||||
wall.cabinets.extend([cab1, cab2])
|
||||
room.walls.append(wall)
|
||||
|
||||
# Check that property access works without AttributeError and flattens correctly
|
||||
assert len(room.cabinets) == 2
|
||||
assert room.cabinets[0] == cab1
|
||||
assert room.cabinets[1] == cab2
|
||||
|
||||
def test_validation_intent():
|
||||
room = KitchenModel()
|
||||
# No walls -> should fail validate_intent
|
||||
report = ValidationEngine.validate_intent(room)
|
||||
assert not report.is_valid
|
||||
assert any("No walls found" in d["message"] for d in report.diagnostics)
|
||||
|
||||
wall = WallModel("Wall", 100.0)
|
||||
room.walls.append(wall)
|
||||
|
||||
# Walls exist -> should pass validate_intent
|
||||
report = ValidationEngine.validate_intent(room)
|
||||
assert report.is_valid
|
||||
|
||||
# But it has no cabinets, so validate_placement should fail
|
||||
report2 = ValidationEngine.validate_placement(room)
|
||||
assert not report2.is_valid
|
||||
assert any("No cabinets found" in d["message"] for d in report2.diagnostics)
|
||||
@@ -0,0 +1,257 @@
|
||||
def test_all_legacy():
|
||||
all_ok = True
|
||||
def check(name, condition, info=""):
|
||||
nonlocal all_ok
|
||||
status = "[PASS]" if condition else "[FAIL]"
|
||||
print(f" {status} {name} {info}")
|
||||
if not condition:
|
||||
all_ok = False
|
||||
|
||||
"""
|
||||
Validation tests for all core modules.
|
||||
Run: python test_all.py
|
||||
"""
|
||||
import sys
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
|
||||
PASS = "[PASS]"
|
||||
FAIL = "[FAIL]"
|
||||
|
||||
try:
|
||||
from core.config import PROJECT_ROOT, EUR_USD_RATE, ANTHROPIC_API_KEY, STANDARD_WIDTHS_IN
|
||||
|
||||
check("Project Root valid", PROJECT_ROOT.exists(), "OK")
|
||||
check("EUR_USD_RATE valid", EUR_USD_RATE > 0.5, "OK")
|
||||
check("Anthropic Key loaded", len(ANTHROPIC_API_KEY) > 10 if ANTHROPIC_API_KEY else True, "OK")
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} Config import failed: {e}")
|
||||
all_ok = False
|
||||
|
||||
# ── Test 2: Dimension Parser ─────────────────────────
|
||||
print("\n[2] Dimension Parser")
|
||||
try:
|
||||
from core.dimension_parser import parse_metric_mm, parse_imperial_mm, cross_validate
|
||||
|
||||
# Metric
|
||||
tests_m = [
|
||||
("76.20", 762.0),
|
||||
("90.00", 900.0),
|
||||
("228.60", 2286.0),
|
||||
("30", 300.0),
|
||||
("1", None),
|
||||
("9999", None),
|
||||
]
|
||||
for txt, expected in tests_m:
|
||||
result = parse_metric_mm(txt)
|
||||
ok = (result == expected) or (result is None and expected is None)
|
||||
check(f"metric({txt!r})", ok, f"-> {result} (exp {expected})")
|
||||
all_ok = all_ok and ok
|
||||
|
||||
# Imperial
|
||||
tests_i = [
|
||||
("36\"", 914.4),
|
||||
("3'-0\"", 914.4),
|
||||
("[14']", 4267.2),
|
||||
]
|
||||
for txt, expected in tests_i:
|
||||
result = parse_imperial_mm(txt)
|
||||
result_str = f"{result:.1f}" if result is not None else "None"
|
||||
ok = result is not None and abs(result - expected) < 1.5
|
||||
check(f"imperial({txt!r})", ok, f"-> {result_str} (exp {expected})")
|
||||
all_ok = all_ok and ok
|
||||
|
||||
# Cross-validation
|
||||
pair = cross_validate(762.0, 762.0)
|
||||
check("cross_validate(762,762)", pair.confidence == "HIGH", pair.confidence)
|
||||
|
||||
pair_mis = cross_validate(762.0, 914.4)
|
||||
check("cross_validate mismatch", pair_mis.confidence == "MISMATCH", pair_mis.confidence)
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} dimension_parser error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 3: Job Costing ──────────────────────────────
|
||||
print("\n[3] Job Costing")
|
||||
try:
|
||||
from core.job_costing import JobCostingInput, calculate_selling_price
|
||||
|
||||
inp = JobCostingInput(total_cabinet_count=630, material_cost_usd=95_000.0)
|
||||
res = calculate_selling_price(inp)
|
||||
|
||||
ok_gp = abs(res.gp_check_pct - 0.35) < 0.001
|
||||
ok_pos = res.selling_price > 0
|
||||
ok_math = abs(res.pre_margin_total / (1 - 0.35 - 0.05 - 0.015) - res.selling_price) < 1.0
|
||||
|
||||
check("GP% verification", ok_gp, f"{res.gp_check_pct:.4f} (exp 0.35)")
|
||||
check("Selling price > 0", ok_pos, f"${res.selling_price:,.2f}")
|
||||
check("Algebraic formula", ok_math, f"pre-margin/denom = ${res.selling_price:,.2f}")
|
||||
check("Containers needed", res.containers_needed == 3, f"{res.containers_needed} containers")
|
||||
|
||||
all_ok = all_ok and ok_gp and ok_pos and ok_math
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} job_costing error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 4: AI Vision JSON Parser ────────────────────
|
||||
print("\n[4] AI Vision Classifier (JSON parser, no API key needed)")
|
||||
try:
|
||||
from core.ai_vision_classifier import CabinetVisionClassifier, _normalize_cabinet_type, _default_height
|
||||
|
||||
# Test JSON parsing without creating full object
|
||||
c = object.__new__(CabinetVisionClassifier)
|
||||
sample_json = '''{ "cabinets": [
|
||||
{"item_num": 1, "cabinet_type": "upper_wall", "width_mm": 762, "height_mm": 762,
|
||||
"depth_mm": 330, "location": "Left of range", "elevation_ref": "ELEV A",
|
||||
"confidence": 0.92, "quantity": 1, "is_ada": false, "notes": ""},
|
||||
{"item_num": 2, "cabinet_type": "base", "width_mm": 914.4, "height_mm": 720,
|
||||
"depth_mm": 600, "location": "Sink base", "elevation_ref": "ELEV A",
|
||||
"confidence": 0.88, "quantity": 1, "is_ada": false, "notes": "sink base"},
|
||||
{"item_num": 3, "cabinet_type": "appliance_space", "width_mm": 610, "height_mm": 720,
|
||||
"depth_mm": 600, "location": "DW", "elevation_ref": "ELEV A",
|
||||
"confidence": 0.98, "quantity": 1, "is_ada": false, "notes": "dishwasher"}
|
||||
]}'''
|
||||
cabs_data = c._parse_cabinet_json(sample_json, "ELEV A")
|
||||
from core.ai_vision_classifier import CabinetItem, _normalize_cabinet_type, _default_height, _default_depth, VALID_CABINET_TYPES
|
||||
cabs = []
|
||||
for i, item in enumerate(cabs_data.get("cabinets", []), 1):
|
||||
cab_type = item.get("cabinet_type", "unknown").lower().strip()
|
||||
if cab_type not in VALID_CABINET_TYPES:
|
||||
cab_type = _normalize_cabinet_type(cab_type)
|
||||
width_in = float(item.get("width_mm", 0) or 0) / 25.4
|
||||
height_in = float(item.get("height_mm", 0) or 0) / 25.4
|
||||
depth_in = float(item.get("depth_mm", 0) or 0) / 25.4
|
||||
if height_in == 0:
|
||||
height_in = _default_height(cab_type) / 25.4
|
||||
if depth_in == 0:
|
||||
depth_in = _default_depth(cab_type) / 25.4
|
||||
cabs.append(CabinetItem(
|
||||
item_num = i,
|
||||
cabinet_type = cab_type,
|
||||
width_in = width_in,
|
||||
height_in = height_in,
|
||||
depth_in = depth_in,
|
||||
location = item.get("location", ""),
|
||||
elevation_ref = "ELEV A",
|
||||
confidence = item.get("confidence", 0.9),
|
||||
quantity = item.get("quantity", 1),
|
||||
is_ada = item.get("is_ada", False),
|
||||
notes = item.get("notes", "")
|
||||
))
|
||||
|
||||
check("Parsed 3 items", len(cabs) == 3, f"{len(cabs)} items")
|
||||
check("First item width=30in", abs(cabs[0].width_in - 30) < 0.1, str(cabs[0].width_in))
|
||||
check("First item code contains W30", "W30" in cabs[0].code, cabs[0].code)
|
||||
check("Third item = appliance_space", cabs[2].cabinet_type == "appliance_space", cabs[2].cabinet_type)
|
||||
|
||||
# Test type normalization
|
||||
check("normalize 'wall'", _normalize_cabinet_type("wall") == "upper_wall")
|
||||
check("normalize 'dishwasher'", _normalize_cabinet_type("dishwasher") == "appliance_space")
|
||||
|
||||
# Test default heights
|
||||
check("pantry height=2130", _default_height("pantry") == 2130.0)
|
||||
check("base height=720", _default_height("base") == 720.0)
|
||||
|
||||
all_ok = all_ok and len(cabs) == 3
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} ai_vision_classifier error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 5: Cabinet Validator ────────────────────────
|
||||
print("\n[5] Cabinet Validator")
|
||||
try:
|
||||
from core.cabinet_validator import CabinetValidator
|
||||
from core.ai_vision_classifier import CabinetItem
|
||||
|
||||
test_cabs = [
|
||||
CabinetItem(1, "upper_wall", 762.0/25.4, 300.0/25.4, 330.0/25.4, "Left", "ELEV A", 0.92),
|
||||
CabinetItem(2, "base", 900.0/25.4, 720.0/25.4, 600.0/25.4, "Base", "ELEV A", 0.88),
|
||||
CabinetItem(3, "appliance_space", 610.0/25.4, 720.0/25.4, 600.0/25.4, "DW", "ELEV A", 0.98),
|
||||
]
|
||||
validator = CabinetValidator()
|
||||
result = validator.get_validation_result(test_cabs, room_width_in=None, is_ada=False)
|
||||
|
||||
check("Score > 0.8", result.overall_score > 0.8, f"{result.overall_score:.2f}")
|
||||
check("No critical flags", len(result.flags) == 0, f"{len(result.flags)} flags")
|
||||
|
||||
# ADA test
|
||||
ada_cabs = [
|
||||
CabinetItem(1, "base", 900.0/25.4, 1000.0/25.4, 600.0/25.4, "ADA Base", "ELEV A", 0.9),
|
||||
]
|
||||
ada_result = validator.get_validation_result(ada_cabs, is_ada=True)
|
||||
check("ADA height flag detected", len(ada_result.flags) > 0, f"{ada_result.flags}")
|
||||
|
||||
all_ok = all_ok and result.overall_score > 0.8
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} cabinet_validator error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 6: Price Matcher Fallback ───────────────────
|
||||
print("\n[6] Price Matcher (fallback catalog)")
|
||||
try:
|
||||
from core.price_matcher import get_fallback_price_usd, _generate_code
|
||||
|
||||
check("B36 fallback", get_fallback_price_usd("B36") == 149.0, str(get_fallback_price_usd("B36")))
|
||||
check("VAN60 fallback", get_fallback_price_usd("VAN60") == 310.0, str(get_fallback_price_usd("VAN60")))
|
||||
check("unknown fallback", get_fallback_price_usd("XYZ999") == 2048.0, str(get_fallback_price_usd("XYZ999")))
|
||||
|
||||
code = _generate_code("base", 914.0)
|
||||
check("base 914mm code = B36", code == "B36", code)
|
||||
code2 = _generate_code("vanity", 762.0)
|
||||
check("vanity 762mm code = VAN30", code2 == "VAN30", code2)
|
||||
|
||||
except Exception as e:
|
||||
print(f" {FAIL} price_matcher error: {e}")
|
||||
import traceback; traceback.print_exc()
|
||||
all_ok = False
|
||||
|
||||
# ── Test 7: Unit Counter (manual mode) ───────────────
|
||||
print("\n[7] Unit Counter (manual override)")
|
||||
try:
|
||||
from core.unit_matrix_extractor import load_matrix_from_config
|
||||
matrix = load_matrix_from_config({"A1": 14, "B1": 6}, "Test Project")
|
||||
check("Totals loaded", matrix.totals == {"A1": 14, "B1": 6})
|
||||
check("Confidence = 1.0", matrix.confidence == 1.0)
|
||||
check("Needs review = False", not matrix.needs_review)
|
||||
except Exception as e:
|
||||
print(f" {FAIL} unit_matrix_extractor error: {e}")
|
||||
all_ok = False
|
||||
|
||||
# ── Test 8: PDF Extractor (basic import) ─────────────
|
||||
print("\n[8] PDF Extractor (import test)")
|
||||
try:
|
||||
from core.pdf_extractor import PDFExtractor, TextSpan, VectorRect, PageData
|
||||
check("PDFExtractor imported", True)
|
||||
check("TextSpan imported", True)
|
||||
check("VectorRect imported", True)
|
||||
except Exception as e:
|
||||
print(f" {FAIL} pdf_extractor import error: {e}")
|
||||
all_ok = False
|
||||
|
||||
# ── Test 9: Region Detector (basic import) ───────────
|
||||
print("\n[9] Region Detector (import test)")
|
||||
try:
|
||||
from core.region_detector import RegionDetector, DetectedRegion
|
||||
check("RegionDetector imported", True)
|
||||
check("DetectedRegion imported", True)
|
||||
except Exception as e:
|
||||
print(f" {FAIL} region_detector import error: {e}")
|
||||
all_ok = False
|
||||
|
||||
# ── Summary ───────────────────────────────────────────
|
||||
print("\n" + "=" * 55)
|
||||
if all_ok:
|
||||
print(" ALL TESTS PASSED")
|
||||
else:
|
||||
print(" SOME TESTS FAILED - see above")
|
||||
print("=" * 55)
|
||||
|
||||
assert all_ok, "Some core tests failed"
|
||||
@@ -21,7 +21,7 @@ import sys
|
||||
import os
|
||||
|
||||
# Add project root to path
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from core.engines.constraint_solver import (
|
||||
ConstraintExtractor, ConstraintSolver, WallConstraints,
|
||||
@@ -76,7 +76,7 @@ def test_centered_sink_120():
|
||||
print(f" {p.code:8s} [{p.x_start:.0f}\" - {p.x_end:.0f}\"]")
|
||||
|
||||
# Verify total width
|
||||
total = sum(p.filler_width if p.is_filler else p.width for p in placed)
|
||||
total = sum(p.filler_width if p.is_filler else p.width for p in placed if "upper" not in p.cabinet_type and "shelf" not in p.cabinet_type)
|
||||
print(f"\n Total width: {total:.0f}\" (wall: {wc.wall_length:.0f}\")")
|
||||
assert abs(total - 120.0) < 0.01, f"Total width {total} != 120"
|
||||
|
||||
@@ -127,7 +127,7 @@ def test_empty_wall_90():
|
||||
placed = engine.place_wall(wc)
|
||||
codes = engine.placed_to_codes(placed)
|
||||
|
||||
total = sum(p.filler_width if p.is_filler else p.width for p in placed)
|
||||
total = sum(p.filler_width if p.is_filler else p.width for p in placed if "upper" not in p.cabinet_type and "shelf" not in p.cabinet_type)
|
||||
print(f" Placed: {codes}")
|
||||
print(f" Total: {total:.0f}\"")
|
||||
assert abs(total - 90.0) < 0.01, f"Total width {total} != 90"
|
||||
@@ -161,7 +161,7 @@ def test_wall_with_window():
|
||||
placed = engine.place_wall(wc)
|
||||
codes = engine.placed_to_codes(placed)
|
||||
|
||||
total = sum(p.filler_width if p.is_filler else p.width for p in placed)
|
||||
total = sum(p.filler_width if p.is_filler else p.width for p in placed if "upper" not in p.cabinet_type and "shelf" not in p.cabinet_type)
|
||||
print(f" Placed: {codes}")
|
||||
print(f" Total cabinet: {total:.0f}\" (available: 84\")")
|
||||
assert abs(total - 84.0) < 0.01, f"Total width {total} != 84"
|
||||
@@ -200,7 +200,7 @@ def test_wall_with_ref_and_range():
|
||||
end = p.x_end
|
||||
print(f" {p.code:8s} [{p.x_start:.0f}\" - {end:.0f}\"]")
|
||||
|
||||
total_placed = sum(p.filler_width if p.is_filler else p.width for p in placed)
|
||||
total_placed = sum(p.filler_width if p.is_filler else p.width for p in placed if "upper" not in p.cabinet_type and "shelf" not in p.cabinet_type)
|
||||
available = 168.0 - 36.0 - 30.0 # minus REF and RANGE
|
||||
print(f" Total cabinet: {total_placed:.1f}\" (available: {available:.0f}\")")
|
||||
|
||||
@@ -232,11 +232,13 @@ def test_constraint_extraction():
|
||||
structural=structural,
|
||||
)
|
||||
|
||||
print(f" Obstructions: {len(wc.obstructions)}")
|
||||
print(f" Obstructions (full height): {len(wc.obstructions)}")
|
||||
print(f" Windows: {len(wc.windows)}")
|
||||
print(f" Anchors: {len(wc.anchors)}")
|
||||
print(f" Appliance slots: {len(wc.appliance_slots)}")
|
||||
|
||||
assert len(wc.obstructions) == 1, f"Expected 1 obstruction (window), got {len(wc.obstructions)}"
|
||||
assert len(wc.obstructions) == 0, f"Expected 0 full obstructions, got {len(wc.obstructions)}"
|
||||
assert len(wc.windows) == 1, f"Expected 1 window, got {len(wc.windows)}"
|
||||
assert len(wc.anchors) == 1, f"Expected 1 anchor (sink), got {len(wc.anchors)}"
|
||||
assert len(wc.appliance_slots) == 1, f"Expected 1 appliance slot (REF), got {len(wc.appliance_slots)}"
|
||||
|
||||
@@ -276,4 +278,4 @@ if __name__ == "__main__":
|
||||
print(f"\n ALL {len(results)} TESTS PASSED")
|
||||
else:
|
||||
print(f"\n SOME TESTS FAILED")
|
||||
sys.exit(1)
|
||||
assert False, 'Some tests failed'
|
||||
@@ -0,0 +1,42 @@
|
||||
import pytest
|
||||
from core.units import Length
|
||||
|
||||
def test_length_conversion():
|
||||
# Test from_mm
|
||||
l = Length.from_mm(914.4)
|
||||
assert l.inches == pytest.approx(36.0)
|
||||
assert l.mm == pytest.approx(914.4)
|
||||
|
||||
# Test from_inches
|
||||
l2 = Length.from_inches(24.0)
|
||||
assert l2.inches == 24.0
|
||||
assert l2.mm == pytest.approx(609.6)
|
||||
|
||||
# Test from_cm
|
||||
l3 = Length.from_cm(91.44)
|
||||
assert l3.inches == pytest.approx(36.0)
|
||||
|
||||
def test_length_math():
|
||||
l1 = Length.from_inches(10.0)
|
||||
l2 = Length.from_inches(5.0)
|
||||
|
||||
assert (l1 + l2).inches == 15.0
|
||||
assert (l1 - l2).inches == 5.0
|
||||
assert (l1 * 2).inches == 20.0
|
||||
|
||||
# Test float interop
|
||||
assert (l1 + 5.0).inches == 15.0
|
||||
assert (l1 - 2.5).inches == 7.5
|
||||
|
||||
def test_length_equality():
|
||||
l1 = Length.from_inches(36.0)
|
||||
l2 = Length.from_mm(914.4)
|
||||
assert l1 == l2
|
||||
assert l1 >= l2
|
||||
assert not (l1 < l2)
|
||||
|
||||
def test_length_float_cast():
|
||||
l1 = Length.from_inches(34.5)
|
||||
assert float(l1) == 34.5
|
||||
assert round(l1) == 34
|
||||
assert round(l1, 1) == 34.5
|
||||
@@ -0,0 +1 @@
|
||||
# Manual reference tool scripts.
|
||||
@@ -0,0 +1,109 @@
|
||||
"""
|
||||
tools/generate_yolo_annotations.py
|
||||
|
||||
Auto-generate YOLO annotation .txt files from what the pipeline already knows.
|
||||
Run this first to bootstrap the training dataset, then correct in CVAT/Label Studio.
|
||||
|
||||
Usage:
|
||||
python tools/generate_yolo_annotations.py \
|
||||
--pdf "path/to/architectural.pdf" \
|
||||
--output-dir datasets/floor_plan/ \
|
||||
--dpi 200
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import fitz # PyMuPDF
|
||||
|
||||
from core.pdf_extractor import PDFExtractor
|
||||
from core.region_detector import RegionDetector
|
||||
from core.opening_extractor import OpeningExtractor
|
||||
from core.drawing_classifier import DrawingClassifier
|
||||
|
||||
# Try to import YOLO classes from the central definition, fallback if not found
|
||||
try:
|
||||
from core.yolo_extractor import FLOOR_PLAN_CLASSES
|
||||
except ImportError:
|
||||
FLOOR_PLAN_CLASSES = [
|
||||
"kitchen_region", "bath_region", "sink_symbol", "range_symbol", "dw_symbol",
|
||||
"fridge_symbol", "oven_symbol", "microwave_symbol", "hood_symbol", "pantry_symbol",
|
||||
"vanity_sink_symbol", "toilet_symbol", "bathtub_symbol", "shower_symbol",
|
||||
"shower_door_symbol", "medicine_cabinet_symbol", "linen_closet_symbol", "bidet_symbol",
|
||||
"door_swing", "window_symbol", "structural_column", "soffit_hatch"
|
||||
]
|
||||
|
||||
YOLO_CLASS_IDS = {name: idx for idx, name in enumerate(FLOOR_PLAN_CLASSES)}
|
||||
|
||||
def _to_yolo(bbox_px, page_w_px, page_h_px):
|
||||
"""Convert (x0,y0,x1,y1) pixel coords to YOLO normalized format."""
|
||||
x0, y0, x1, y1 = bbox_px
|
||||
cx = (x0 + x1) / 2 / page_w_px
|
||||
cy = (y0 + y1) / 2 / page_h_px
|
||||
w = (x1 - x0) / page_w_px
|
||||
h = (y1 - y0) / page_h_px
|
||||
return cx, cy, w, h
|
||||
|
||||
def generate_annotations(pdf_path: str, output_dir: str, dpi: int = 200):
|
||||
out = Path(output_dir)
|
||||
(out / "images").mkdir(parents=True, exist_ok=True)
|
||||
(out / "labels").mkdir(parents=True, exist_ok=True)
|
||||
|
||||
print(f"Generating YOLO floor plan annotations for: {pdf_path}")
|
||||
print(f"Output directory: {out}")
|
||||
print(f"DPI: {dpi}")
|
||||
|
||||
scale_factor = dpi / 72.0
|
||||
|
||||
with PDFExtractor(pdf_path) as extractor:
|
||||
for page_idx in range(extractor.page_count):
|
||||
page = extractor.extract_page(page_idx)
|
||||
page_type = DrawingClassifier.classify_page(page.spans)
|
||||
|
||||
if page_type not in ("UNIT PLAN", "FLOOR PLAN"):
|
||||
continue
|
||||
|
||||
# Render page image
|
||||
img_bytes = extractor.render_full_page(page_idx, dpi=dpi)
|
||||
pdf_stem = Path(pdf_path).stem
|
||||
img_name = f"{pdf_stem}_page_{page_idx:04d}"
|
||||
img_path = out / "images" / f"{img_name}.png"
|
||||
img_path.write_bytes(img_bytes)
|
||||
|
||||
import io
|
||||
from PIL import Image
|
||||
with Image.open(io.BytesIO(img_bytes)) as pil_img:
|
||||
page_w_px, page_h_px = pil_img.size
|
||||
|
||||
annotations = []
|
||||
|
||||
# Auto-annotate kitchen/bath regions from RegionDetector
|
||||
detector = RegionDetector(page.spans, page.rects, page.page_w, page.page_h)
|
||||
for region in detector.detect():
|
||||
cls = "kitchen_region" if region.is_kitchen() else "bath_region"
|
||||
if cls in YOLO_CLASS_IDS:
|
||||
# Convert PDF points to pixels for the bbox
|
||||
bbox_px = (
|
||||
region.crop_rect[0] * scale_factor,
|
||||
region.crop_rect[1] * scale_factor,
|
||||
region.crop_rect[2] * scale_factor,
|
||||
region.crop_rect[3] * scale_factor,
|
||||
)
|
||||
yolo_coords = _to_yolo(bbox_px, page_w_px, page_h_px)
|
||||
annotations.append(f"{YOLO_CLASS_IDS[cls]} " + " ".join(f"{v:.6f}" for v in yolo_coords))
|
||||
|
||||
# Future enhancement: Auto-annotate doors/windows from OpeningExtractor VectorRects
|
||||
# (Left for CVAT manual tagging for now, as RegionDetector provides the main structural bounding boxes)
|
||||
|
||||
# Write label file
|
||||
label_path = out / "labels" / f"{img_name}.txt"
|
||||
label_path.write_text("\n".join(annotations))
|
||||
print(f" Page {page_idx}: saved image and {len(annotations)} auto-annotations")
|
||||
|
||||
if __name__ == "__main__":
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--pdf", required=True)
|
||||
parser.add_argument("--output-dir", required=True)
|
||||
parser.add_argument("--dpi", type=int, default=200)
|
||||
args = parser.parse_args()
|
||||
generate_annotations(args.pdf, args.output_dir, args.dpi)
|
||||
@@ -1,3 +1,25 @@
|
||||
"""
|
||||
================================================================================
|
||||
MANUAL REFERENCE TOOL — NOT PART OF THE AUTOMATED pipeline.py PIPELINE.
|
||||
================================================================================
|
||||
This script reproduces a known deliverable by tracing a hand-drafted reference
|
||||
document or writing literal string data. It does NOT read architectural source
|
||||
PDFs through the extraction pipeline.
|
||||
|
||||
It will produce nothing meaningful for a new project that does not already have
|
||||
a completed hand-drafted shop drawing as its source input.
|
||||
|
||||
DO NOT treat output from this script as evidence that pipeline.py works.
|
||||
|
||||
Kept here for:
|
||||
- Reproducing a specific known-good project deliverable quickly
|
||||
- Reference / comparison against the automated pipeline output
|
||||
|
||||
For the real automated pipeline, run:
|
||||
python pipeline.py --project projects/<name>/project_config.json
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
@@ -1,18 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
===========================================================================
|
||||
HERITAGE VILLAGE — PRODUCTION SHOP DRAWINGS COMPILER & RECONSTRUCTOR v1.0
|
||||
===========================================================================
|
||||
This script programmatically compiles the 16-page tabloid shop drawing package:
|
||||
- Page 1: COVER (dynamically generated from project data)
|
||||
- Page 2: MATRIX (dynamically generated from unit quantities)
|
||||
- Pages 3-16: Vector-level reconstruction from the client's 14 unit plan PDFs,
|
||||
separating the drawing graphics from the title blocks, and wrapping each
|
||||
sheet with our dynamic, uniform title block layout.
|
||||
================================================================================
|
||||
MANUAL REFERENCE TOOL — NOT PART OF THE AUTOMATED pipeline.py PIPELINE.
|
||||
================================================================================
|
||||
This script reproduces a known deliverable by tracing a hand-drafted reference
|
||||
document or writing literal string data. It does NOT read architectural source
|
||||
PDFs through the extraction pipeline.
|
||||
|
||||
All CAD elements (lines, arcs, dimensions, text rotation, dashes) are copied
|
||||
with 100% precision, producing a crisp, vector-grade print PDF.
|
||||
===========================================================================
|
||||
It will produce nothing meaningful for a new project that does not already have
|
||||
a completed hand-drafted shop drawing as its source input.
|
||||
|
||||
DO NOT treat output from this script as evidence that pipeline.py works.
|
||||
|
||||
Kept here for:
|
||||
- Reproducing a specific known-good project deliverable quickly
|
||||
- Reference / comparison against the automated pipeline output
|
||||
|
||||
For the real automated pipeline, run:
|
||||
python pipeline.py --project projects/<name>/project_config.json
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import math
|
||||
@@ -1,18 +1,23 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
===========================================================================
|
||||
CASA FAMILIA — PRODUCTION SHOP DRAWINGS COMPILER & RECONSTRUCTOR v5.0
|
||||
===========================================================================
|
||||
This script programmatically reconstructs the 23-page shop drawing package:
|
||||
- Page 1: COVER (dynamically generated from project data)
|
||||
- Page 2: MATRIX (dynamically generated from unit quantities)
|
||||
- Pages 3-23: Vector-level reconstruction from the client's reference PDF,
|
||||
separating the drawing graphics from the title blocks, and wrapping each
|
||||
sheet with our dynamic, uniform title block layout.
|
||||
================================================================================
|
||||
MANUAL REFERENCE TOOL — NOT PART OF THE AUTOMATED pipeline.py PIPELINE.
|
||||
================================================================================
|
||||
This script reproduces a known deliverable by tracing a hand-drafted reference
|
||||
document or writing literal string data. It does NOT read architectural source
|
||||
PDFs through the extraction pipeline.
|
||||
|
||||
All CAD elements (lines, arcs, dimensions, text rotation, dashes) are copied
|
||||
with 100% precision, producing a crisp, vector-grade print PDF.
|
||||
===========================================================================
|
||||
It will produce nothing meaningful for a new project that does not already have
|
||||
a completed hand-drafted shop drawing as its source input.
|
||||
|
||||
DO NOT treat output from this script as evidence that pipeline.py works.
|
||||
|
||||
Kept here for:
|
||||
- Reproducing a specific known-good project deliverable quickly
|
||||
- Reference / comparison against the automated pipeline output
|
||||
|
||||
For the real automated pipeline, run:
|
||||
python pipeline.py --project projects/<name>/project_config.json
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import math
|
||||