feat: Update elevation layout, appliance library, DXF generation, and reorganize tools and scripts

This commit is contained in:
Atharv1705
2026-11-05 12:17:57 +05:30
parent e003fce9d8
commit c460c08ed3
104 changed files with 7095 additions and 697 deletions
+7
View File
@@ -0,0 +1,7 @@
# Analysis scratch
_analysis/
# OS files
.DS_Store
Thumbs.db
desktop.ini
+30
View File
@@ -0,0 +1,30 @@
name: Python CI
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python 3.9
uses: actions/setup-python@v4
with:
python-version: "3.9"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
if [ -f requirements.txt ]; then pip install -r requirements.txt; fi
pip install pytest pytest-cov
- name: Test with pytest
run: |
pytest --cov=core --cov=generators tests/
+27
View File
@@ -0,0 +1,27 @@
name: Tests
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python 3.10
uses: actions/setup-python@v4
with:
python-version: "3.10"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install pytest
- name: Run Pytest for Constraint and Placement Engine
run: |
pytest tests/test_placement.py
+13
View File
@@ -51,13 +51,26 @@ outputs/
# Scratch / one-off inspection scripts (kept on disk, not tracked)
debug.py
debug_*.py
pipeline_debug.py
analyze_config.py
check_vanity.py
update_k4.py
debug.html
temp_*.py
temp_*.pdf
deep_inspect_*.py
inspect_*.py
# Scratch binary artifacts
*.png
test*.pdf
test_merge*.pdf
test_dim.dxf
OUTPUT_ARCH_ANALYSIS.pdf
EXTRACTION_OUTPUT/
shop_review/
# Datasets
data/
datasets/floor_plan_full/
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,141 @@
import os
import json
import fitz
from typing import Dict, Any, List, Optional
from typing_extensions import TypedDict
from dotenv import load_dotenv
from pydantic import BaseModel, Field
from langchain_openai import ChatOpenAI
from langchain_core.messages import HumanMessage, SystemMessage
from langgraph.graph import StateGraph, START, END
from core.agents.config_schema import ExtractedConfigMetadata
load_dotenv()
# State definition
class ExtractionState(TypedDict):
pdf_path: str
extracted_text: str
parsed_config: Optional[ExtractedConfigMetadata]
errors: List[str]
retry_count: int
# Initialize LLM
def get_llm():
return ChatOpenAI(
model="google/gemini-2.5-flash",
api_key=os.environ.get("OPENROUTER_API_KEY"),
base_url="https://openrouter.ai/api/v1",
temperature=0.0
)
def load_document(state: ExtractionState) -> Dict:
"""Extracts text from the first few pages of the PDF, which usually contain the schedules and metadata."""
pdf_path = state["pdf_path"]
text_content = []
try:
doc = fitz.open(pdf_path)
# We only need the first 3-5 pages typically for metadata and schedules
num_pages_to_scan = min(5, len(doc))
for i in range(num_pages_to_scan):
page = doc[i]
text = page.get_text()
text_content.append(f"--- PAGE {i+1} ---\n{text}")
except Exception as e:
return {"errors": state.get("errors", []) + [f"Failed to read PDF: {str(e)}"]}
return {"extracted_text": "\n".join(text_content)}
def llm_extract_data(state: ExtractionState) -> Dict:
"""Uses LangChain with_structured_output to parse the text into our Pydantic schema."""
text = state.get("extracted_text", "")
errors = state.get("errors", [])
if not text:
return {"errors": errors + ["No text available to extract."], "retry_count": state.get("retry_count", 0) + 1}
llm = get_llm()
structured_llm = llm.with_structured_output(ExtractedConfigMetadata)
system_prompt = (
"You are an expert architectural plan parser. Your task is to extract "
"project metadata, appliance schedules, and the unit matrix from the provided raw text "
"extracted from a PDF plan set.\n\n"
"Guidelines:\n"
"- Fill out as many fields as possible based on the text.\n"
"- If a field isn't explicitly found, leave it as default or empty.\n"
"- The 'unit_matrix' contains rows of units and how many vanity/kitchen types they have.\n"
"- The 'buildings' field maps building names (e.g. 'BUILDING TYPE A') to the unit keys they contain.\n"
)
if errors:
last_error = errors[-1]
system_prompt += f"\nPrevious attempt failed with error:\n{last_error}\nPlease correct this issue."
try:
result = structured_llm.invoke([
SystemMessage(content=system_prompt),
HumanMessage(content=text)
])
return {"parsed_config": result, "retry_count": state.get("retry_count", 0) + 1}
except Exception as e:
return {"errors": errors + [f"LLM extraction failed: {str(e)}"], "retry_count": state.get("retry_count", 0) + 1}
def validate_config(state: ExtractionState) -> Dict:
"""Validates the extracted config."""
config: ExtractedConfigMetadata = state.get("parsed_config")
errors = state.get("errors", [])
if not config:
return {"errors": errors + ["Parsed config is None"]}
new_errors = []
# Check if unit_matrix has at least one row
if not config.unit_matrix:
new_errors.append("Unit matrix is empty. Expected at least one row.")
else:
# Populate auto-computed unit_counts
config.unit_counts = {row.key: row.qty for row in config.unit_matrix}
return {"errors": errors + new_errors, "parsed_config": config}
def should_continue(state: ExtractionState) -> str:
"""Routing logic after validation."""
errors = state.get("errors", [])
retry_count = state.get("retry_count", 0)
if errors and retry_count < 3:
return "retry"
return "end"
def build_extractor_graph():
"""Builds and returns the LangGraph state machine."""
builder = StateGraph(ExtractionState)
builder.add_node("load_document", load_document)
builder.add_node("llm_extract_data", llm_extract_data)
builder.add_node("validate_config", validate_config)
builder.add_edge(START, "load_document")
builder.add_edge("load_document", "llm_extract_data")
builder.add_edge("llm_extract_data", "validate_config")
builder.add_conditional_edges(
"validate_config",
should_continue,
{
"retry": "llm_extract_data",
"end": END
}
)
return builder.compile()
+1 -1
View File
@@ -785,7 +785,7 @@ def _downscale_image_if_possible(image_bytes: bytes, target_dpi: int = 150) -> b
new_w = max(1, int(orig_w * scale))
new_h = max(1, int(orig_h * scale))
img_resized = img.resize((new_w, new_h), Image.LANCZOS)
img_resized = img.resize((new_w, new_h), Image.Resampling.LANCZOS)
buf = _io.BytesIO()
img_resized.save(buf, format="PNG", optimize=True)
result = buf.getvalue()
+59 -25
View File
@@ -4,6 +4,12 @@
===========================================================================
Constructs the spatial layout graph of cabinets, appliances, and openings.
Calculates offsets, identifies adjacency, and builds the target schemas.
Invariant: base-vs-upper is a first-class field all the way to the output.
Each cabinet dict carries a "tier" key ("base" | "upper") and the wall
dict uses two separate keys — "cabinets" (base run) and "uppers" (upper
run) — matching the shape of project_config.json and _draw_elevation_view.
The merged flat-list that discarded tier info has been removed.
===========================================================================
"""
from __future__ import annotations
@@ -75,16 +81,23 @@ class CabinetGraphBuilder:
else:
base_items.append(cab_dict)
# Sequence base run
# ── Tier 1: base run — cursor from x=0 ───────────────────────
base_x = 0
tall_right_x = 0 # right edge of REF/tall column (upper cursor origin)
sequenced_base_cabs = []
for b in base_items:
b["x"] = base_x
b["tier"] = "base" # ← preserve tier all the way to output
sequenced_base_cabs.append(b)
# If it's an appliance space, also add it to the appliances list
# Track REF/tall right edge so upper cursor starts correctly
is_tall = any(kw in (b.get("cabinet_type", "") + b["id"]).lower()
for kw in ("ref", "tall", "pantry", "refrigerator"))
if is_tall:
tall_right_x = max(tall_right_x, base_x + b["width"])
# Appliance spaces → also add to the appliances list
if b["type"] == "appliance_space" or b["cabinet_type"] == "appliance_space":
# Determine type of appliance
app_type = "REF"
for t in ["REF", "DW", "RANGE", "MIC", "HOOD", "OVEN"]:
if t in b["notes"].upper() or t in b["id"].upper():
@@ -98,25 +111,42 @@ class CabinetGraphBuilder:
})
base_x += b["width"]
# Sequence upper run
upper_x = 0
# ── Tier 2: upper run — cursor starts at REF/tall right edge ─
# (matches ElevationLayout.build_two_tier() behaviour)
upper_x = tall_right_x
sequenced_upper_cabs = []
for u in upper_items:
u["x"] = upper_x
u["tier"] = "upper" # ← preserve tier all the way to output
sequenced_upper_cabs.append(u)
upper_x += u["width"]
# Combine all sequenced cabinets
# Standardize output cabinets format: id, x, width, height
all_cabs_output = []
for c in sequenced_base_cabs + sequenced_upper_cabs:
if c["type"] != "appliance_space":
all_cabs_output.append({
"id": c["id"],
"x": c["x"],
"width": c["width"],
"height": c["height"]
})
# ── Emit two separate lists (base/uppers) not one merged list ─
# Shape matches project_config.json and _draw_elevation_view so
# all downstream consumers see "cabinets" (base) + "uppers" (upper)
# and can distinguish the two tiers without ambiguity.
base_output = [
{
"id": c["id"],
"x": c["x"],
"width": c["width"],
"height": c["height"],
"tier": "base",
}
for c in sequenced_base_cabs
if c["type"] != "appliance_space"
]
upper_output = [
{
"id": c["id"],
"x": c["x"],
"width": c["width"],
"height": c["height"],
"tier": "upper",
}
for c in sequenced_upper_cabs
if c["type"] != "appliance_space"
]
# Process openings
doors_output = []
@@ -136,16 +166,20 @@ class CabinetGraphBuilder:
"sill_height": w.get("sill_height_in", 36)
})
wall_length = max(base_x, upper_x)
# wall_length = base run end (authoritative).
# Do NOT use max(base_x, upper_x): upper_x starts at tall_right_x
# and its final value exceeds wall bounds if uppers fill past the base run.
wall_length = base_x
if wall_length == 0:
wall_length = 90.0 # default wall length
walls_list.append({
"name": wall_name,
"length": wall_length,
"doors": doors_output,
"name": wall_name,
"length": wall_length,
"doors": doors_output,
"windows": windows_output,
"cabinets": all_cabs_output
"cabinets": base_output, # base run
"uppers": upper_output, # upper run — separate key, not merged
})
# Try to parse appliances list directly from elevations if none added from base run
@@ -156,10 +190,10 @@ class CabinetGraphBuilder:
wall_name = "A"
for app in ev.appliances:
appliances_list.append({
"type": app.get("type", "REF"),
"type": getattr(app, "type", "REF"),
"wall": wall_name,
"x": app.get("x_in", 0),
"width": app.get("width_in", 36)
"x": getattr(app, "x_in", 0),
"width": getattr(app, "width_in", 36)
})
# Normalize layout shape
+152 -23
View File
@@ -34,72 +34,103 @@ class ApplianceLibrary:
# ─────────────────────────────────────────────────────────────────────
@staticmethod
def draw_refrigerator_elevation(x0: float, y0: float, width: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
def draw_refrigerator_elevation(x0: float, y0: float, width: float, height: float = 72.0, scale_x: float = 4.0, scale_y: float = 3.0, label: str = "REF") -> Dict[str, List]:
"""Draws a refrigerator in elevation view."""
geom = {"lines": [], "blocks": [], "texts": []}
geom = {"lines": [], "blocks": [], "texts": [], "block_refs": []}
x1 = x0 + width * scale_x
y1 = y0 + 72.0 * scale_y # Ref height typically 72"
y1 = y0 + height * scale_y
# Standard DXF block ref
geom["block_refs"].append({
"name": "REF_BLOCK",
"coords": [x0, y0],
"scale": [width * scale_x, height * scale_y],
"layer": "APPLIANCES"
})
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "REF", "layer": "APPLIANCES", "style": "solid"
"id": "REF", "layer": "APPLIANCES", "style": "solid",
"is_legacy_appliance": True
})
# Doors divide
mid_x = x0 + (width / 2.0) * scale_x
geom["lines"].append({"start": [mid_x, y0], "end": [mid_x, y1], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [mid_x, y0], "end": [mid_x, y1], "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True})
# Handles
h_start_y = y0 + 30.0 * scale_y
h_end_y = y0 + 48.0 * scale_y
geom["lines"].append({"start": [mid_x - 1.5, h_start_y], "end": [mid_x - 1.5, h_end_y], "layer": "HANDLES", "style": "solid"})
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", "is_legacy_appliance": True})
geom["lines"].append({"start": [mid_x + 1.5, h_start_y], "end": [mid_x + 1.5, h_end_y], "layer": "HANDLES", "style": "solid", "is_legacy_appliance": True})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2], "text": "REF", "size": 4.5, "layer": "TEXT"})
# Format label to avoid spilling
import re
label = re.sub(r'(?i)refrigerator', 'REF', label).upper()
lines = label.split("\n")
for i, ln in enumerate(reversed(lines)):
geom["texts"].append({"pos": [(x0 + x1) / 2, ((y0 + y1) / 2) + i * 15], "text": ln, "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_dishwasher_elevation(x0: float, y0: float, width: float, height: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
geom = {"lines": [], "blocks": [], "texts": [], "block_refs": []}
x1 = x0 + width * scale_x
y1 = y0 + height * scale_y
geom["block_refs"].append({
"name": "DW_BLOCK",
"coords": [x0, y0],
"scale": [width * scale_x, height * scale_y],
"layer": "APPLIANCES"
})
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "D/W", "layer": "APPLIANCES", "style": "solid"
"id": "D/W", "layer": "APPLIANCES", "style": "solid",
"is_legacy_appliance": True
})
# Control panel
geom["lines"].append({"start": [x0, y1 - 4.0 * scale_y], "end": [x1, y1 - 4.0 * scale_y], "layer": "APPLIANCES", "style": "solid"})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2 - 2.0 * scale_y], "text": "D/W\nS.S", "size": 4.5, "layer": "TEXT"})
geom["lines"].append({"start": [x0, y1 - 4.0 * scale_y], "end": [x1, y1 - 4.0 * scale_y], "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True})
geom["texts"].append({"pos": [(x0 + x1) / 2, (y0 + y1) / 2 - 2.0 * scale_y], "text": "D/W S.S", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_range_elevation(x0: float, y0: float, width: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": []}
geom = {"lines": [], "blocks": [], "texts": [], "block_refs": []}
x1 = x0 + width * scale_x
y1_stove = y0 + 36.0 * scale_y
geom["block_refs"].append({
"name": "RANGE_BLOCK",
"coords": [x0, y0],
"scale": [width * scale_x, 36.0 * scale_y],
"layer": "APPLIANCES"
})
# Main body
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1_stove - y0],
"id": "STOVE", "layer": "APPLIANCES", "style": "solid"
"id": "STOVE", "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True
})
# Bottom warming drawer
geom["lines"].append({"start": [x0, y0 + 8.0 * scale_y], "end": [x1, y0 + 8.0 * scale_y], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [x0, y0 + 8.0 * scale_y], "end": [x1, y0 + 8.0 * scale_y], "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True})
# Glass window
geom["blocks"].append({
"type": "rect",
"coords": [x0 + 4.0 * scale_x, y0 + 12.0 * scale_y, (width - 8.0) * scale_x, 14.0 * scale_y],
"id": "", "layer": "APPLIANCES", "style": "solid"
"id": "", "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True
})
# Control panel
geom["lines"].append({"start": [x0, y1_stove - 4.0 * scale_y], "end": [x1, y1_stove - 4.0 * scale_y], "layer": "APPLIANCES", "style": "solid"})
geom["lines"].append({"start": [x0, y1_stove - 4.0 * scale_y], "end": [x1, y1_stove - 4.0 * scale_y], "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True})
# Knobs
for i in range(1, 5):
@@ -107,7 +138,7 @@ class ApplianceLibrary:
geom["blocks"].append({
"type": "rect",
"coords": [kx - 1.0, y1_stove - 3.0 * scale_y, 2.0, 2.0 * scale_y],
"id": "", "layer": "APPLIANCES", "style": "solid"
"id": "", "layer": "APPLIANCES", "style": "solid", "is_legacy_appliance": True
})
return geom
@@ -181,14 +212,83 @@ class ApplianceLibrary:
@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 kitchen sink bowl in elevation behind base cabinets."""
geom = {"lines": [], "blocks": [], "texts": []}
"""Draws a sink bowl (dashed) and a faucet (solid) on the countertop in elevation."""
geom = {"lines": [], "blocks": [], "texts": [], "block_refs": []}
x1 = x0 + width * scale_x
cx = (x0 + x1) / 2.0
sink_d = 8.0 * scale_y
geom["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"})
geom["block_refs"].append({
"name": "SINK_BLOCK",
"coords": [cx, y1], # Insertion point is top-center of the counter
"scale": [width * scale_x, sink_d],
"layer": "SINK"
})
# Sink bowl (dashed, behind the cabinet face)
geom["lines"].append({"start": [x0 + 3.0 * scale_x, y1], "end": [x0 + 3.0 * scale_x, y1 - sink_d], "layer": "SINK", "style": "dashed", "is_legacy_appliance": True})
geom["lines"].append({"start": [x0 + 3.0 * scale_x, y1 - sink_d], "end": [x1 - 3.0 * scale_x, y1 - sink_d], "layer": "SINK", "style": "dashed", "is_legacy_appliance": True})
geom["lines"].append({"start": [x1 - 3.0 * scale_x, y1 - sink_d], "end": [x1 - 3.0 * scale_x, y1], "layer": "SINK", "style": "dashed", "is_legacy_appliance": True})
# Faucet base on top of counter
faucet_h = 4.0 * scale_y
faucet_w = 1.0 * scale_x
geom["lines"].append({"start": [cx - faucet_w, y1], "end": [cx - faucet_w, y1 + faucet_h], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [cx + faucet_w, y1], "end": [cx + faucet_w, y1 + faucet_h], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [cx - faucet_w, y1 + faucet_h], "end": [cx + faucet_w, y1 + faucet_h], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
# Faucet spout (arching over)
spout_w = 4.0 * scale_x
geom["lines"].append({"start": [cx - faucet_w, y1 + faucet_h], "end": [cx - spout_w, y1 + faucet_h + 2.0 * scale_y], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [cx - spout_w, y1 + faucet_h + 2.0 * scale_y], "end": [cx - spout_w, y1 + 1.0 * scale_y], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
# Faucet handles
geom["lines"].append({"start": [cx - faucet_w - 2.0 * scale_x, y1 + 1.0 * scale_y], "end": [cx - faucet_w, y1 + 1.0 * scale_y], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
geom["lines"].append({"start": [cx + faucet_w, y1 + 1.0 * scale_y], "end": [cx + faucet_w + 2.0 * scale_x, y1 + 1.0 * scale_y], "layer": "FAUCET", "style": "solid", "is_legacy_appliance": True})
return geom
@staticmethod
def draw_toilet_elevation(x0: float, y0: float, width: float, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""Draws a standard toilet in elevation view (tank + bowl)."""
geom = {"lines": [], "blocks": [], "texts": []}
cx = x0 + (width / 2.0) * scale_x
# Toilet Tank (centered, approx 16" wide, 14" high, starting 15" from floor)
tank_w = 16.0 * scale_x
tank_h = 14.0 * scale_y
tank_y = y0 + 15.0 * scale_y
geom["blocks"].append({
"type": "rect",
"coords": [cx - tank_w/2.0, tank_y, tank_w, tank_h],
"id": "TOILET_TANK", "layer": "FIXTURES", "style": "solid"
})
# Toilet Bowl Base (approx 10" wide, 15" high from floor)
base_w = 10.0 * scale_x
base_h = 15.0 * scale_y
geom["blocks"].append({
"type": "rect",
"coords": [cx - base_w/2.0, y0, base_w, base_h],
"id": "TOILET_BASE", "layer": "FIXTURES", "style": "solid"
})
# Toilet Seat/Lid line (horizontal line at 15" height, slightly wider than base)
seat_w = 14.0 * scale_x
geom["blocks"].append({
"type": "rect",
"coords": [cx - seat_w/2.0, y0 + base_h, seat_w, 1.5 * scale_y],
"id": "TOILET_SEAT", "layer": "FIXTURES", "style": "solid"
})
# Flush handle
geom["blocks"].append({
"type": "rect",
"coords": [cx + tank_w/2.0 - 3.0*scale_x, tank_y + tank_h - 3.0*scale_y, 2.0*scale_x, 1.0*scale_y],
"id": "TOILET_HANDLE", "layer": "FIXTURES", "style": "solid"
})
geom["texts"].append({"pos": [cx, y0 + 5.0 * scale_y], "text": "TOILET", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
@@ -299,6 +399,35 @@ class ApplianceLibrary:
geom["texts"].append({"pos": [cx, y0 + tank_h + bowl_h / 2], "text": "WC", "size": 3.0, "layer": "TEXT"})
return geom
@staticmethod
def draw_bathtub_elevation(x0: float, y0: float, width: float, height: float = 45.0, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
"""Draws a standard bathtub profile in elevation view."""
geom = {"blocks": [], "lines": [], "texts": []}
w_pt = width * scale_x
h_pt = height * scale_y
# Tub outline
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, w_pt, h_pt],
"layer": "FIXTURES",
"style": "solid"
})
# Lip/Edge line near the top (about 2 inches down)
geom["lines"].append({
"start": [x0, y0 + h_pt - 2.0 * scale_y],
"end": [x0 + w_pt, y0 + h_pt - 2.0 * scale_y],
"layer": "FIXTURES",
"style": "continuous"
})
# Label "TUB BY OTHERS"
cx = x0 + w_pt / 2.0
geom["texts"].append({"pos": [cx, y0 + h_pt/2.0 + 3.0*scale_y], "text": "TUB BY", "size": 4.5, "layer": "TEXT"})
geom["texts"].append({"pos": [cx, y0 + h_pt/2.0 - 2.0*scale_y], "text": "OTHERS", "size": 4.5, "layer": "TEXT"})
return geom
@staticmethod
def draw_bathtub_plan(x0: float, y0: float, width: float = 32.0, length: float = 60.0, scale_x: float = 4.0, scale_y: float = 4.0) -> Dict[str, List]:
"""
+84 -16
View File
@@ -23,6 +23,21 @@ class CabinetRendererFactory:
# Just return the solid box for a filler or panel, no doors/drawers
return geom
if render_style == 'section':
# Section cut: no face frame, just shelves.
# 1 shelf for base, 2 for upper/tall.
num_shelves = 2 if is_upper or is_pantry else 1
shelf_h = cab_h / (num_shelves + 1)
for i in range(1, num_shelves + 1):
sy = y0 + i * shelf_h
geom["lines"].append({
"start": [x0, sy],
"end": [x1, sy],
"layer": layer,
"style": "solid"
})
return geom
# 1.5 Face Frame Inner Edge (1.5" frame width)
frame_w = 1.5 * scale_x
geom["blocks"].append({
@@ -75,28 +90,81 @@ class CabinetRendererFactory:
dy_drawer = y1 - frame_w - drawer_h
gap = 0.125 * scale_x
# Drawer Front
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, dy_drawer + gap, (x1 - x0) - 2*(frame_w + gap), drawer_h - 2*gap],
"layer": "DOOR_PANEL",
"style": "solid"
})
# Drawer Handle
hy = dy_drawer + drawer_h/2
geom["lines"].append({
"start": [(x0 + x1)/2 - 3.0 * scale_x, hy],
"end": [(x0 + x1)/2 + 3.0 * scale_x, hy],
"layer": "HANDLES", "style": "solid"
})
if cab_w > 21.0:
# Double top drawers
xm = (x0 + x1) / 2
# Left Drawer
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, dy_drawer + gap, (xm - x0) - frame_w - 2*gap, drawer_h - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Left Drawer Handle
hy = dy_drawer + drawer_h/2
geom["lines"].append({"start": [(x0 + xm)/2 - 3.0 * scale_x, hy], "end": [(x0 + xm)/2 + 3.0 * scale_x, hy], "layer": "HANDLES", "style": "solid"})
# Right Drawer
geom["blocks"].append({
"type": "rect",
"coords": [xm + gap, dy_drawer + gap, (x1 - xm) - frame_w - 2*gap, drawer_h - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Right Drawer Handle
geom["lines"].append({"start": [(xm + x1)/2 - 3.0 * scale_x, hy], "end": [(xm + x1)/2 + 3.0 * scale_x, hy], "layer": "HANDLES", "style": "solid"})
else:
# Single top drawer
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, dy_drawer + gap, (x1 - x0) - 2*(frame_w + gap), drawer_h - 2*gap],
"layer": "DOOR_PANEL",
"style": "solid"
})
# Drawer Handle
hy = dy_drawer + drawer_h/2
geom["lines"].append({
"start": [(x0 + x1)/2 - 3.0 * scale_x, hy],
"end": [(x0 + x1)/2 + 3.0 * scale_x, hy],
"layer": "HANDLES", "style": "solid"
})
# Drawer separator line
geom["lines"].append({"start": [x0 + frame_w, dy_drawer], "end": [x1 - frame_w, dy_drawer], "layer": layer, "style": "solid"})
y1_door = dy_drawer
# Doors
gap = 0.125 * scale_x
if cab_w > 21.0:
if is_pantry:
# Tall cabinets have split doors (upper and lower)
split_y = y0 + 34.5 * scale_y # typically matches counter height
# Lower door
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, y0 + frame_w + gap, (x1 - x0) - 2*frame_w - 2*gap, (split_y - y0) - frame_w - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Upper door
geom["blocks"].append({
"type": "rect",
"coords": [x0 + frame_w + gap, split_y + gap, (x1 - x0) - 2*frame_w - 2*gap, (y1_door - split_y) - frame_w - 2*gap],
"layer": "DOOR_PANEL", "style": "solid"
})
# Split line
geom["lines"].append({"start": [x0 + frame_w, split_y], "end": [x1 - frame_w, split_y], "layer": layer, "style": "solid"})
# Swings Lower
geom["lines"].append({"start": [x0 + frame_w, y0 + frame_w], "end": [x1 - frame_w, split_y - gap], "layer": "SWING", "style": "dashed"})
geom["lines"].append({"start": [x0 + frame_w, split_y - gap], "end": [x1 - frame_w, y0 + frame_w], "layer": "SWING", "style": "dashed"})
# Swings Upper
geom["lines"].append({"start": [x0 + frame_w, split_y + gap], "end": [x1 - frame_w, y1_door], "layer": "SWING", "style": "dashed"})
geom["lines"].append({"start": [x0 + frame_w, y1_door], "end": [x1 - frame_w, split_y + gap], "layer": "SWING", "style": "dashed"})
# Handles
xm = (x0 + x1) / 2
geom["lines"].append({"start": [xm - 5.0 * scale_x, split_y - 7.0 * scale_y], "end": [xm - 5.0 * scale_x, split_y - 2.0 * scale_y], "layer": "HANDLES", "style": "solid"})
geom["lines"].append({"start": [xm - 5.0 * scale_x, split_y + 2.0 * scale_y], "end": [xm - 5.0 * scale_x, split_y + 7.0 * scale_y], "layer": "HANDLES", "style": "solid"})
elif cab_w > 21.0:
# Double door
xm = (x0 + x1) / 2
# Left Door
@@ -0,0 +1,135 @@
"""
config_validator.py
====================
Validates project_config.json before any PDF/DXF generation runs.
Checks performed:
1. Cabinet width sum vs wall length (phantom cabinet detection)
- Iterates every kitchen type, every wall (wall_a, wall_b).
- Sums base cabinet width_cm and compares against wall length_cm.
- Raises ConfigValidationError on overflow; logs a WARNING on underflow
(gap fill may be intentional).
2. Skips wall_b cleanly if absent or has no length_cm (single-wall layouts).
Usage:
from core.engines.config_validator import validate_config
validate_config(config) # raises ConfigValidationError if invalid
# or
errors = validate_config(config, raise_on_error=False)
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Optional
logger = logging.getLogger(__name__)
TOLERANCE_CM = 0.5 # allow up to 0.5 cm floating-point slack
class ConfigValidationError(ValueError):
"""Raised when project_config.json fails validation."""
def _validate_wall(
wall: dict,
wall_key: str,
kitchen_key: str,
errors: list,
warnings: list,
) -> None:
"""Check that base cabinet widths don't exceed the wall length."""
length_cm: Optional[float] = wall.get("length_cm")
cabinets: list = wall.get("cabinets", [])
# Skip walls with no length specified (valid for empty/single-wall layouts)
if length_cm is None:
return
total_cabinet_cm = sum(cab.get("width_cm", 0.0) for cab in cabinets)
overflow = total_cabinet_cm - length_cm
if overflow > TOLERANCE_CM:
errors.append(
f"[{kitchen_key} / {wall_key}] Cabinet total {total_cabinet_cm:.2f} cm "
f"EXCEEDS wall length {length_cm:.2f} cm by {overflow:.2f} cm. "
f"({len(cabinets)} cabinet(s) listed)"
)
elif (length_cm - total_cabinet_cm) > 10.0:
# Large gap may indicate a missing cabinet entry — warn but don't block
warnings.append(
f"[{kitchen_key} / {wall_key}] Cabinet total {total_cabinet_cm:.2f} cm is "
f"{length_cm - total_cabinet_cm:.2f} cm UNDER wall length {length_cm:.2f} cm. "
f"Verify this gap is intentional (filler / open area)."
)
def validate_config(config: dict, raise_on_error: bool = True) -> list[str]:
"""
Validate the project config dict.
Parameters
----------
config : The loaded project_config.json dict.
raise_on_error : If True, raises ConfigValidationError on first failure batch.
If False, returns a list of error strings (empty = clean).
Returns
-------
List of error strings (empty if clean).
"""
errors: list[str] = []
warnings: list[str] = []
kitchen_types: dict = config.get("kitchen_types", {})
if not kitchen_types:
warnings.append("No 'kitchen_types' key found in config — skipping wall validation.")
logger.warning("No kitchen_types in config.")
for k_key, k_data in kitchen_types.items():
for wall_key in ("wall_a", "wall_b"):
wall = k_data.get(wall_key)
if not wall:
continue # wall_b absent on single-wall layouts — skip cleanly
_validate_wall(wall, wall_key, k_key, errors, warnings)
for w in warnings:
logger.warning(w)
if errors:
msg = "\n ".join(["ConfigValidationError — layout issues detected:"] + errors)
if raise_on_error:
raise ConfigValidationError(msg)
logger.error(msg)
return errors
def validate_config_file(path: Path | str, raise_on_error: bool = True) -> list[str]:
"""Convenience wrapper — loads JSON from path and validates."""
with open(path, encoding="utf-8") as f:
config = json.load(f)
return validate_config(config, raise_on_error=raise_on_error)
# ── CLI self-test ─────────────────────────────────────────────────────────────
if __name__ == "__main__":
import sys
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
config_path = Path(sys.argv[1]) if len(sys.argv) > 1 else (
Path(__file__).parents[2] / "Casa familia" / "project_config.json"
)
print(f"Validating: {config_path}")
errs = validate_config_file(config_path, raise_on_error=False)
if errs:
print(f"\n[FAIL] {len(errs)} error(s) found:")
for e in errs:
print(f" * {e}")
sys.exit(1)
else:
print("[OK] Config is valid -- no cabinet overflow detected.")
sys.exit(0)
@@ -95,6 +95,7 @@ class WallConstraints:
available_runs: List[AvailableRun] = field(default_factory=list)
windows: List[Obstruction] = field(default_factory=list)
is_ada: bool = False
issues: List[str] = field(default_factory=list)
# Standard clearance depths for bathroom fixtures (inches).
# Toilet: 30" clear in front (ADA: 48").
+154 -36
View File
@@ -1,86 +1,204 @@
from typing import Dict, List
class DimensionEngine:
"""Generates standard CAD-compatible dimension objects."""
# ─────────────────────────────────────────────────────────────────────
# Formatting utility — single source of truth for all dimension labels
# ─────────────────────────────────────────────────────────────────────
@staticmethod
def generate_horizontal_chain(components: List[Dict], start_x: float, y_pos: float, scale: float = 1.0) -> List[Dict]:
"""Generates continuous chain dimensions for a row of components with collision avoidance."""
def format_dimension(inches: float) -> str:
"""
Convert a raw float in inches to a clean architectural label.
Rules:
- Round to the nearest 1/16"
- Format as: [feet'-inches fraction"]
e.g. 30.0 → 2'-6"
36.0 → 3'-0"
18.5 → 1'-6 1/2"
0.5 → 1/2"
29.9999→ 2'-6" (float safety)
Never outputs a raw decimal.
"""
# Guard
if inches < 0:
inches = 0.0
# Round to nearest 1/16"
sixteenths = round(inches * 16)
feet = sixteenths // 192 # 16 * 12 = 192 sixteenths per foot
rem16 = sixteenths % 192
whole_in = rem16 // 16
frac16 = rem16 % 16
# Fraction string
def _frac(f: int) -> str:
if f == 0: return ""
if f % 8 == 0: return f"{f // 8}/2"
if f % 4 == 0: return f"{f // 4}/4"
if f % 2 == 0: return f"{f // 2}/8"
return f"{f}/16"
frac_str = _frac(frac16)
if feet > 0:
if whole_in == 0 and not frac_str:
return f"{feet}'-0\""
elif not frac_str:
return f"{feet}'-{whole_in}\""
else:
return f"{feet}'-{whole_in} {frac_str}\""
else:
if whole_in == 0 and not frac_str:
return '0"'
elif not frac_str:
return f'{whole_in}"'
else:
return f'{whole_in} {frac_str}"'
# ─────────────────────────────────────────────────────────────────────
# Dimension generators
# ─────────────────────────────────────────────────────────────────────
@staticmethod
def generate_horizontal_chain(
components: List[Dict], start_x: float, y_pos: float, scale: float = 1.0
) -> List[Dict]:
"""
Generates continuous chain dimensions for a row of components.
Labels are formatted via format_dimension() — never raw floats.
Narrow segments are staggered vertically to avoid collision.
"""
dims = []
current_x = start_x
toggle_offset = False
for comp in components:
width = float(comp.get('width', 0))
width = float(comp.get("width", 0))
is_blank = comp.get("blank", False)
if width > 0:
scaled_width = width * scale
# Collision Avoidance: Stagger narrow dimensions vertically
if scaled_width < 18.0:
current_y_pos = y_pos + (12.0 * scale if toggle_offset else 0.0)
toggle_offset = not toggle_offset
else:
current_y_pos = y_pos
toggle_offset = False
dims.append({
"start": [current_x, current_y_pos],
"end": [current_x + scaled_width, current_y_pos],
"text": f'{width}"'
})
current_x += scaled_width
if not is_blank:
# Stagger if the segment is narrow (e.g., filler or panel < 12cm = 4.7 inches)
# But actually, let's stagger anything < 15.0cm just in case.
current_y_pos = y_pos
if width < 20.0:
if toggle_offset:
current_y_pos += 8.0 # Push up
else:
current_y_pos -= 8.0 # Push down
toggle_offset = not toggle_offset
dims.append({
"start": [current_x, current_y_pos],
"end": [current_x + scaled_width, current_y_pos],
"text": DimensionEngine.format_dimension(width),
})
current_x += scaled_width
return dims
@staticmethod
def generate_overall_dimensions(start_pos: List[float], end_pos: List[float], total_width: float) -> Dict:
def generate_vertical_chain(
components: List[Dict], x_pos: float, start_y: float, scale: float = 1.0
) -> List[Dict]:
"""
Generates continuous chain dimensions vertically.
Components should provide 'height' instead of 'width'.
"""
dims = []
current_y = start_y
toggle_offset = False
for comp in components:
height = float(comp.get("height", 0))
if height > 0:
scaled_height = height * scale
current_x_pos = x_pos
dims.append({
"start": [current_x_pos, current_y],
"end": [current_x_pos, current_y + scaled_height],
"text": DimensionEngine.format_dimension(height),
})
current_y += scaled_height
return dims
@staticmethod
def generate_overall_dimensions(
start_pos: List[float], end_pos: List[float], total_width: float
) -> Dict:
"""Generates the overall total dimension line."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{total_width}\""
"end": end_pos,
"text": DimensionEngine.format_dimension(total_width),
}
@staticmethod
def generate_vertical_dimensions(start_pos: List[float], end_pos: List[float], total_height: float) -> Dict:
def generate_vertical_dimensions(
start_pos: List[float], end_pos: List[float], total_height: float
) -> Dict:
"""Generates overall vertical dimension."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{total_height}\""
"end": end_pos,
"text": DimensionEngine.format_dimension(total_height),
}
@staticmethod
def generate_opening_dimensions(start_pos: List[float], end_pos: List[float], width: float, label: str = "OPENING") -> Dict:
def generate_opening_dimensions(
start_pos: List[float], end_pos: List[float], width: float, label: str = "OPENING"
) -> Dict:
"""Generates dimension for appliance/fixture openings."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{width}\" {label}"
"end": end_pos,
"text": f"{DimensionEngine.format_dimension(width)} {label}",
}
@staticmethod
def generate_countertop_dimensions(start_pos: List[float], end_pos: List[float], width: float) -> Dict:
def generate_countertop_dimensions(
start_pos: List[float], end_pos: List[float], width: float
) -> Dict:
"""Generates countertop specific dimensions including overhangs."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{width}\" C.TOP"
"end": end_pos,
"text": f"{DimensionEngine.format_dimension(width)} C.TOP",
}
@staticmethod
def generate_appliance_dimensions(start_pos: List[float], end_pos: List[float], width: float, label: str) -> Dict:
def generate_appliance_dimensions(
start_pos: List[float], end_pos: List[float], width: float, label: str
) -> Dict:
"""Generates specific appliance dimension callouts."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{width}\" {label}"
"end": end_pos,
"text": f"{DimensionEngine.format_dimension(width)} {label}",
}
@staticmethod
def generate_clearance_dimensions(start_pos: List[float], end_pos: List[float], width: float, required_clearance: float) -> Dict:
def generate_clearance_dimensions(
start_pos: List[float],
end_pos: List[float],
width: float,
required_clearance: float,
) -> Dict:
"""Generates clearance dimensions for ADA validation."""
return {
"start": start_pos,
"end": end_pos,
"text": f"{width}\" CLR (MIN {required_clearance}\")"
"end": end_pos,
"text": (
f"{DimensionEngine.format_dimension(width)} CLR "
f"(MIN {DimensionEngine.format_dimension(required_clearance)})"
),
}
+264 -107
View File
@@ -1,146 +1,303 @@
"""
===========================================================================
core/engines/elevation_generator.py — Kitchen/Vanity Elevation Generator
===========================================================================
Generates elevation geometry for one or more walls.
Architecture (post-refactor):
- Each wall dict carries two SEPARATE cabinet lists:
"base_cfg" — base/tall/appliance cabinets
"upper_cfg" — wall/upper cabinets
These are passed to ElevationLayout.build_two_tier(), which runs two
independent cursors so uppers are never misplaced off the wall.
- Shared reference lines computed once per elevation via RefLines.
- ElevationLayout.validate() runs before rendering and embeds a visible
warning on the drawing instead of crashing the whole PDF pipeline.
- All dimension labels go through DimensionEngine.format_dimension() —
no raw floats ever reach the renderer.
- Elevation title is placed ABOVE the wall border (ceiling_y + 12")
so it never collides with the bottom dimension chain.
===========================================================================
"""
from __future__ import annotations
from typing import Dict, List, Any
from core.engines.appliance_library import ApplianceLibrary
from core.engines.dimension_engine import DimensionEngine
from core.engines.cabinet_renderer import CabinetRendererFactory
from core.engines.cabinet_library_resolver import CabinetLibraryResolver
from core.engines.elevation_layout import ElevationLayout
class ElevationGenerator:
"""Generates the Kitchen/Vanity Elevation geometry."""
@staticmethod
def generate(walls: List[Dict], start_ox: float, start_oy: float, ceiling_height: float = 108.0, scale_x: float = 4.0, scale_y: float = 3.0) -> Dict[str, List]:
geom = {"lines": [], "blocks": [], "texts": [], "dimensions": []}
def generate(
walls: List[Dict],
start_ox: float,
start_oy: float,
ceiling_height: float = 96.0,
scale_x: float = 4.0,
scale_y: float = 3.0,
) -> Dict[str, List]:
"""
Parameters
----------
walls : list of wall dicts, each with:
"name" (str)
"length" (float, inches)
"base_cfg" (list of base/tall cabinet dicts)
"upper_cfg" (list of upper cabinet dicts)
Legacy key "cabinets" (flat merged list) is also
accepted for backward compatibility — it is passed
to build() (single-cursor) instead of build_two_tier().
start_ox/oy : canvas origin for the first wall (PDF points).
ceiling_height : wall height in inches.
scale_x/y : pts per inch.
"""
geom: Dict[str, List] = {"lines": [], "blocks": [], "texts": [], "dimensions": []}
elev_ox = start_ox
elev_oy = start_oy
for w_idx, wall in enumerate(walls):
wall_length = wall.get("length", 90.0)
cabinets = wall.get("cabinets", [])
is_ada = wall.get("is_ada", False)
# ── offset origin for subsequent walls ────────────────────────
if w_idx > 0:
prev_length = walls[w_idx - 1].get("length", 90.0)
offset_x = (prev_length * scale_x) + 100.0
elev_ox += offset_x
# Label the elevation view
geom["texts"].append({
"pos": [elev_ox + wall_length/2.0 - 15.0, elev_oy - 20.0],
"text": f"{wall.get('name', 'WALL')} ELEVATION VIEW",
"layer": "TEXT"
})
wall_has_ada = any(cab.get("is_ada", False) for cab in cabinets)
max_base_h = 32.5 if wall_has_ada else 34.5
cab_x_curr = 0.0
dim_items = []
for cab in cabinets:
cab_id = cab.get("cabinet_id", cab.get("id", "Cab"))
# Normalize cabinet using Phase 1 Resolver
resolved = CabinetLibraryResolver.resolve_cabinet(cab_id)
# Prefer dimensions from the schedule
cab_w = cab.get("width", cab.get("width_in", 0.0))
if cab_w <= 0: cab_w = resolved["width"]
cab_h = cab.get("height", cab.get("height_in", 0.0))
if cab_h <= 0: cab_h = resolved["height"]
family = resolved["family"]
cab_type = cab.get("cabinet_type", cab.get("type", "")).lower()
# Override family based on explicit cabinet_type
if 'upper' in cab_type or 'wall' in cab_type:
family = 'UPPER'
elif 'pantry' in cab_type or 'tall' in cab_type:
family = 'TALL'
dim_items.append({"width": cab_w})
is_upper = family == 'UPPER'
is_pantry = family == 'TALL'
is_sink = resolved["render_style"] == 'sink_base' or 'sink' in cab_type
is_drawer = resolved["render_style"] == 'drawer_base' or 'drawer' in cab_type
render_style = resolved["render_style"]
# Appliances are still a bit hardcoded or can be resolved
is_range = "range" in cab_type or "range" in cab_id.lower() or "cooktop" in cab_id.lower()
is_ref = "ref" in cab_type or "refrigerator" in cab_id.lower() or "appliance" in cab_type
is_dw = "dw" in cab_type or "dishwasher" in cab_id.lower()
is_ada = cab.get("is_ada", False)
x0 = elev_ox + cab_x_curr * scale_x
x1 = x0 + cab_w * scale_x
# Height positioning
if is_pantry:
y0 = elev_oy + 4.0 * scale_y
y1 = elev_oy + cab_h * scale_y
elif is_upper:
aff = 48.0 if is_ada else 54.0
y0 = elev_oy + aff * scale_y
y1 = y0 + cab_h * scale_y
else:
actual_h = cab_h if cab_h > 0 else max_base_h
y0 = elev_oy + 4.0 * scale_y
y1 = elev_oy + actual_h * scale_y
elev_ox += prev_length * scale_x + 100.0
# Appliances vs Cabinets
if is_ref:
app_geom = ApplianceLibrary.draw_refrigerator_elevation(x0, elev_oy, cab_w, scale_x, scale_y)
# ── build validated layout ────────────────────────────────────
base_cfg = wall.get("base_cfg", None)
upper_cfg = wall.get("upper_cfg", None)
if base_cfg is not None:
# Two-tier path (preferred)
layout = ElevationLayout.build_two_tier(
base_cfg = base_cfg,
upper_cfg = upper_cfg or [],
wall_length_in = wall_length,
ceiling_h_in = ceiling_height,
is_ada = is_ada,
)
else:
# Legacy flat-list path (single-tier walls only)
layout = ElevationLayout.build(
segments_cfg = wall.get("cabinets", []),
wall_length_in = wall_length,
ceiling_h_in = ceiling_height,
is_ada = is_ada,
)
# Validate — hard structural errors become a drawing banner; soft
# NKBA guideline warnings are annotated below it without blocking.
try:
layout.validate()
except ValueError as exc:
geom["texts"].append({
"pos": [elev_ox + 10, elev_oy + ceiling_height * scale_y / 2],
"text": f"⚠ LAYOUT ERROR: {exc}",
"layer": "TEXT_ERROR",
"size": 5,
})
# Soft NKBA guideline warnings — annotated on the drawing, not fatal
for i, warn in enumerate(layout.warnings):
geom["texts"].append({
"pos": [elev_ox + 10, elev_oy - (25 + i * 8)],
"text": f"⚑ {warn}",
"layer": "TEXT_NKBA_WARN",
"size": 3.5,
})
ref = layout.ref
# ── elevation title — ABOVE the wall border ───────────────────
title_y = elev_oy + (ceiling_height + 25.0) * scale_y
geom["texts"].append({
"pos": [elev_ox + wall_length * scale_x / 2.0, title_y],
"text": f"{wall.get('name', 'WALL')} ELEVATION VIEW",
"layer": "TEXT",
"size": 6,
"anchor": "center",
})
# ── render each segment ───────────────────────────────────────
dim_items: List[Dict] = []
upper_dim_items: List[Dict] = []
for seg in layout.segments:
x0 = elev_ox + seg.x_in * scale_x
x1 = elev_ox + seg.x1_in * scale_x
y0 = elev_oy + seg.y0_in * scale_y
y1 = elev_oy + seg.y1_in * scale_y
# Collect width for the base-tier dimension chain
if not seg.is_upper:
if seg.is_bathtub:
dim_items.append({"width": seg.width_in, "blank": True})
elif seg.is_toilet:
dim_items.append({"width": seg.width_in / 2.0})
dim_items.append({"width": seg.width_in / 2.0})
else:
dim_items.append({"width": seg.width_in})
else:
upper_dim_items.append({"width": seg.width_in, "x_in": seg.x_in})
# ── dispatch to the right renderer ───────────────────────
if seg.is_ref:
app_geom = ApplianceLibrary.draw_refrigerator_elevation(
x0, elev_oy, seg.width_in, seg.height_in,
scale_x, scale_y, label=seg.label,
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif is_dw:
app_geom = ApplianceLibrary.draw_dishwasher_elevation(x0, y0, cab_w, y1 - y0, scale_x, scale_y)
elif seg.is_dw:
app_geom = ApplianceLibrary.draw_dishwasher_elevation(
x0, y0, seg.width_in, seg.height_in, scale_x, scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif is_range:
app_geom = ApplianceLibrary.draw_range_elevation(x0, elev_oy, cab_w, scale_x, scale_y)
elif seg.is_range:
app_geom = ApplianceLibrary.draw_range_elevation(
x0, elev_oy, seg.width_in, scale_x, scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif seg.is_toilet:
app_geom = ApplianceLibrary.draw_toilet_elevation(
x0, elev_oy, seg.width_in, scale_x, scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif seg.is_bathtub:
app_geom = ApplianceLibrary.draw_bathtub_elevation(
x0, elev_oy, seg.width_in, height=18.0, scale_x=scale_x, scale_y=scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
elif seg.is_dw:
app_geom = ApplianceLibrary.draw_dishwasher_elevation(
x0, elev_oy, seg.width_in, seg.height_in or ref.counter_top_y, scale_x, scale_y
)
geom["blocks"].extend(app_geom["blocks"])
geom["lines"].extend(app_geom["lines"])
geom["texts"].extend(app_geom["texts"])
else:
cab_geom = CabinetRendererFactory.render_elevation(
cab, x0, y0, x1, y1, is_upper, is_pantry, is_drawer, render_style, scale_x, scale_y
{"cabinet_id": seg.label, "is_ada": seg.is_ada},
x0, y0, x1, y1,
seg.is_upper, seg.is_tall, seg.is_drawer,
seg.render_style, scale_x, scale_y,
)
geom["blocks"].extend(cab_geom["blocks"])
geom["lines"].extend(cab_geom["lines"])
geom["texts"].extend(cab_geom["texts"])
if is_sink:
sink_geom = ApplianceLibrary.draw_sink_elevation(x0, y1, cab_w, scale_x, scale_y)
if seg.is_sink:
sink_geom = ApplianceLibrary.draw_sink_elevation(
x0, y1, seg.width_in, scale_x, scale_y
)
geom["lines"].extend(sink_geom["lines"])
# Toe kicks for standard base cabinets (recessed by 3" on sides usually, but in elevation we just draw a box)
if not is_upper and not is_pantry and not is_ref and not is_range and render_style != 'panel':
# ── toe kick for base cabs ────────────────────────────────
if (not seg.is_upper and not seg.is_tall and not seg.is_ref
and not seg.is_range and not seg.is_toilet and not seg.is_bathtub
and seg.render_style != "panel"):
geom["blocks"].append({
"type": "rect",
"type": "rect",
"coords": [x0, elev_oy, x1 - x0, y0 - elev_oy],
"layer": "CABINETS_BASE",
"style": "solid"
"layer": "CABINETS_BASE",
"style": "solid",
})
cab_x_curr += cab_w
# Horizontal Dimensions
geom["dimensions"].extend(DimensionEngine.generate_horizontal_chain(dim_items, elev_ox, elev_oy - 10.0, scale_x))
geom["dimensions"].append(DimensionEngine.generate_overall_dimensions(
[elev_ox, elev_oy + (ceiling_height + 10.0) * scale_y],
[elev_ox + wall_length * scale_x, elev_oy + (ceiling_height + 10.0) * scale_y],
wall_length
))
# ── base-tier dimension chain (below floor line) ──────────────
dim_y = elev_oy - 10.0
geom["dimensions"].extend(
DimensionEngine.generate_horizontal_chain(dim_items, elev_ox, dim_y, scale_x)
)
# ── upper-tier dimension chain (above ceiling line) ───────────
upper_dim_y = elev_oy + (ceiling_height + 5.0) * scale_y
if upper_dim_items:
# upper_dim_items might not be contiguous if there's a gap, but for now we just use the chain.
# Since the width sum might not equal wall length, generate_horizontal_chain just adds them up.
geom["dimensions"].extend(
DimensionEngine.generate_horizontal_chain(upper_dim_items, elev_ox, upper_dim_y, scale_x)
)
# ── overall dimension (above ceiling) ─────────────────────────
overall_y = elev_oy + (ceiling_height + 15.0) * scale_y
geom["dimensions"].append(
DimensionEngine.generate_overall_dimensions(
[elev_ox, overall_y],
[elev_ox + wall_length * scale_x, overall_y],
wall_length,
)
)
# ── vertical dimension chains (left and right) ────────────────
vert_dims = [
{"height": ref.counter_top_y},
{"height": 1.6},
{"height": ref.wall_cab_bot_y - ref.counter_top_y - 1.6},
{"height": ref.wall_cab_top_y - ref.wall_cab_bot_y}
]
geom["dimensions"].extend(
DimensionEngine.generate_vertical_chain(vert_dims, elev_ox - 10.0 * scale_x, elev_oy, scale_y)
)
geom["dimensions"].extend(
DimensionEngine.generate_vertical_chain(vert_dims, elev_ox + wall_length * scale_x + 10.0 * scale_x, elev_oy, scale_y)
)
# overall vertical dimension
geom["dimensions"].append(
DimensionEngine.generate_overall_dimensions(
[elev_ox - 20.0 * scale_x, elev_oy],
[elev_ox - 20.0 * scale_x, elev_oy + ref.wall_cab_top_y * scale_y],
ref.wall_cab_top_y,
)
)
geom["dimensions"].append(
DimensionEngine.generate_overall_dimensions(
[elev_ox + wall_length * scale_x + 20.0 * scale_x, elev_oy],
[elev_ox + wall_length * scale_x + 20.0 * scale_x, elev_oy + ref.wall_cab_top_y * scale_y],
ref.wall_cab_top_y,
)
)
# ── wall border ───────────────────────────────────────────────
w_pt = wall_length * scale_x
h_pt = ceiling_height * scale_y
geom["lines"].append({"start": [elev_ox, elev_oy ], "end": [elev_ox + w_pt, elev_oy ], "layer": "WALLS", "style": "continuous"})
geom["lines"].append({"start": [elev_ox + w_pt, elev_oy ], "end": [elev_ox + w_pt, elev_oy + h_pt], "layer": "WALLS", "style": "continuous"})
geom["lines"].append({"start": [elev_ox + w_pt, elev_oy + h_pt], "end": [elev_ox, elev_oy + h_pt], "layer": "WALLS", "style": "continuous"})
# ── countertop callout ────────────────────────────────────────────
c_x = elev_ox + (wall_length / 2.0) * scale_x
c_y = elev_oy + ref.counter_top_y * scale_y
text_y = c_y + 15.0 * scale_y
# Thick Wall Border
w_len_scale = wall_length * scale_x
c_height_scale = ceiling_height * scale_y
geom["lines"].append({"start": [elev_ox, elev_oy], "end": [elev_ox + w_len_scale, elev_oy], "layer": "WALLS", "style": "continuous"})
geom["lines"].append({"start": [elev_ox + w_len_scale, elev_oy], "end": [elev_ox + w_len_scale, elev_oy + c_height_scale], "layer": "WALLS", "style": "continuous"})
geom["lines"].append({"start": [elev_ox + w_len_scale, elev_oy + c_height_scale], "end": [elev_ox, elev_oy + c_height_scale], "layer": "WALLS", "style": "continuous"})
geom["lines"].append({"start": [elev_ox, elev_oy + c_height_scale], "end": [elev_ox, elev_oy], "layer": "WALLS", "style": "continuous"})
geom["lines"].append({"start": [c_x + 20.0 * scale_x, text_y], "end": [c_x + 5.0 * scale_x, text_y], "layer": "CALLOUTS", "style": "continuous"})
geom["lines"].append({"start": [c_x + 5.0 * scale_x, text_y], "end": [c_x, c_y], "layer": "CALLOUTS", "style": "continuous"})
geom["texts"].append({
"pos": [c_x + 22.0 * scale_x, text_y],
"text": "COUNTERTOP BY OTHERS",
"layer": "CALLOUTS",
"size": 4.0,
"anchor": "left"
})
return geom
@@ -0,0 +1,490 @@
"""
===========================================================================
core/engines/elevation_layout.py — Validated Elevation Layout Model
===========================================================================
Builds a single, validated data model for one elevation wall.
Two-tier cursor model (replaces single flat-list cursor):
- Base tier cursor : starts at x=0, walks left-to-right through base/tall
- Upper tier cursor : starts at tall_right_in (REF/tall right edge, or 0 if
no tall column), walks left-to-right through uppers
The two tiers are fully independent — the upper cursor never inherits the
base cursor's position, and no UPPER_SPACER is needed or accepted.
API:
layout = ElevationLayout.build_two_tier(
base_cfg = wall_data["cabinets"], # list of base/tall dicts
upper_cfg = wall_data["uppers"], # list of upper dicts
wall_length_in = wall["length"],
ceiling_h_in = ceiling_height,
is_ada = False,
)
layout.validate() # raises ValueError on bad geometry
for seg in layout.segments:
...render seg...
Legacy single-list API (build()) is still available for callers that
already have a pre-merged segment list (e.g. appliance-only walls).
===========================================================================
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import List, Optional
# Tolerance (inches) for the width-sum vs wall-length check
_WIDTH_TOL = 0.5 # ~1.3 cm — generous for rounding in cm→inch conversion
_OVERLAP_TOL = 0.01 # pts — effectively zero
@dataclass
class RefLines:
"""
All shared horizontal reference lines for one elevation wall.
All values are in raw inches (before scale is applied in the renderer).
floor_y = 0.0 (local coordinate — caller adds elev_oy when rendering)
"""
floor_y: float = 0.0
toe_top_y: float = 4.0 # top of toe-kick (standard 4" toe)
counter_top_y: float = 34.5 # top of base cabinet / counter height
wall_cab_bot_y: float = 54.0 # bottom of wall cabinet run (AFF for standard)
wall_cab_top_y: float = 84.0 # top of wall cabinet run (= bot + cabinet height)
ceiling_y: float = 96.0 # ceiling / soffit
@dataclass
class Segment:
"""One unit in the ordered elevation layout."""
index: int
label: str
seg_type: str # 'base', 'upper', 'tall', 'ref', 'dw', 'range',
# 'sink_base', 'drawer_base', 'vanity', 'toilet',
# 'filler', 'panel'
width_in: float
height_in: float
x_in: float # left edge — always set by cursor, never assumed
# Snapped y bounds (inches, local coords — add elev_oy when scaling)
y0_in: float # bottom of cabinet body (above toe kick)
y1_in: float # top of cabinet body
render_style: str = "standard"
is_ada: bool = False
# Explicit placement tier set by the factory, not inferred from flags.
# "base" = placed by the base-cursor; "upper" = placed by the upper-cursor.
# Panels/fillers in the upper list have is_upper=False but tier="upper".
tier: str = "base"
# Convenience flags
is_upper: bool = False
is_tall: bool = False
is_ref: bool = False
is_dw: bool = False
is_range: bool = False
is_sink: bool = False
is_drawer: bool = False
is_toilet: bool = False
is_bathtub: bool = False
# NOTE: is_spacer intentionally removed — UPPER_SPACER mechanism deleted.
# Use build_two_tier() instead, which positions uppers correctly without spacers.
@property
def x1_in(self) -> float:
return self.x_in + self.width_in
def bbox(self):
"""Returns (x0, y0, x1, y1) in local inches."""
return (self.x_in, self.y0_in, self.x1_in, self.y1_in)
class ElevationLayout:
"""
Validated, two-tier-cursor-placed layout for one elevation wall.
After calling validate(), check `layout.warnings` for soft NKBA guideline
issues. Hard structural errors (overlaps, width-mismatch, upper overflow)
still raise ValueError so callers can surface them as drawing banners.
"""
def __init__(self, segments: List[Segment], ref: RefLines, wall_length_in: float):
self.segments = segments
self.ref = ref
self.wall_length_in = wall_length_in
# Soft NKBA warnings populated by validate() — don't block generation
self.warnings: List[str] = []
# ─────────────────────────────────────────────────────────────────────
# Primary factory — two-tier cursor
# ─────────────────────────────────────────────────────────────────────
@classmethod
def build_two_tier(
cls,
base_cfg: List[dict],
upper_cfg: List[dict],
wall_length_in: float,
ceiling_h_in: float = 96.0,
is_ada: bool = False,
) -> "ElevationLayout":
"""
Build the layout from two SEPARATE, independent segment lists.
base_cfg — base + tall + appliance (REF, DW, range) cabinets,
in left-to-right order. Cursor starts at x=0.
upper_cfg — wall/upper cabinets, in left-to-right order.
Cursor starts at the right edge of the first REF/tall
column in the base run (or 0 if none).
Neither list should contain UPPER_SPACER entries. The upper
cursor is positioned automatically based on the base-tier geometry.
Each dict must have at minimum:
- width (float, inches)
- height (float, inches) — body height, NOT total with toe
- type (str) — cabinet family hint
- id or cabinet_id (str) — used for appliance detection
"""
ref = _compute_ref_lines(ceiling_h_in, is_ada)
segments: List[Segment] = []
seg_index = 0
# ── Tier 1: base run (cursor from x=0) ───────────────────────────
base_cursor = 0.0
tall_left_in = 0.0
tall_right_in = 0.0 # will be set to REF/tall right edge if found
for cab in base_cfg:
seg, base_cursor = _make_segment(cab, seg_index, base_cursor, ref, is_ada)
seg.tier = "base" # explicit tier — panels/fillers in base stay base
seg_index += 1
# Track the REF/tall edges for the upper cursor start
if seg.is_tall or seg.is_ref:
if tall_right_in == 0.0:
tall_left_in = seg.x_in
tall_right_in = max(tall_right_in, seg.x1_in)
segments.append(seg)
# ── Tier 2: upper run ──────────────────────────────────────────────────
# If the tall cabinet is on the left edge, uppers start after it.
# Otherwise, they start at 0.
upper_cursor = tall_right_in if (tall_left_in <= 0.1 and tall_right_in > 0.0) else 0.0
for cab in upper_cfg:
if cab.get("anchor") == "over_tall":
upper_cursor = tall_left_in
seg, upper_cursor = _make_segment(cab, seg_index, upper_cursor, ref, is_ada)
seg.tier = "upper" # explicit tier — panels/fillers in upper list stay upper
seg_index += 1
segments.append(seg)
return cls(segments, ref, wall_length_in)
# ─────────────────────────────────────────────────────────────────────
# Legacy single-list factory (kept for appliance-only / test use)
# ─────────────────────────────────────────────────────────────────────
@classmethod
def build(
cls,
segments_cfg: List[dict],
wall_length_in: float,
ceiling_h_in: float = 96.0,
is_ada: bool = False,
) -> "ElevationLayout":
"""
Build from a single pre-ordered list. Suitable for walls that have
only base cabinets or only upper cabinets (e.g. appliance walls,
simple vanities, toilet walls).
WARNING: Do NOT pass base + upper cabinets in one list — the cursor
never resets between tiers, so uppers will land at the wrong x.
Use build_two_tier() for two-tier walls.
"""
ref = _compute_ref_lines(ceiling_h_in, is_ada)
segments: List[Segment] = []
cursor_x = 0.0
for i, cab in enumerate(segments_cfg):
seg, cursor_x = _make_segment(cab, i, cursor_x, ref, is_ada)
segments.append(seg)
return cls(segments, ref, wall_length_in)
# ─────────────────────────────────────────────────────────────────────
# Validation
# ─────────────────────────────────────────────────────────────────────
def validate(self) -> None:
"""
Raises ValueError with a descriptive message if any of:
Base tier:
- Width sum of base/tall segments diverges from wall_length_in
- Any two base/tall bounding boxes overlap
Upper tier:
- The upper run ends past the wall right edge
- Any two upper bounding boxes overlap
"""
# Use explicit tier field — panels/fillers in the upper config have
# is_upper=False but tier="upper", so they must NOT be counted in base_sum.
base_segs = [s for s in self.segments if s.tier == "base"]
upper_segs = [s for s in self.segments if s.tier == "upper"]
# 1. Base-tier width-sum check
base_sum = sum(s.width_in for s in base_segs)
if base_sum > 0 and abs(base_sum - self.wall_length_in) > _WIDTH_TOL:
raise ValueError(
f"width mismatch: base segments sum to {base_sum:.4f}\" "
f"but wall_length is {self.wall_length_in:.4f}\" "
f"(delta = {base_sum - self.wall_length_in:+.4f}\")"
)
# 2. Upper-tier right-edge check
if upper_segs:
upper_end = max(s.x1_in for s in upper_segs)
if upper_end > self.wall_length_in + _WIDTH_TOL:
hint = " (Hint: If an over-fridge cabinet is pushing the run out, ensure it has 'anchor': 'over_tall' in the config.)"
raise ValueError(
f"ElevationLayout upper run overflows wall: upper run ends at "
f"{upper_end:.4f}\" but wall_length is {self.wall_length_in:.4f}\" "
f"(overflow = {upper_end - self.wall_length_in:+.4f}\"){hint}"
)
# 3. Overlap check — within each tier independently
for tier_label, tier in (("base", base_segs), ("upper", upper_segs)):
for i, a in enumerate(tier):
for b in tier[i + 1:]:
if _boxes_overlap(a.bbox(), b.bbox()):
raise ValueError(
f"ElevationLayout {tier_label}-tier overlap: "
f"segment {a.index} ({a.label!r}, "
f"x={a.x_in:.2f}\"..{a.x1_in:.2f}\") overlaps "
f"segment {b.index} ({b.label!r}, "
f"x={b.x_in:.2f}\"..{b.x1_in:.2f}\")"
)
# ── 4. NKBA Guideline Checks (SOFT — appended to self.warnings, never raised) ──
#
# Rationale: A cabinet overlap or width mismatch means the drawing is
# physically impossible and must block generation. A dishwasher placed
# 40" from the sink or a range without a dedicated hood is a best-practice
# deviation that real small kitchens do intentionally — it should appear as
# an annotation on the drawing, not crash the whole sheet.
self.warnings.clear()
sinks = [s for s in base_segs if s.is_sink]
dws = [s for s in base_segs if s.is_dw]
ranges = [s for s in base_segs if s.is_range]
# Vent detection: check id, label, AND seg_type so WMH (label='') still matches.
def _is_vent(s: Segment) -> bool:
haystack = (s.label + " " + s.seg_type).lower()
id_lower = s.label.lower() # label was set from id in _make_segment
# Also peek at the raw cabinet id stored as the label when label==id
return any(kw in haystack for kw in ("hood", "mic", "vent", "wmh", "microwave"))
vents = [s for s in upper_segs if _is_vent(s)]
for dw in dws:
if not sinks:
# Skip — sink may be on a different wall (island kitchen, split layout)
continue
dw_center = dw.x_in + dw.width_in / 2.0
closest_sink = min(sinks, key=lambda s: abs((s.x_in + s.width_in / 2.0) - dw_center))
dist = abs((closest_sink.x_in + closest_sink.width_in / 2.0) - dw_center)
max_dist = (closest_sink.width_in / 2.0) + 36.0 + (dw.width_in / 2.0)
if dist > max_dist + _WIDTH_TOL:
self.warnings.append(
f"NKBA GUIDELINE: Dishwasher is {dist:.1f}\" from sink center "
f"(max recommended {max_dist:.1f}\" edge-to-edge)."
)
for rng in ranges:
rng_center = rng.x_in + rng.width_in / 2.0
has_vent = any(
abs(rng_center - (v.x_in + v.width_in / 2.0)) < (rng.width_in / 2.0 + 6.0)
for v in vents
)
if not has_vent:
self.warnings.append(
f"NKBA GUIDELINE: Range/Stove at x={rng.x_in:.1f}\" has no overhead "
f"ventilation (Hood or OTR Microwave) detected on this wall."
)
# ─────────────────────────────────────────────────────────────────────
# Convenience accessors
# ─────────────────────────────────────────────────────────────────────
def base_run_end_x(self) -> float:
"""X coordinate of the right edge of the last base/tall segment."""
base_segs = [s for s in self.segments if not s.is_upper]
if not base_segs:
return 0.0
return max(s.x1_in for s in base_segs)
def upper_run_start_x(self) -> float:
"""
Upper cabinets left-align to start after the first tall/REF column's
right edge. If no tall/REF column exists they start from x=0.
"""
tall_segs = [s for s in self.segments if s.is_tall or s.is_ref]
if tall_segs:
return max(s.x1_in for s in tall_segs)
return 0.0
def __repr__(self) -> str:
segs = ", ".join(f"{s.label}({s.width_in:.1f}\"@{s.x_in:.1f}\")" for s in self.segments)
return f"ElevationLayout(wall={self.wall_length_in:.1f}\", segs=[{segs}])"
# ─────────────────────────────────────────────────────────────────────────
# Private helpers
# ─────────────────────────────────────────────────────────────────────────
def _classify(cab_id: str, cab_type: str):
"""Return classification flags for one cabinet dict."""
cab_id_lower = cab_id.lower()
cab_type = cab_type.lower()
is_upper = ("upper" in cab_type or "wall" in cab_type) and "spacer" not in cab_type
is_upper = is_upper or (cab_id.startswith("W") and "spacer" not in cab_type)
is_tall = "pantry" in cab_type or "tall" in cab_type or cab_id.startswith("T")
is_ref = "ref" in cab_type or "refrigerator" in cab_id_lower or "ref" in cab_id_lower
is_dw = "dw" in cab_type or "dishwasher" in cab_id_lower or "dw" in cab_id_lower
is_range = "range" in cab_type or "range" in cab_id_lower or "cooktop" in cab_id_lower
is_sink = "sink" in cab_type or cab_id.startswith("SB")
is_drawer = "drawer" in cab_type or cab_id.startswith("DB") or cab_id.startswith("3DB")
is_toilet = "toilet" in cab_type or "toilet" in cab_id_lower
is_vanity = "vanity" in cab_type or cab_id.startswith("V") or "ada_vanity" in cab_type
is_bathtub = "bathtub" in cab_type or "tub" in cab_id_lower or "tub" in cab_type
is_filler = "filler" in cab_type or cab_id.startswith("F") or cab_id.startswith("BF")
is_panel = "panel" in cab_type or cab_id.startswith("P") or cab_id.startswith("BEP") or cab_id.startswith("WEP")
return (is_upper, is_tall, is_ref, is_dw, is_range,
is_sink, is_drawer, is_toilet, is_bathtub, is_vanity, is_filler, is_panel)
def _make_segment(
cab: dict,
index: int,
cursor_x: float,
ref: RefLines,
is_ada: bool,
force_upper: bool = False,
) -> tuple:
"""
Build one Segment from a cabinet dict, advancing cursor_x by its width.
Returns (Segment, new_cursor_x).
"""
cab_id = cab.get("cabinet_id", cab.get("id", "CAB")).upper()
cab_type = cab.get("cabinet_type", cab.get("type", "")).lower()
label = cab.get("label", cab_id) or cab_id # explicit "" falls back to cab_id
w_in = float(cab.get("width", 0.0))
h_in = float(cab.get("height", 0.0))
(is_upper, is_tall, is_ref, is_dw, is_range,
is_sink, is_drawer, is_toilet, is_bathtub, is_vanity, is_filler, is_panel) = _classify(cab_id, cab_type)
if force_upper:
is_upper = True
is_tall = False
# Derive render_style
if cab.get("is_section"): render_style = "section"
elif is_filler: render_style = "filler"
elif is_panel: render_style = "panel"
elif is_sink: render_style = "sink_base"
elif is_drawer: render_style = "drawer_base"
elif is_vanity: render_style = "vanity"
else: render_style = "standard"
y0_in, y1_in = _snap_to_ref(ref, h_in, is_upper, is_tall, is_ref, is_ada)
# FIX: Panels and fillers should start from the floor, not the top of the toe kick
if is_panel or is_filler:
if not is_upper:
y1_in = y0_in + h_in if h_in > 0 else (ref.counter_top_y if not is_tall else ref.wall_cab_top_y)
y0_in = ref.floor_y
# If the dict provided an explicit x, use it. Otherwise, use sequential cursor.
explicit_x = cab.get("x")
if explicit_x is not None:
cursor_x = float(explicit_x)
seg = Segment(
index = index,
label = label,
seg_type = cab_type or ("upper" if is_upper else ("tall" if is_tall else "base")),
width_in = w_in,
height_in = h_in,
x_in = cursor_x,
y0_in = y0_in,
y1_in = y1_in,
render_style= render_style,
is_ada = is_ada,
is_upper = is_upper,
is_tall = is_tall,
is_ref = is_ref,
is_dw = is_dw,
is_range = is_range,
is_sink = is_sink,
is_drawer = is_drawer,
is_toilet = is_toilet,
is_bathtub = is_bathtub,
)
return seg, cursor_x + w_in
def _compute_ref_lines(ceiling_h_in: float, is_ada: bool) -> RefLines:
"""Compute the shared wall reference lines for one elevation."""
toe_top = 4.0
counter = 32.5 if is_ada else 34.5
wall_bot = 48.0 if is_ada else 54.0
wall_top = wall_bot + 30.0
return RefLines(
floor_y = 0.0,
toe_top_y = toe_top,
counter_top_y = counter,
wall_cab_bot_y= wall_bot,
wall_cab_top_y= wall_top,
ceiling_y = ceiling_h_in,
)
def _snap_to_ref(
ref: RefLines,
h_in: float,
is_upper: bool,
is_tall: bool,
is_ref: bool,
is_ada: bool,
) -> tuple:
"""
Returns (y0_in, y1_in) snapped to the appropriate shared reference lines.
All values are LOCAL inches (caller adds elev_oy and multiplies by scale).
"""
if is_tall or is_ref:
y0 = ref.floor_y
y1 = h_in if h_in > 0 else ref.wall_cab_top_y
elif is_upper:
actual_h = h_in if h_in > 0 else 30.0
y1 = ref.wall_cab_top_y
y0 = y1 - actual_h
else:
actual_h = h_in if h_in > 0 else ref.counter_top_y
y0 = ref.toe_top_y
y1 = ref.toe_top_y + actual_h
return (y0, y1)
def _boxes_overlap(a: tuple, b: tuple, tol: float = _OVERLAP_TOL) -> bool:
"""
Returns True if two (x0, y0, x1, y1) boxes overlap more than tol in BOTH axes.
Touching edges (x1_a == x0_b) do not count as overlapping.
"""
ax0, ay0, ax1, ay1 = a
bx0, by0, bx1, by1 = b
x_overlap = ax0 < bx1 - tol and ax1 > bx0 + tol
y_overlap = ay0 < by1 - tol and ay1 > by0 + tol
return x_overlap and y_overlap
@@ -14,7 +14,14 @@ class FloorPlanGenerator:
for w_idx, wall in enumerate(walls):
wall_length = wall.get("length", 90.0)
cabinets = wall.get("cabinets", [])
base_cfg = wall.get("base_cfg", [])
upper_cfg = wall.get("upper_cfg", [])
legacy_cabinets = wall.get("cabinets", [])
if not base_cfg and not upper_cfg and legacy_cabinets:
base_cfg = legacy_cabinets # Fallback for old tests
dim_items = []
if w_idx > 0:
prev_length = walls[w_idx - 1].get("length", 90.0)
@@ -38,61 +45,86 @@ class FloorPlanGenerator:
"layer": "TEXT"
})
# TODO: Wall Hatch can be represented by diagonal lines
# For now, just thick outline is drawn above
cab_x_curr = 0.0
dim_items = []
for cab in cabinets:
cab_id = cab.get("cabinet_id", "Cab")
cab_type = cab.get("cabinet_type", cab.get("type", "")).lower()
cab_w = cab.get("width", 0.0)
cab_d = cab.get("depth", 24.0)
if cab_d <= 0:
cab_d = 24.0
is_upper = cab_id.upper().startswith("W") or "upper" in cab_type
is_sink = "sink" in cab_type or cab_id.upper().startswith("SB")
is_range = "range" in cab_type or "range" in cab_id.lower() or "cooktop" in cab_id.lower()
is_ref = "ref" in cab_type or "refrigerator" in cab_id.lower()
is_dw = "dw" in cab_type or "dishwasher" in cab_id.lower()
def _draw_cabs(cabs, is_upper_tier):
# Separate over_tall from main
over_tall_cabs = [c for c in cabs if c.get("anchor") == "over_tall"]
main_cabs = [c for c in cabs if c.get("anchor") != "over_tall"]
dim_items.append({"width": cab_w})
x0 = plan_ox + cab_x_curr * scale_factor
y0 = plan_oy + wall_depth
if is_upper:
# Draw dashed hidden overhead footprint
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, cab_w * scale_factor, cab_d * scale_factor],
"id": cab_id, "layer": "CABINETS_UPPER", "style": "dashed"
})
else:
# Base footprint
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, cab_w * scale_factor, cab_d * scale_factor],
"id": cab_id, "layer": "CABINETS_BASE", "style": "solid"
})
if is_sink:
sink_geom = ApplianceLibrary.draw_sink_plan(x0, y0, cab_w, cab_d, scale_factor, scale_factor)
geom["blocks"].extend(sink_geom["blocks"])
geom["lines"].extend(sink_geom["lines"])
elif is_range:
rng_geom = ApplianceLibrary.draw_range_plan(x0, y0, cab_w, cab_d, scale_factor, scale_factor)
geom["blocks"].extend(rng_geom["blocks"])
geom["lines"].extend(rng_geom["lines"])
elif is_ref:
geom["texts"].append({"pos": [x0 + (cab_w*scale_factor)/2, y0 + (cab_d*scale_factor)/2], "text": "REF", "size": 4.0, "layer": "TEXT"})
elif is_dw:
geom["texts"].append({"pos": [x0 + (cab_w*scale_factor)/2, y0 + (cab_d*scale_factor)/2], "text": "D/W", "size": 4.0, "layer": "TEXT"})
cab_x_curr += cab_w
tall_width = 0.0
if is_upper_tier:
tall_segs = [c for c in base_cfg if "ref" in c.get("type", "").lower() or "tall" in c.get("type", "").lower() or "pantry" in c.get("type", "").lower() or (c.get("id") or "").startswith("P")]
if tall_segs:
tall_width = sum(c.get("width", 0) for c in tall_segs)
def _draw_group(group_cabs, start_x):
cab_x_curr = start_x
for cab in group_cabs:
cab_id = cab.get("cabinet_id", cab.get("id", "Cab"))
cab_type = cab.get("cabinet_type", cab.get("type", "")).lower()
cab_w = cab.get("width", 0.0)
cab_d = cab.get("depth", 24.0) if not is_upper_tier else cab.get("depth", 12.0)
if cab_d <= 0:
cab_d = 24.0 if not is_upper_tier else 12.0
is_upper = is_upper_tier or cab_id.upper().startswith("W") or "upper" in cab_type
is_sink = "sink" in cab_type or cab_id.upper().startswith("SB")
is_range = "range" in cab_type or "range" in cab_id.lower() or "cooktop" in cab_id.lower()
is_ref = "ref" in cab_type or "refrigerator" in cab_id.lower()
is_dw = "dw" in cab_type or "dishwasher" in cab_id.lower()
is_toilet = "toilet" in cab_type or "toilet" in cab_id.lower()
cab_x_val = cab.get("x")
if cab_x_val is None:
cab_x_val = cab_x_curr
if not is_upper:
dim_items.append({"width": cab_w})
x0 = plan_ox + cab_x_val * scale_factor
y0 = plan_oy + wall_depth
if is_upper:
# Draw dashed hidden overhead footprint
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, cab_w * scale_factor, cab_d * scale_factor],
"id": cab_id, "layer": "CABINETS_UPPER", "style": "dashed"
})
elif is_toilet:
# Toilets do not have a standard rectangular footprint
toilet_geom = ApplianceLibrary.draw_toilet_plan(x0, y0, width=cab_w, depth=cab_d, scale_x=scale_factor, scale_y=scale_factor)
geom["blocks"].extend(toilet_geom["blocks"])
geom["lines"].extend(toilet_geom.get("lines", []))
else:
# Base footprint
geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, cab_w * scale_factor, cab_d * scale_factor],
"id": cab_id, "layer": "CABINETS_BASE", "style": "solid"
})
if is_sink:
sink_geom = ApplianceLibrary.draw_sink_plan(x0, y0, cab_w, cab_d, scale_factor, scale_factor)
geom["blocks"].extend(sink_geom["blocks"])
geom["lines"].extend(sink_geom["lines"])
elif is_range:
rng_geom = ApplianceLibrary.draw_range_plan(x0, y0, cab_w, cab_d, scale_factor, scale_factor)
geom["blocks"].extend(rng_geom["blocks"])
geom["lines"].extend(rng_geom["lines"])
elif is_ref:
geom["texts"].append({"pos": [x0 + (cab_w*scale_factor)/2, y0 + (cab_d*scale_factor)/2], "text": "REF", "size": 4.0, "layer": "TEXT"})
elif is_dw:
geom["texts"].append({"pos": [x0 + (cab_w*scale_factor)/2, y0 + (cab_d*scale_factor)/2], "text": "D/W", "size": 4.0, "layer": "TEXT"})
if cab.get("x") is None:
cab_x_curr += cab_w
_draw_group(over_tall_cabs, 0.0)
_draw_group(main_cabs, tall_width if is_upper_tier else 0.0)
_draw_cabs(base_cfg, is_upper_tier=False)
_draw_cabs(upper_cfg, is_upper_tier=True)
# Add Horizontal Chain Dimension
chain_dims = DimensionEngine.generate_horizontal_chain(dim_items, plan_ox, plan_oy + wall_depth + 30.0 * scale_factor, scale_factor)
geom["dimensions"].extend(chain_dims)
@@ -103,6 +103,12 @@ class PlacedCabinet:
"base": "B",
"sink_base": "SB",
"dw_adjacent": "DW",
"upper_wall": "W",
"microwave_shelf": "MW",
"appliance_space": "APP",
"pantry": "P",
"linen": "L",
"corner_upper": "CW"
}
return f"{prefix_map.get(self.cabinet_type, 'B')}{self.width}"
+105 -38
View File
@@ -4,6 +4,14 @@ class SectionGenerator:
"""Generate detailed CAD sections with fabrication specs."""
SECTION_TYPES = {
'kitchen_standard': {
'title': 'KITCHEN SECTION',
'height': 228.0,
'callouts': [
'PLYWOOD BACKING 6" H',
'STANDARD CABINET',
]
},
'kitchen_ada': {
'title': 'KITCHEN ADA',
'height': 228.0, # 7'-6" typical
@@ -50,6 +58,13 @@ class SectionGenerator:
'PLYWOOD BACKING FULL HEIGHT'
]
},
'vanity_standard': {
'title': 'VANITY SECTION',
'callouts': [
'STANDARD VANITY CABINET',
'MOUNTED AT STANDARD HEIGHT'
]
},
'vanity_ada': {
'title': 'VANITY ADA',
'callouts': [
@@ -99,9 +114,15 @@ class SectionGenerator:
'notes': spec.get('notes', '')
}
# Generate base outline
cls._draw_base_outline(section, kwargs.get('width', 84.0),
kwargs.get('height', spec.get('height', 84.0)))
# Generate base outline based on section type
if 'pantry' in section_type:
cls._draw_pantry_outline(section, kwargs.get('width', 24.0),
kwargs.get('height', spec.get('height', 84.0)))
else:
default_width = 21.0 if 'vanity' in section_type else 24.0
cls._draw_base_outline(section, kwargs.get('width', default_width),
kwargs.get('height', spec.get('height', 84.0)),
is_vanity='vanity' in section_type)
# Add specific details based on type
if section_type == 'kitchen_ada':
@@ -118,13 +139,10 @@ class SectionGenerator:
return section
@staticmethod
def _draw_base_outline(section: Dict, width: float, height: float, **kwargs):
"""Draw full cabinet profile."""
def _draw_pantry_outline(section: Dict, width: float, height: float, **kwargs):
"""Draw full height pantry profile."""
geom = section['geometry']
# Determine ADA flag for height
is_ada = kwargs.get('ada', False)
# FLOOR LINE
geom['lines'].append({'start': [0, 0], 'end': [width, 0], 'layer': 'FLOOR'})
@@ -138,10 +156,50 @@ class SectionGenerator:
'layer': 'STRUCTURE'
})
# BASE CABINET (24" depth, 28.4" height standard, 34" ADA max minus toe kick)
# 34" total ADA counter height - 1.6" counter = 32.4" top of cabinet.
# Height of base cab above floor: 28.4" standard, 32.4" ADA.
base_top = 32.4 if is_ada else 28.4
# PANTRY CABINET (default 84" or 90" height)
geom['blocks'].append({
'type': 'rect',
'coords': [0, toe_kick_y, width, height],
'fill': False,
'layer': 'CABINET'
})
# PLYWOOD BACKING (full height)
geom['blocks'].append({
'type': 'rect',
'coords': [0, toe_kick_y, width, height],
'hatch': 'BRICKS',
'layer': 'BACKING'
})
@staticmethod
def _draw_base_outline(section: Dict, width: float, height: float, **kwargs):
"""Draw full cabinet profile."""
geom = section['geometry']
# Determine ADA flag for height
is_ada = kwargs.get('ada', False)
is_vanity = kwargs.get('is_vanity', False)
# FLOOR LINE
geom['lines'].append({'start': [0, 0], 'end': [width, 0], 'layer': 'FLOOR'})
# TOE KICK (3" inset, 4" high)
toe_kick_y = 4.0
toe_kick_inset = 3.0
geom['blocks'].append({
'type': 'rect',
'coords': [toe_kick_inset, 0, width - toe_kick_inset, toe_kick_y],
'hatch': 'DIAGONAL',
'layer': 'STRUCTURE'
})
# BASE CABINET (24" depth standard, 21" for vanities)
# Height of base cab above floor: 28.4" standard kitchen, 32.4" ADA, 32" standard vanity.
if is_vanity:
base_top = 32.4 if is_ada else 32.0
else:
base_top = 32.4 if is_ada else 28.4
geom['blocks'].append({
'type': 'rect',
'coords': [0, toe_kick_y, width, base_top],
@@ -169,18 +227,17 @@ class SectionGenerator:
'layer': 'COUNTERTOP'
})
# UPPER CABINET (12" depth typical, 30" height, 16" clearance from counter)
upper_y = counter_y + counter_thickness + 16.0
upper_height = 30.0
upper_depth = 12.0
# Determine depth of the wall bounds (which is 'width' passed to function, e.g. 24")
# Upper cabinet is typically flush with back wall
geom['blocks'].append({
'type': 'rect',
'coords': [width - upper_depth, upper_y, width, upper_y + upper_height],
'fill': False,
'layer': 'CABINET'
})
# UPPER CABINET (only for kitchens)
if not is_vanity:
upper_y = counter_y + counter_thickness + 16.0
upper_height = 30.0
upper_depth = 12.0
geom['blocks'].append({
'type': 'rect',
'coords': [width - upper_depth, upper_y, width, upper_y + upper_height],
'fill': False,
'layer': 'CABINET'
})
@staticmethod
@@ -255,20 +312,30 @@ class SectionGenerator:
dims = []
# LEFT SIDE VERTICAL DIMENSIONS
dims.extend([
# Floor to toe kick top
{'start': [-30, 0], 'end': [-30, toe_kick_y], 'text': str(toe_kick_y), 'label': 'TOE KICK', 'position': 'left'},
# Toe kick to counter top
{'start': [-30, toe_kick_y], 'end': [-30, counter_y], 'text': str(round(base_top - toe_kick_y, 1)), 'label': 'BASE CAB HEIGHT', 'position': 'left'},
# Counter thickness
{'start': [-30, counter_y], 'end': [-30, counter_y + 1.6], 'text': "1.6", 'label': 'COUNTERTOP', 'position': 'left'},
# Clearance from counter to upper
{'start': [-30, counter_y + 1.6], 'end': [-30, upper_y], 'text': "16.0", 'label': 'CLEARANCE', 'position': 'left'},
# Upper cabinet height
{'start': [-30, upper_y], 'end': [-30, upper_y + 30.0], 'text': "30.0", 'label': 'UPPER CAB HEIGHT', 'position': 'left'},
# Total height (example 84")
{'start': [-45, 0], 'end': [-45, 84.0], 'text': "84.0", 'label': 'TOTAL HEIGHT', 'position': 'left'},
])
if 'pantry' in section.get('type', ''):
dims.extend([
# Floor to toe kick top
{'start': [-30, 0], 'end': [-30, toe_kick_y], 'text': str(toe_kick_y), 'label': 'TOE KICK', 'position': 'left'},
# Toe kick to top of pantry
{'start': [-30, toe_kick_y], 'end': [-30, kwargs.get('height', 84.0)], 'text': str(round(kwargs.get('height', 84.0) - toe_kick_y, 1)), 'label': 'PANTRY CAB HEIGHT', 'position': 'left'},
# Total height
{'start': [-45, 0], 'end': [-45, kwargs.get('height', 84.0)], 'text': str(kwargs.get('height', 84.0)), 'label': 'TOTAL HEIGHT', 'position': 'left'},
])
else:
dims.extend([
# Floor to toe kick top
{'start': [-30, 0], 'end': [-30, toe_kick_y], 'text': str(toe_kick_y), 'label': 'TOE KICK', 'position': 'left'},
# Toe kick to counter top
{'start': [-30, toe_kick_y], 'end': [-30, counter_y], 'text': str(round(base_top - toe_kick_y, 1)), 'label': 'BASE CAB HEIGHT', 'position': 'left'},
# Counter thickness
{'start': [-30, counter_y], 'end': [-30, counter_y + 1.6], 'text': "1.6", 'label': 'COUNTERTOP', 'position': 'left'},
# Clearance from counter to upper
{'start': [-30, counter_y + 1.6], 'end': [-30, upper_y], 'text': "16.0", 'label': 'CLEARANCE', 'position': 'left'},
# Upper cabinet height
{'start': [-30, upper_y], 'end': [-30, upper_y + 30.0], 'text': "30.0", 'label': 'UPPER CAB HEIGHT', 'position': 'left'},
# Total height (example 84")
{'start': [-45, 0], 'end': [-45, kwargs.get('height', 84.0)], 'text': str(kwargs.get('height', 84.0)), 'label': 'TOTAL HEIGHT', 'position': 'left'},
])
# BOTTOM HORIZONTAL DIMENSIONS
dims.extend([
@@ -0,0 +1,148 @@
import re
from pathlib import Path
from typing import List
from core.ai_vision_classifier import (
ElevationResult, WallIntent, ApplianceIntent, FixtureIntent
)
from core.pdf_extractor import PDFExtractor
from core.yolo_extractor import YOLOExtractor, YOLODetection
from core.dimension_parser import parse_imperial_mm, parse_metric_mm
class YoloIntentAdapter:
"""
Adapter that converts YOLO floor plan detections and native text dimensions
into the ElevationResult intent objects expected by the pipeline.
This provides a deterministic layout path without Gemini Vision.
"""
@staticmethod
def extract_from_floor_plan(pdf_path: Path, dpi: float = 300.0) -> List[ElevationResult]:
"""Run YOLO on the floor plan and combine with native text to produce intent objects."""
import fitz
doc = fitz.open(str(pdf_path))
page = doc[0]
pix = page.get_pixmap(dpi=int(dpi))
img_bytes = pix.tobytes("png")
import core.yolo_extractor
core.yolo_extractor.DETECTION_CONF = 0.30
yolo = YOLOExtractor()
yolo_res = yolo.detect_floor_plan(img_bytes, dpi=dpi)
all_appliances = yolo_res.get("appliances", [])
all_fixtures = yolo_res.get("fixtures", [])
# Get text spans and rects from PDF for deterministic region detection
with PDFExtractor(pdf_path) as ex:
spans = ex.extract_spans(0)
rects = ex.extract_rects(0)
from core.region_detector import RegionDetector
detector = RegionDetector(spans, rects, page.rect.width, page.rect.height)
detected_regions = detector.detect()
kitchens = [r for r in detected_regions if r.region_type == "KITCHEN"]
baths = [r for r in detected_regions if r.region_type in ("BATH", "VANITY")]
results: List[ElevationResult] = []
# Process each detected room region
for region_type, regions in [("KITCHEN", kitchens), ("BATH", baths)]:
for i, r in enumerate(regions):
label = f"{region_type} {i+1} (Deterministic)"
ev = ElevationResult(elevation_label=label, unit_type="UNKNOWN", project_name="Deterministic")
# r.crop_rect is (x0, y0, x1, y1) in PDF points
x0_pt, y0_pt, x1_pt, y1_pt = r.crop_rect
# Convert PDF points to pixels for YOLO symbol matching
x0_px = x0_pt * dpi / 72.0
y0_px = y0_pt * dpi / 72.0
x1_px = x1_pt * dpi / 72.0
y1_px = y1_pt * dpi / 72.0
# 1. Map Appliances inside this region
# YOLO appliances are dicts with x_in, width_in, type. But we need y_in to group walls.
# Actually, yolo_res["appliances"] only has x_in, width_in. It lost y_in.
# Wait, we can just use the room width as the wall length for a simple 1-wall approximation
# Calculate room's absolute coords
room_x_in = x0_px / dpi
room_y_in = y0_px / dpi
for app in all_appliances:
app_x_px = app["x_in"] * dpi
app_y_px = app.get("y_in", 0) * dpi
# Check if appliance center is within room bbox
if x0_px <= app_x_px <= x1_px and y0_px <= app_y_px <= y1_px:
# Relativize x_in to the room's left edge
rel_x = app["x_in"] - room_x_in
ev.appliances.append(ApplianceIntent(
type=app["type"],
width_in=app.get("width_in", 24.0),
height_in=36.0, # default base height
x_in=max(0.0, rel_x),
notes="source: yolo"
))
for fix in all_fixtures:
fix_x_px = fix["x_in"] * dpi
fix_y_px = fix.get("y_in", 0) * dpi
if x0_px <= fix_x_px <= x1_px and y0_px <= fix_y_px <= y1_px:
rel_x = fix["x_in"] - room_x_in
ev.fixtures.append(FixtureIntent(
type=fix["type"],
width_in=fix.get("width_in", 24.0),
x_in=max(0.0, rel_x),
notes="source: yolo"
))
# 2. Extract Native Text Dimensions for Wall length
# We already have x0_pt, y0_pt, x1_pt, y1_pt from crop_rect
# Expand search area slightly for dimensions that might sit just outside the bounding box
bx0_pt, by0_pt = x0_pt - 40.0, y0_pt - 40.0
bx1_pt, by1_pt = x1_pt + 40.0, y1_pt + 40.0
# Pixel-derived width is the ground-truth fallback.
# At the rendering DPI, (x1_px-x0_px)/dpi gives page-inches which
# must then be multiplied by the architectural scale.
# Standard residential scale: 1/4"=1'-0" → 1 paper-inch = 48 real inches.
# Typical kitchen region in a floor plan at 300 DPI: 100–400px → 0.3–1.3 paper-inches
# → 16–62 real feet (192–744 inches). Use that as a sanity window.
pixel_width_paper_in = (x1_px - x0_px) / dpi # paper inches
# Assume 1/4" = 1'-0" scale (48 real in per paper in) as safe default.
# Clamp architectural scale: if parsed dims suggest different scale, we'll use them.
ARCH_SCALE_FALLBACK = 24.0 # 1/2"=1'-0" is typical for kitchen details
pixel_derived_in = pixel_width_paper_in * ARCH_SCALE_FALLBACK
# Parse dimensions, but only accept plausible kitchen/vanity wall widths:
# Real kitchen walls: 48" (4') to 300" (25'). Reject outliers.
MIN_WALL_IN = 48.0
MAX_WALL_IN = 300.0
max_dim_in = 0.0
for s in spans:
if bx0_pt <= s.cx <= bx1_pt and by0_pt <= s.cy <= by1_pt:
mm_val = parse_imperial_mm(s.text) or parse_metric_mm(s.text)
if mm_val:
in_val = mm_val / 25.4
# Only accept dimensions in the plausible wall-length range
if MIN_WALL_IN <= in_val <= MAX_WALL_IN:
if in_val > max_dim_in:
max_dim_in = in_val
# If no plausible dimension was found, fall back to pixel-derived estimate.
# Clamp that too — if YOLO crops an unreasonably large region, pin to 168" (14').
if max_dim_in == 0.0:
max_dim_in = max(MIN_WALL_IN, min(pixel_derived_in, MAX_WALL_IN))
ev.walls.append(WallIntent(
name=label,
length_in=round(max_dim_in, 1),
notes="YOLO+NativeText length"
))
results.append(ev)
return results
+22 -3
View File
@@ -26,7 +26,8 @@ class GeometryEngine:
walls: list[dict],
appliances: list[dict],
ceiling_height: float = 108.0,
soffit_height: float = 96.0
soffit_height: float = 96.0,
unit_type: str = 'kitchen_standard'
) -> dict:
"""
Processes wall runs to generate plan and elevation geometries.
@@ -54,8 +55,26 @@ class GeometryEngine:
scale_y=1.0
)
# Phase 2 will implement the SectionGenerator
side_geom = {"lines": [], "dimensions": [], "blocks": [], "texts": []}
from core.engines.section_generator import SectionGenerator
try:
# Check if there are ADA cabinets in the walls
is_ada = False
for w in walls:
for cab in w.get("base_cfg", []):
if cab.get("is_ada"):
is_ada = True
break
if is_ada: break
actual_type = unit_type
if is_ada and not actual_type.endswith("_ada"):
actual_type = actual_type.replace("_standard", "_ada")
section_res = SectionGenerator.generate_section(actual_type, ada=is_ada)
side_geom = section_res['geometry']
except Exception as e:
# Fallback
side_geom = {"lines": [], "dimensions": [], "blocks": [], "texts": []}
return {
"plan": plan_geom,
+174 -5
View File
@@ -79,6 +79,7 @@ ELEVATION_CLASSES = [
]
@dataclass
class YOLODetection:
"""One detected element from YOLO inference."""
@@ -90,6 +91,53 @@ class YOLODetection:
height_in: float = 0.0 # real-world height in inches
def _numpy_nms(boxes: "np.ndarray", iou_thresh: float) -> list[int]:
"""
Pure-NumPy non-maximum suppression.
boxes: float32 array of shape [N, 6] — (x0, y0, x1, y1, conf, cls_idx).
Returns a list of indices to keep, sorted by descending confidence.
"""
import numpy as np
if len(boxes) == 0:
return []
x0 = boxes[:, 0]
y0 = boxes[:, 1]
x1 = boxes[:, 2]
y1 = boxes[:, 3]
scores = boxes[:, 4]
cls = boxes[:, 5]
areas = (x1 - x0) * (y1 - y0)
order = scores.argsort()[::-1] # highest confidence first
keep: list[int] = []
while order.size > 0:
i = order[0]
keep.append(int(i))
# Suppress boxes of the same class with high IoU
same_cls = (cls[order[1:]] == cls[i])
rest = order[1:]
ix0 = np.maximum(x0[i], x0[rest])
iy0 = np.maximum(y0[i], y0[rest])
ix1 = np.minimum(x1[i], x1[rest])
iy1 = np.minimum(y1[i], y1[rest])
inter = np.maximum(0.0, ix1 - ix0) * np.maximum(0.0, iy1 - iy0)
iou = inter / np.maximum(areas[i] + areas[rest] - inter, 1e-6)
# Keep if different class OR IoU below threshold
suppress = same_cls & (iou >= iou_thresh)
order = rest[~suppress]
return keep
class YOLOExtractor:
"""
Runs YOLO inference on a rendered page image and converts detections
@@ -152,6 +200,81 @@ class YOLOExtractor:
pt = px * 72.0 / dpi # pixels → PDF points
return pt * arch_scale_in_per_pt # PDF points → real-world inches
# ── Tiled / SAHI-style inference ──────────────────────────────────────
@staticmethod
def _run_tiled_inference(
model,
img: "np.ndarray",
conf: float = 0.35,
tile_size: int = 1280,
overlap: float = 0.20,
iou_nms: float = 0.45,
) -> list[tuple]:
"""
Slide a tile_size×tile_size window over the image with `overlap` fraction
of overlap, run YOLO on each tile, map detections back to full-image coords,
then apply non-max suppression to de-duplicate across tile boundaries.
Returns a list of (class_name, conf, x0, y0, x1, y1) tuples.
Why tiled?
----------
Architectural sheets pack multiple scaled floor plan views onto one page.
At 200 DPI a single unit plan occupies ~1/4 of the sheet width, making
fixtures appear at ~25% of the size they were during training (640–1280 px).
Tiling brings each symbol back to training-scale so recall jumps significantly.
"""
import numpy as np
H, W = img.shape[:2]
stride = int(tile_size * (1.0 - overlap))
# Collect raw detections from every tile: [x0,y0,x1,y1,conf,cls_idx]
raw: list[list] = []
class_names: dict = {}
x_starts = list(range(0, max(W - tile_size, 0) + 1, stride)) or [0]
y_starts = list(range(0, max(H - tile_size, 0) + 1, stride)) or [0]
# Always include right/bottom edge tiles
if x_starts[-1] + tile_size < W:
x_starts.append(W - tile_size)
if y_starts[-1] + tile_size < H:
y_starts.append(H - tile_size)
for ys in y_starts:
for xs in x_starts:
xe = min(xs + tile_size, W)
ye = min(ys + tile_size, H)
tile = img[ys:ye, xs:xe]
res = model(tile, conf=conf, verbose=False)[0]
if not class_names:
class_names = res.names
for box in res.boxes:
bx0, by0, bx1, by1 = (float(v) for v in box.xyxy[0])
# Map tile-local coords back to full-image coords
raw.append([
bx0 + xs, by0 + ys,
bx1 + xs, by1 + ys,
float(box.conf),
int(box.cls),
])
if not raw:
return []
# ── NMS across all tiles (torchvision-free pure-numpy) ───────────────
raw_arr = np.array(raw, dtype=np.float32) # [N, 6]
keep = _numpy_nms(raw_arr, iou_nms)
result = []
for i in keep:
x0, y0, x1, y1, c, cls_idx = raw_arr[i]
result.append((class_names[int(cls_idx)], float(c),
float(x0), float(y0), float(x1), float(y1)))
return result
# ── Public API ────────────────────────────────────────────────────────
def detect_floor_plan(
@@ -183,7 +306,52 @@ class YOLOExtractor:
return {"yolo_used": False}
img = _bytes_to_array(page_image_bytes)
results = model(img, conf=DETECTION_CONF, verbose=False)[0]
boxes_raw = self._run_tiled_inference(model, img, conf=DETECTION_CONF)
# --- Merge fragmented region boxes ---
# Tiling cuts large rooms into pieces. We must union overlapping/touching boxes of the same region class.
merged_boxes = []
regions = [b for b in boxes_raw if "region" in b[0]]
symbols = [b for b in boxes_raw if "region" not in b[0]]
# Group regions by class
from collections import defaultdict
regions_by_cls = defaultdict(list)
for r in regions:
regions_by_cls[r[0]].append(r)
for cls_name, boxes in regions_by_cls.items():
# Iteratively merge overlapping boxes
merged = []
for b in boxes:
_, conf, x0, y0, x1, y1 = b
# Check if it overlaps with any existing merged box
overlap_found = False
for i, mb in enumerate(merged):
m_conf, mx0, my0, mx1, my1 = mb
# Overlap condition (including slight touching/adjacent due to tiling overlap)
# Two boxes overlap if they intersect. We pad slightly (e.g. 50px) to catch adjacent tiles.
pad = 50
if not (x1 < mx0 - pad or x0 > mx1 + pad or y1 < my0 - pad or y0 > my1 + pad):
# Merge them (take union of coordinates, max of confidence)
merged[i] = (
max(m_conf, conf),
min(x0, mx0),
min(y0, my0),
max(x1, mx1),
max(y1, my1)
)
overlap_found = True
break
if not overlap_found:
merged.append((conf, x0, y0, x1, y1))
# Add merged regions back to boxes_raw
for m in merged:
merged_boxes.append((cls_name, m[0], m[1], m[2], m[3], m[4]))
boxes_raw = merged_boxes + symbols
# Classes present in the 12-class trained dataset (data.yaml order)
KITCHEN_APPLIANCE_MAP = {
@@ -214,10 +382,7 @@ class YOLOExtractor:
"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])
for cls, conf, x0, y0, x1, y1 in boxes_raw:
w_px = x1 - x0
h_px = y1 - y0
@@ -247,17 +412,21 @@ class YOLOExtractor:
min_conf = LOW_DATA_CLASSES.get(cls, DETECTION_CONF)
if conf < min_conf:
continue
y_in = self._px_to_inches_flat(y0, dpi)
out["appliances"].append({
"type": KITCHEN_APPLIANCE_MAP[cls],
"x_in": x_in,
"y_in": y_in,
"width_in": width_in,
"confidence": conf,
"notes": f"YOLO {cls} conf={conf:.2f}",
})
elif cls in BATH_FIXTURE_MAP:
y_in = self._px_to_inches_flat(y0, dpi)
out["fixtures"].append({
"type": BATH_FIXTURE_MAP[cls],
"x_in": x_in,
"y_in": y_in,
"width_in": width_in,
"height_in": height_in,
"confidence": conf,
+6 -16
View File
@@ -1,17 +1,7 @@
path: C:/Users/abhil/Desktop/Cabinetries/Cabinets/Albert_Project/datasets/floor_plan_annotated
train: images
val: images
path: C:/Users/abhil/Desktop/Cabinetries/Cabinets/Albert_Project/datasets/floor_plan_full
train: train/images
val: valid/images
test: test/images
names:
0: Legends_Symbols
1: bath_region
2: bathtub_symbol
3: dw_symbol
4: fridge_symbol
5: kitchen_region
6: microwave_symbol
7: pantry_symbol
8: range_symbol
9: sink_symbol
10: toilet_symbol
11: vanity_sink_symbol
nc: 12
names: ['Legends_Symbols', 'bath_region', 'bathtub_symbol', 'dw_symbol', 'fridge_symbol', 'kitchen_region', 'microwave_symbol', 'pantry_symbol', 'range_symbol', 'sink_symbol', 'toilet_symbol', 'vanity_sink_symbol']
@@ -1,22 +0,0 @@
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
Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.3 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.5 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.4 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.9 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.8 MiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.6 MiB

@@ -1 +0,0 @@
0 0.610887 0.749086 0.615139 0.490254
@@ -1,3 +0,0 @@
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
@@ -1,2 +0,0 @@
1 0.669524 0.765500 0.231481 0.268519
0 0.475522 0.797213 0.886310 0.038537
@@ -1,3 +0,0 @@
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
@@ -1,2 +0,0 @@
1 0.416865 0.511435 0.107725 0.967870
0 0.674722 1.149565 0.231481 -0.299130
@@ -1,3 +0,0 @@
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
@@ -1,2 +0,0 @@
1 0.416647 0.511435 0.108161 0.967870
0 0.674722 1.149565 0.231481 -0.299130
@@ -1,3 +0,0 @@
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
@@ -1,3 +0,0 @@
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
@@ -1,3 +0,0 @@
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
@@ -1,4 +0,0 @@
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
@@ -1,5 +0,0 @@
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
@@ -1,2 +0,0 @@
0 0.822315 0.410695 0.192283 0.335648
1 0.845509 0.867407 0.145895 0.265185
@@ -1,2 +0,0 @@
0 0.822246 0.408750 0.192422 0.335648
1 0.845440 0.866435 0.146034 0.267130
@@ -1,3 +0,0 @@
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,339 @@
"""
casa_familia_generator.py — Standalone professional shop drawing generator.
Generates the complete 23-page Casa Familia shop drawing PDF + DXF files.
Run: python generators/casa_familia_generator.py
"""
from __future__ import annotations
import json
import os
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from reportlab.lib.pagesizes import landscape, LEDGER
from reportlab.lib import colors
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from generators.shop_drawing_pdf import (
_draw_cover, _draw_matrix_page, _draw_page_border, _draw_title_block,
_FONT_REG, _FONT_BOLD, PAGE_W, PAGE_H, DA_L, DA_R, DA_T, DA_B, NAVY, WHITE
)
from generators.elevation_drawing_pages import (
draw_kitchen_sheet, draw_vanity_sheet,
_draw_border, _draw_title_block as _el_title_block,
_draw_elevation_view, _FR, _FB, BLACK, LTGRAY
)
def load_config(path: str) -> dict:
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def add_section_pages(c, cfg, pg, total):
"""Add ADA section detail pages (matching reference pages 19-23)."""
sections = [
{
"title": "KITCHEN ADA",
"subtitle": 'SECTION SCALE 1/2"=1\'-0"',
"dims": [
("61.00", "[24\"]"),
("15.21", "[6\"]"),
("1.90", "[3/4\"]"),
("23.00", "[9 1/16\"]"),
("68.80", "[27 1/16\"]"),
("61.00", "[2']"),
],
"notes": [
"PLYWOOD BACKING 6\" H",
"INTERNAL DRAWER",
"ACCESSIBLE CABINET",
"ADA - MAX 34\" HEIGHT TO COUNTERTOP",
f"ALL CABINET FINISHES: {cfg.get('finish', 'K019 SILVER LIBERTY ELM').upper()}",
]
},
{
"title": "KITCHEN ADA DRAWER",
"subtitle": 'SECTION SCALE 1/2"=1\'-0"',
"dims": [
("12.00", "[4 3/4\"]"),
("72.00", "[2'-4 3/8\"]"),
],
"notes": [
"PLYWOOD BACKING 6\" H",
"INTERNAL DRAWER",
]
},
{
"title": "SECTION HOOD KITCHEN ADA",
"subtitle": 'SCALE 1/2"=1\'-0"',
"dims": [
("35.50", "[1'-2\"]"),
("168.00", "[5'-6 1/8\"]"),
],
"notes": [
"PLYWOOD BACKING 6\" H",
"RANGE HOOD",
"ADA RANGE",
]
},
]
for sec in sections:
pg += 1
_draw_border(c)
_el_title_block(c, cfg, pg, total,
f"A.{pg-2}",
"SECTION DETAILS",
sec["title"],
sec["subtitle"])
# Draw section callouts
y = DA_T - 40
c.setFont(_FB, 10)
c.setFillColor(BLACK)
c.drawString(DA_L + 20, y, sec["title"])
c.setFont(_FR, 7.5)
c.drawString(DA_L + 20, y - 14, sec["subtitle"])
y -= 40
for note in sec.get("notes", []):
c.setFont(_FR, 8)
c.drawString(DA_L + 30, y, f"• {note}")
y -= 14
y -= 20
for (metric, imperial) in sec.get("dims", []):
c.setFont(_FR, 8)
c.drawString(DA_L + 30, y, f" {metric} {imperial}")
y -= 12
# Draw simplified ADA section diagram
_draw_ada_section_diagram(c, sec["title"], DA_L + 400, DA_B + 80)
c.showPage()
return pg
def _draw_ada_section_diagram(c, section_type, ox, oy):
"""Draw a simplified ADA section diagram."""
w, h = 280.0, 340.0
c.saveState()
c.setStrokeColor(BLACK)
c.setLineWidth(1.0)
c.setFillColor(WHITE)
# Main cabinet outline
c.rect(ox, oy, w, h, fill=1, stroke=1)
# Toe kick
toe_h = 25.0
c.setLineWidth(0.5)
c.line(ox, oy + toe_h, ox + w, oy + toe_h)
# Countertop
ct_y = oy + h * 0.75
c.setLineWidth(2.0)
c.line(ox, ct_y, ox + w, ct_y)
c.setFont(_FR, 6)
c.setFillColor(colors.gray)
c.drawString(ox + 8, ct_y + 3, "COUNTERTOP BY OTHERS")
c.setFillColor(BLACK)
# Knee space for ADA
if "ADA" in section_type.upper() or "DRAWER" in section_type.upper():
c.setLineWidth(0.5)
c.setStrokeColor(colors.Color(0.4, 0.4, 0.4))
c.setDash(3, 3)
knee_y = oy + toe_h
c.line(ox, knee_y + 50, ox + w * 0.6, knee_y + 50)
c.line(ox + w * 0.6, knee_y + 50, ox + w * 0.6, oy + h)
c.setDash()
c.setStrokeColor(BLACK)
c.setFont(_FR, 6)
c.drawString(ox + w * 0.1, knee_y + 30, "KNEE CLEARANCE")
c.drawString(ox + w * 0.1, knee_y + 20, "MIN 27\"W x 19\"D @ 32\"H")
# Plywood backing
c.setFillColor(colors.Color(0.85, 0.85, 0.85))
c.rect(ox + w - 10, oy + toe_h, 10, h - toe_h, fill=1, stroke=1)
c.setFillColor(BLACK)
c.setFont(_FR, 5)
c.restoreState()
def generate_professional_pdf(config_path: str, output_path: str) -> str:
"""Generate the complete professional shop drawing PDF."""
cfg = load_config(config_path)
# Determine page count
k_types = list(cfg.get("kitchen_types", {}).keys())
v_types = list(cfg.get("vanity_types", {}).keys())
total_pages = 2 + len(k_types) * 2 + len(v_types)
print(f" Generating {total_pages} pages...")
print(f" Kitchen types: {k_types}")
print(f" Vanity types: {v_types}")
out = Path(output_path)
out.parent.mkdir(parents=True, exist_ok=True)
c = canvas.Canvas(str(out), pagesize=(PAGE_W, PAGE_H))
c.setTitle(f"SHOP DRAWINGS — {cfg.get('project_name', '')} — {cfg.get('project_no', '')}")
c.setAuthor("Italian Kitchen and Bath — AI Estimation System")
# Build unit_totals from config
unit_totals = {}
for row in cfg.get("unit_matrix", []):
unit_totals[row["key"]] = row["qty"]
# ── Page 1: Cover ──────────────────────────────────────────────────────
_draw_cover(c, cfg, unit_totals, total_pages)
c.showPage()
# ── Page 2: Matrix ─────────────────────────────────────────────────────
_draw_matrix_page(c, cfg, {}, unit_totals, total_pages)
c.showPage()
pg = 2
# ── Kitchen Type Sheets ─────────────────────────────────────────────────
for k_key in k_types:
pg = draw_kitchen_sheet(c, cfg, k_key, pg, total_pages)
# ── Vanity Type Sheets ──────────────────────────────────────────────────
for v_key in v_types:
pg = draw_vanity_sheet(c, cfg, v_key, pg, total_pages)
c.save()
print(f" [SUCCESS] PDF saved: {out} ({pg} pages)")
return str(out)
def _wall_to_geom_engine_format(wall_data, name, is_ada):
IN = 2.54
base_cfg = []
for cab in wall_data.get("cabinets", []):
w_cm = cab.get("width_cm", 30.0)
h_cm = cab.get("height_cm", 86.36 if not is_ada else 81.28)
base_dict = {
"id": cab.get("label", cab.get("type", "base")),
"type": cab.get("type", "base"),
"width": w_cm / IN,
"height": h_cm / IN,
"is_ada": is_ada
}
if "x_in" in cab:
base_dict["x"] = cab["x_in"]
elif "x_cm" in cab:
base_dict["x"] = cab["x_cm"] / IN
base_cfg.append(base_dict)
upper_cfg = []
for uc in wall_data.get("uppers", []):
w_cm = uc.get("width_cm", 30.0)
h_cm = uc.get("height_cm", 76.20)
uc_dict = {
"id": uc.get("label", uc.get("type", "upper")),
"type": "upper",
"width": w_cm / IN,
"height": h_cm / IN,
"is_ada": is_ada
}
if "anchor" in uc:
uc_dict["anchor"] = uc["anchor"]
if "x_in" in uc:
uc_dict["x"] = uc["x_in"]
elif "x_cm" in uc:
uc_dict["x"] = uc["x_cm"] / IN
upper_cfg.append(uc_dict)
return {
"name": name,
"length": wall_data.get("length_cm", 300.0) / IN,
"base_cfg": base_cfg,
"upper_cfg": upper_cfg
}
def generate_all_dxf(config_path: str, output_dir: str):
"""Generate DXF files for all kitchen and vanity types."""
from core.geometry_engine import GeometryEngine
from generators.shop_drawing_dxf import DXFDrawingGenerator
cfg = load_config(config_path)
out = Path(output_dir)
out.mkdir(parents=True, exist_ok=True)
k_types = cfg.get("kitchen_types", {})
v_types = cfg.get("vanity_types", {})
geom_engine = GeometryEngine()
dxf_generator = DXFDrawingGenerator()
for k_key, k_data in k_types.items():
walls_info = []
is_ada = k_data.get("is_ada", False)
if "wall_a" in k_data:
walls_info.append(_wall_to_geom_engine_format(k_data["wall_a"], "A", is_ada))
if "wall_b" in k_data and k_data["wall_b"].get("length_cm", 0) > 0:
walls_info.append(_wall_to_geom_engine_format(k_data["wall_b"], "B", is_ada))
geom_data = geom_engine.generate_layout_geometry(
walls=walls_info,
appliances=[],
ceiling_height=274.32 / 2.54,
soffit_height=274.32 / 2.54 - 12.0,
unit_type="kitchen_standard"
)
dxf_path = out / f"{k_key}.dxf"
dxf_generator.generate(geom_data, dxf_path)
print(f" [SUCCESS] DXF saved: {dxf_path}")
for v_key, v_data in v_types.items():
walls_info = []
is_ada = v_data.get("is_ada", False)
if "wall_a" in v_data:
walls_info.append(_wall_to_geom_engine_format(v_data["wall_a"], "A", is_ada))
geom_data = geom_engine.generate_layout_geometry(
walls=walls_info,
appliances=[],
ceiling_height=274.32 / 2.54,
soffit_height=274.32 / 2.54 - 12.0,
unit_type="vanity_standard"
)
dxf_path = out / f"{v_key}.dxf"
dxf_generator.generate(geom_data, dxf_path)
print(f" [SUCCESS] DXF saved: {dxf_path}")
print(f" [SUCCESS] DXF files saved to: {out}")
if __name__ == "__main__":
from core.engines.config_validator import validate_config_file
CONFIG = "Casa familia/project_config.json"
PDF_OUT = "outputs/casa_familia/pdf/ITALIANKB_SHOP_DRAWINGS_23-033_CASA_FAMILIA.pdf"
DXF_DIR = "outputs/casa_familia/dxf"
print("\n=== CASA FAMILIA SHOP DRAWING GENERATOR ===\n")
print("Step 0: Validating configuration...")
validate_config_file(CONFIG)
print(" [OK] Configuration valid.\n")
print("Step 1: Generating professional PDF...")
generate_professional_pdf(CONFIG, PDF_OUT)
print("\nStep 2: Generating DXF files...")
generate_all_dxf(CONFIG, DXF_DIR)
print("\n=== COMPLETE ===")
print(f"PDF: {PDF_OUT}")
print(f"DXF: {DXF_DIR}/")
@@ -0,0 +1,940 @@
"""
===========================================================================
generators/elevation_drawing_pages.py
Professional Kitchen/Vanity Elevation Drawing Pages
===========================================================================
"""
from __future__ import annotations
import math
from pathlib import Path
from typing import Optional
from reportlab.lib import colors
from reportlab.lib.pagesizes import landscape, LEDGER
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
PAGE_W, PAGE_H = landscape(LEDGER)
TB_W = 62.0
TB_X = PAGE_W - TB_W
MARGIN = 18.0
DA_L = MARGIN
DA_R = TB_X - 4.0
DA_T = PAGE_H - 10.0
DA_B = 10.0
BLACK = colors.black
WHITE = colors.white
NAVY = colors.Color(0.10, 0.10, 0.10)
GRAY = colors.Color(0.5, 0.5, 0.5)
LTGRAY = colors.Color(0.93, 0.93, 0.93)
HATCH = colors.Color(0.3, 0.3, 0.3)
def _register_fonts():
for p in ["C:/Windows/Fonts/GOTHIC.TTF","C:/Windows/Fonts/Gothic.ttf"]:
if Path(p).exists():
try:
pdfmetrics.registerFont(TTFont("CenturyGothic",p))
return "CenturyGothic","CenturyGothic"
except Exception:
pass
for p in ["C:/Windows/Fonts/arial.ttf","C:/Windows/Fonts/Arial.ttf"]:
if Path(p).exists():
try:
pdfmetrics.registerFont(TTFont("Arial",p))
for bp in ["C:/Windows/Fonts/arialbd.ttf","C:/Windows/Fonts/ArialBD.ttf"]:
if Path(bp).exists():
pdfmetrics.registerFont(TTFont("Arial-Bold",bp))
return "Arial","Arial-Bold"
return "Arial","Helvetica-Bold"
except Exception:
pass
return "Helvetica","Helvetica-Bold"
_FR,_FB = _register_fonts()
IN_PER_CM = 1.0/2.54
def fmt_dual(cm):
inches=cm*IN_PER_CM
metric=f"{cm:.2f}"
feet=int(inches//12)
rem_in=inches%12
whole=int(rem_in)
frac16=round((rem_in-whole)*16)
if frac16==16:
whole+=1;frac16=0
if whole==12:
feet+=1;whole=0
def fs(f):
if f==0:return ""
if f%8==0:return f"{f//8}/2"
if f%4==0:return f"{f//4}/4"
if f%2==0:return f"{f//2}/8"
return f"{f}/16"
s=fs(frac16)
if feet>0:
imp=f"[{feet}']" if whole==0 and not s else (f"[{feet}'-{whole}]" if not s else f"[{feet}'-{whole} {s}\"]")
else:
imp="[0]" if whole==0 and not s else (f"[{whole}\"]" if not s else f"[{whole} {s}\"]")
return metric,imp
def _draw_title_block(c,cfg,pg,total,sheet_num,sheet_title,large_title,sub_title):
company=cfg.get("company",{})
c.setFillColor(WHITE)
c.rect(TB_X,0,TB_W,PAGE_H,fill=1,stroke=0)
c.setStrokeColor(NAVY)
c.setLineWidth(1.5)
c.line(TB_X,0,TB_X,PAGE_H)
c.saveState()
c.translate(TB_X-6,PAGE_H-8)
c.setFillColor(NAVY)
c.setFont(_FB,22)
c.drawRightString(0,-22,large_title)
c.setFont(_FR,11)
c.drawRightString(0,-38,sub_title)
c.restoreState()
# D1 FIX: clip the rotated sidebar text strictly inside the title-block column
# so it cannot bleed left into the drawing canvas on wide elevation pages.
c.saveState()
from reportlab.lib.utils import ImageReader
p = c.beginPath()
p.rect(TB_X, 0, TB_W, PAGE_H)
c.clipPath(p, stroke=0, fill=0)
c.translate(TB_X+TB_W/2.0,PAGE_H/2.0)
c.rotate(90)
half=PAGE_H/2.0
c.setFillColor(NAVY)
c.setFont(_FB,8)
c.drawCentredString(0,half-14,company.get("name","ITALIAN KITCHEN AND BATH"))
c.setFont(_FR,5)
c.drawCentredString(0,half-22,company.get("tagline","kitchen | bath | tile | closet"))
c.drawCentredString(0,half-29,company.get("address","1777 NW 72TH AVE. MIAMI FL, 33126"))
c.drawCentredString(0,half-35,company.get("phone","T. 305.599.9000"))
c.setStrokeColor(NAVY)
c.setLineWidth(0.5)
c.line(-28,half-40,28,half-40)
meta=[f"PROJECT #: {cfg.get('project_no','')}",cfg.get("project_name",""),sheet_title]
y0=-half+130
c.setFont(_FR,5.5)
for i,line in enumerate(meta):
c.drawCentredString(0,y0-i*9,line)
c.line(-28,y0-len(meta)*9-2,28,y0-len(meta)*9-2)
lm=[f"DATE: {cfg.get('date','')}",f"REV: {cfg.get('revision','')}",f"DIMENSION: {cfg.get('dimension','CM|INCHES')}",f"DRAWN BY: {cfg.get('drawn_by','A.C')}"]
y1=y0-len(meta)*9-10
c.setFont(_FR,5)
for i,line in enumerate(lm):
c.drawCentredString(0,y1-i*8,line)
sn_y=-half+28
c.setFont(_FR,5)
c.drawCentredString(0,sn_y+10,"SHEET NUMBER")
c.setFont(_FB,10)
c.drawCentredString(0,sn_y-2,sheet_num)
c.restoreState()
def _draw_border(c):
c.setStrokeColor(NAVY)
c.setLineWidth(0.75)
c.rect(MARGIN,MARGIN,DA_R-DA_L,PAGE_H-2*MARGIN,fill=0,stroke=1)
def _dim_horiz(c,x0,y0,x1,cm_val,above=True):
c.saveState()
c.setStrokeColor(BLACK)
c.setLineWidth(0.5)
c.line(x0,y0,x1,y0)
tk=4
for px in(x0,x1):
c.line(px-tk,y0-tk,px+tk,y0+tk)
metric,imperial=fmt_dual(cm_val)
cx=(x0+x1)/2.0
c.setFont(_FR,5)
c.setFillColor(BLACK)
if above:
c.drawCentredString(cx,y0+9,metric)
c.drawCentredString(cx,y0+3,imperial)
else:
c.drawCentredString(cx,y0-6,metric)
c.drawCentredString(cx,y0-12,imperial)
c.restoreState()
def _dim_vert(c,x0,y0,y1,cm_val,left=True):
c.saveState()
c.setStrokeColor(BLACK)
c.setLineWidth(0.5)
c.line(x0,y0,x0,y1)
tk=4
for py in(y0,y1):
c.line(x0-tk,py-tk,x0+tk,py+tk)
metric,imperial=fmt_dual(cm_val)
cy=(y0+y1)/2.0
c.setFont(_FR,5)
c.setFillColor(BLACK)
# We draw text horizontally for readability
if left:
c.drawRightString(x0 - 4, cy + 3, metric)
c.drawRightString(x0 - 4, cy - 3, imperial)
else:
c.drawString(x0 + 4, cy + 3, metric)
c.drawString(x0 + 4, cy - 3, imperial)
c.restoreState()
def _draw_hatch(c,x,y,w,h,spacing=5.0):
c.saveState()
c.setStrokeColor(HATCH)
c.setLineWidth(0.4)
p=c.beginPath()
p.rect(x,y,w,h)
c.clipPath(p,stroke=0,fill=0)
total=w+h
steps=int(total/spacing)+2
for i in range(-steps,steps+1):
ox2=x+i*spacing
c.line(ox2,y,ox2+h,y+h)
c.restoreState()
def _draw_cabinet_box(c,x,y,w,h,cab_type="base",label="",style="solid"):
c.saveState()
lw=0.75 if cab_type in("base","upper","vanity","sink_base") else 0.4
c.setStrokeColor(BLACK)
c.setLineWidth(lw)
c.setFillColor(WHITE)
if style=="dashed":
c.setDash(4,2)
c.rect(x,y,w,h,fill=1,stroke=1)
c.setDash()
toe_h=0
if cab_type in("base","sink_base","ada_base"):
toe_h=10.2
c.setLineWidth(0.5)
c.line(x,y+toe_h,x+w,y+toe_h)
# D4 FIX: per-door swing lines + handle icons instead of single blanket X
if cab_type not in("filler","panel","ada_base") and w>5:
door_y0=y+toe_h
door_y1=y+h
door_h=door_y1-door_y0
c.setLineWidth(0.4)
# Split wide cabinets into 2 door panels; narrow ones get 1 panel
n_doors = 2 if w > 45 else 1
door_w = w / n_doors
HANDLE_W = 2.5
HANDLE_H = 8.0
for d in range(n_doors):
dx0 = x + d * door_w
dx1 = dx0 + door_w
# Diagonal X per door panel
c.line(dx0, door_y0, dx1, door_y1)
c.line(dx1, door_y0, dx0, door_y1)
# Handle rectangle at the inner edge, vertically centred
hinge_side = dx1 if d == 0 else dx0 # handle on inside edge
h_x = hinge_side - HANDLE_W if d == 0 else hinge_side
h_y = door_y0 + (door_h - HANDLE_H) / 2.0
c.setLineWidth(0.5)
c.rect(h_x, h_y, HANDLE_W, HANDLE_H, fill=0, stroke=1)
if cab_type=="vanity":
# Drawer strip across the top 25% of the face
drawer_y=y+toe_h+(h-toe_h)*0.75
c.setLineWidth(0.5)
c.line(x,drawer_y,x+w,drawer_y)
if label:
lines=label.split("\n")
c.setFont(_FR,5.5)
c.setFillColor(NAVY)
mid_y=y+(h+toe_h)/2.0
for i,ln in enumerate(lines):
c.drawCentredString(x+w/2,mid_y+(len(lines)-1-i)*6.5-3,ln)
c.restoreState()
def _draw_refrigerator_elev(c,x,y,w,h,label="REFRIGERATOR"):
c.saveState()
c.setStrokeColor(BLACK)
c.setLineWidth(0.75)
c.setFillColor(LTGRAY)
c.rect(x,y,w,h,fill=1,stroke=1)
hx=x+w*0.85
c.setLineWidth(1.5)
c.setStrokeColor(BLACK)
c.line(hx,y+h*0.35,hx,y+h*0.65)
if label:
c.setFont(_FR,5)
c.setFillColor(BLACK)
lines=label.split("\n")
for i,ln in enumerate(reversed(lines)):
c.drawCentredString(x+w/2,y+h*0.3+i*7,ln)
c.restoreState()
def _draw_range_elev(c,x,y,w,h,is_ada=False):
c.saveState()
c.setStrokeColor(BLACK)
c.setLineWidth(0.75)
c.setFillColor(WHITE)
c.rect(x,y,w,h,fill=1,stroke=1)
c.setLineWidth(0.5)
row_y=y+h-15
for bx in[x+w*0.25,x+w*0.75]:
c.circle(bx,row_y,5,stroke=1,fill=0)
c.rect(x+5,y+10,w-10,h*0.5-10,stroke=1,fill=0)
if is_ada:
c.setFont(_FR,5)
c.setFillColor(NAVY)
c.drawCentredString(x+w/2,y+h/2,"ADA\nRANGE")
c.restoreState()
def _draw_floor_plan(c,k_data,ox,oy,scale,is_vanity=False):
wall_a=k_data.get("wall_a",{})
wall_b=k_data.get("wall_b",{})
layout=k_data.get("layout","straight")
len_a_cm=wall_a.get("length_cm",300.0)
len_b_cm=wall_b.get("length_cm",0.0) if wall_b else 0.0
depth_cm=61.0
len_a=len_a_cm*scale
len_b=len_b_cm*scale
depth=depth_cm*scale
wall_t=6.0*scale
c.saveState()
c.setStrokeColor(BLACK)
c.setLineWidth(1.5)
c.setFillColor(WHITE)
if layout=="L-shape" and len_b>0:
# Wall A is at the top (horizontal), Wall B goes down (vertical) from the right corner
# Wall outline
p=c.beginPath()
p.moveTo(ox,oy+depth)
p.lineTo(ox,oy+depth+wall_t)
p.lineTo(ox+len_a,oy+depth+wall_t)
p.lineTo(ox+len_a,oy+depth+wall_t-len_b)
p.lineTo(ox+len_a-wall_t,oy+depth+wall_t-len_b)
p.lineTo(ox+len_a-wall_t,oy+depth)
p.close()
c.drawPath(p,stroke=1,fill=0)
# Hatches
_draw_hatch(c,ox,oy+depth,len_a,wall_t)
_draw_hatch(c,ox+len_a-wall_t,oy+depth+wall_t-len_b,wall_t,len_b-wall_t)
# Cabinet bodies
c.setFillColor(WHITE)
c.setLineWidth(1.0)
# Wall A cabinets
c.rect(ox,oy,len_a-wall_t,depth,fill=1,stroke=1)
# Wall B cabinets (extending down)
c.rect(ox+len_a-depth-wall_t, oy+depth+wall_t-len_b, depth, len_b-depth-wall_t, fill=1, stroke=1)
# Appliances
_draw_floor_plan_appliances(c,wall_a,ox,oy,depth,scale)
# We need to draw Wall B appliances. They should face left.
# But for now, Wall B only has a fridge in K1/K3, and no complex appliances on Wall B for the others.
# Let's draw Wall B appliances if any:
cx_b = oy + depth + wall_t - len_b
for cab in reversed(wall_b.get("cabinets", [])):
w_pt = cab.get("width_cm", 30) * scale
ctype = cab.get("type", "base")
cab_id = cab.get("id", "")
# Skip Wall A return overlapping corner
if "RETURN" in cab_id:
cx_b += w_pt
continue
bx = ox + len_a - depth - wall_t
by = cx_b
if ctype == "refrigerator":
c.setFillColor(LTGRAY)
c.setStrokeColor(BLACK)
c.setLineWidth(0.6)
c.rect(bx, by, depth, w_pt, fill=1, stroke=1)
c.saveState()
c.translate(bx + depth/2, by + w_pt/2)
c.rotate(-90)
c.setFont(_FR, 5)
c.setFillColor(BLACK)
c.drawCentredString(0, 0, "REF")
c.restoreState()
else:
c.setFillColor(WHITE)
c.setStrokeColor(BLACK)
c.setLineWidth(0.5)
c.rect(bx, by, depth, w_pt, fill=1, stroke=1)
cx_b += w_pt
# Dimensions
_dim_horiz(c,ox,oy+depth+wall_t+15,ox+len_a,len_a_cm, above=True)
_dim_vert(c,ox+len_a+25,oy+depth+wall_t-len_b,oy+depth+wall_t,len_b_cm, left=False)
elif layout == "parallel" and len_b > 0:
gap = 120.0 * scale
oy_b = oy + depth + gap
# Wall A
c.rect(ox, oy+depth, len_a, wall_t, fill=0, stroke=1)
_draw_hatch(c, ox, oy+depth, len_a, wall_t)
c.setLineWidth(1.0)
c.rect(ox, oy, len_a, depth, fill=1, stroke=1)
_draw_floor_plan_appliances(c, wall_a, ox, oy, depth, scale)
_dim_horiz(c, ox, oy-15, ox+len_a, len_a_cm)
# Wall B
c.rect(ox, oy_b, len_b, wall_t, fill=0, stroke=1)
_draw_hatch(c, ox, oy_b, len_b, wall_t)
c.setLineWidth(1.0)
c.rect(ox, oy_b-depth, len_b, depth, fill=1, stroke=1)
# Note: Appliances for Wall B would face downwards in reality.
else:
c.rect(ox,oy+depth,len_a,wall_t,fill=0,stroke=1)
_draw_hatch(c,ox,oy+depth,len_a,wall_t)
c.setLineWidth(1.0)
c.rect(ox,oy,len_a,depth,fill=1,stroke=1)
_draw_floor_plan_appliances(c,wall_a,ox,oy,depth,scale)
_dim_horiz(c,ox,oy-15,ox+len_a,len_a_cm)
# Draw Elevation Callouts
c.setLineWidth(1.0)
c.setStrokeColor(BLACK)
if layout == "L-shape":
# Callout A (Below Wall A, looking UP)
ca_x = ox + len_a / 2
ca_y = oy - 40
c.setFillColor(WHITE)
c.circle(ca_x, ca_y, 10, stroke=1, fill=1)
c.setFillColor(BLACK)
c.setFont(_FB, 8)
c.drawCentredString(ca_x, ca_y-3, "A")
p = c.beginPath()
p.moveTo(ca_x - 4, ca_y + 10)
p.lineTo(ca_x + 4, ca_y + 10)
p.lineTo(ca_x, ca_y + 18)
p.close()
c.drawPath(p, stroke=1, fill=1)
else:
# Callout A (Above Wall A, looking DOWN for standard straight, or below for others)
ca_x = ox + len_a / 2
ca_y = oy + depth + 40
c.setFillColor(WHITE)
c.circle(ca_x, ca_y, 10, stroke=1, fill=1)
c.setFillColor(BLACK)
c.setFont(_FB, 8)
c.drawCentredString(ca_x, ca_y-3, "A")
p = c.beginPath()
p.moveTo(ca_x - 4, ca_y - 10)
p.lineTo(ca_x + 4, ca_y - 10)
p.lineTo(ca_x, ca_y - 18)
p.close()
c.drawPath(p, stroke=1, fill=1)
if len_b > 0 and layout == "L-shape":
# Callout for Wall B (Left of Wall B, looking RIGHT)
cb_x = ox + len_a - depth - wall_t - 40
cb_y = oy + depth + wall_t - len_b / 2
c.setFillColor(WHITE)
c.circle(cb_x, cb_y, 10, stroke=1, fill=1)
c.setFillColor(BLACK)
c.setFont(_FB, 8)
c.drawCentredString(cb_x, cb_y-3, "B")
p = c.beginPath()
p.moveTo(cb_x + 10, cb_y - 4)
p.lineTo(cb_x + 10, cb_y + 4)
p.lineTo(cb_x + 18, cb_y)
p.close()
c.drawPath(p, stroke=1, fill=1)
elif len_b > 0 and layout == "parallel":
# Callout for Wall B (Top wall, looking DOWN)
cb_x = ox + len_b / 2
cb_y = oy_b - depth - 40
c.setFillColor(WHITE)
c.circle(cb_x, cb_y, 10, stroke=1, fill=1)
c.setFillColor(BLACK)
c.setFont(_FB, 8)
c.drawCentredString(cb_x, cb_y-3, "B")
p = c.beginPath()
p.moveTo(cb_x - 4, cb_y - 10)
p.lineTo(cb_x + 4, cb_y - 10)
p.lineTo(cb_x, cb_y - 18)
p.close()
c.drawPath(p, stroke=1, fill=1)
c.restoreState()
def _draw_floor_plan_appliances(c,wall_data,ox,oy,depth,scale):
cabinets=wall_data.get("cabinets",[])
cx=ox
for cab in cabinets:
w_pt=cab.get("width_cm",30)*scale
ctype=cab.get("type","base")
if ctype=="refrigerator":
c.setFillColor(LTGRAY)
c.setStrokeColor(BLACK)
c.setLineWidth(0.6)
c.rect(cx,oy,w_pt,depth,fill=1,stroke=1)
c.setFont(_FR,5)
c.setFillColor(BLACK)
c.drawCentredString(cx+w_pt/2,oy+depth/2,"REF")
elif ctype=="sink_base":
c.setFillColor(WHITE)
c.setStrokeColor(BLACK)
c.setLineWidth(0.6)
c.rect(cx,oy,w_pt,depth,fill=1,stroke=1)
c.ellipse(cx+w_pt*0.15,oy+depth*0.2,cx+w_pt*0.85,oy+depth*0.8,stroke=1,fill=0)
elif "range" in ctype or cab.get("label","").upper().startswith("RANGE"):
c.setFillColor(WHITE)
c.setStrokeColor(BLACK)
c.setLineWidth(0.6)
c.rect(cx,oy,w_pt,depth,fill=1,stroke=1)
for bx,bd in[(0.3,0.3),(0.3,0.7),(0.7,0.3),(0.7,0.7)]:
c.circle(cx+w_pt*bx,oy+depth*bd,depth*0.1,stroke=1,fill=0)
else:
c.setFillColor(WHITE)
c.setStrokeColor(BLACK)
c.setLineWidth(0.5)
c.rect(cx,oy,w_pt,depth,fill=1,stroke=1)
cx+=w_pt
def _get_actual_wall_length(wall_data):
if not wall_data: return 0.0
length_cm = wall_data.get("length_cm", 300.0)
# Calculate max base cabinet extent
cab_x_cm = 0.0
for cab in wall_data.get("cabinets", []):
cab_x_cm += cab.get("width_cm", 30.0)
max_extent = max(length_cm, cab_x_cm)
# Check upper cabinets extent
uppers = wall_data.get("uppers", [])
total_upper_w_cm = sum(uc.get("width_cm", 30.0) for uc in uppers)
tall_width = sum(cab.get("width_cm", 0.0) for cab in wall_data.get("cabinets", []) if "ref" in cab.get("type", "").lower() or "tall" in cab.get("type", "").lower() or "pantry" in cab.get("type", "").lower())
cab_x_cm_uppers = max(length_cm - total_upper_w_cm, tall_width)
if cab_x_cm_uppers + total_upper_w_cm > max_extent:
max_extent = cab_x_cm_uppers + total_upper_w_cm
return max_extent
def _auto_scale(total_w_cm, available_pt, ceiling_cm=243.84, available_h_pt=None):
"""Compute a uniform scale (pts/cm) that fits the wall width AND ceiling height."""
if total_w_cm <= 0:
return 1.2
scale_w = (available_pt * 0.88) / total_w_cm
if available_h_pt and ceiling_cm > 0:
# leave 60pt margin inside the drawing area for dim lines above
scale_h = (available_h_pt - 60.0) / ceiling_cm
return min(1.6, scale_w, scale_h)
return min(1.6, scale_w)
def _draw_elevation_view(c, wall_data, ox, oy, scale, ceiling_cm, is_ada, elev_label, kitchen_label, show_countertop=True):
from core.engines.elevation_generator import ElevationGenerator
IN = 2.54
# ── 1. Build base_cfg — base/tall/appliance cabinets (cm → inches) ──────────
# Each dict has no "x" key — ElevationLayout.build_two_tier() owns placement.
base_cfg: list = []
base_run_w_cm = 0.0
for cab in wall_data.get("cabinets", []):
w_cm = cab.get("width_cm", 30.0)
h_cm = cab.get("height_cm", 86.36 if not is_ada else 81.28)
base_cfg.append({
"id": cab.get("id", cab.get("cabinet_id", cab.get("type", "base"))),
"label": cab.get("label", ""),
"type": cab.get("type", "base"),
"width": w_cm / IN,
"height": h_cm / IN,
"is_ada": is_ada,
})
base_run_w_cm += w_cm
# ── 2. Build upper_cfg — wall/upper cabinets (cm → inches) ───────────────
# Upper cursor is positioned automatically by build_two_tier() at the
# right edge of the REF/tall column (or x=0 if none). No spacer needed.
upper_cfg: list = []
for uc in wall_data.get("uppers", []):
w_cm = uc.get("width_cm", 30.0)
h_cm = uc.get("height_cm", 76.20)
upper_cfg.append({
"id": uc.get("id", uc.get("cabinet_id", uc.get("type", "upper"))),
"label": uc.get("label", ""),
"type": "upper",
"width": w_cm / IN,
"height": h_cm / IN,
"is_ada": is_ada,
})
# ── 3. Vanity elevation — automatic toilet injection removed ───────────────
# Toilets must now be explicitly defined in project_config.json to support
# varied placements (e.g., left vs right of vanity).
# ── 4. Compute drawn wall length ──────────────────────────────────────────
drawn_length_cm = max(wall_data.get("length_cm", 300.0), base_run_w_cm)
walls = [{
"name": elev_label,
"length": drawn_length_cm / IN,
"base_cfg": base_cfg,
"upper_cfg": upper_cfg,
}]
scale_inch = scale * IN
geom = ElevationGenerator.generate(
walls=walls,
start_ox=ox,
start_oy=oy,
ceiling_height=ceiling_cm / IN,
scale_x=scale_inch,
scale_y=scale_inch,
)
c.saveState()
# D1 FIX: Clip drawing to canvas so nothing spills off the page (e.g. overlong dimension lines)
p = c.beginPath()
# Using DA_L, DA_B, DA_R, DA_T from global scope
p.rect(DA_L, DA_B, DA_R - DA_L, DA_T - DA_B)
c.clipPath(p, stroke=0, fill=0)
# Draw blocks
for block in geom.get("blocks", []):
if block.get("type") == "rect":
bx, by, bw, bh = block["coords"]
lw = 1.5 if block.get("layer") == "WALLS" else 0.5
c.setLineWidth(lw)
c.setStrokeColorRGB(0, 0, 0)
if block.get("layer") == "DOOR_PANEL":
c.setFillColorRGB(0.98, 0.98, 0.98)
else:
c.setFillColorRGB(1, 1, 1)
c.rect(bx, by, bw, bh, fill=1, stroke=1)
elif block.get("type") == "circle":
cx, cy, r = block["coords"]
c.setLineWidth(0.5)
c.circle(cx, cy, r, fill=1, stroke=1)
# Draw lines
for line in geom.get("lines", []):
c.setLineWidth(1.5 if line.get("layer") == "WALLS" else 0.5)
c.setStrokeColorRGB(0, 0, 0)
if line.get("style") == "dashed":
c.setDash(4, 2)
else:
c.setDash()
s = line["start"]
e = line["end"]
c.line(s[0], s[1], e[0], e[1])
c.setDash()
# Draw text
for txt in geom.get("texts", []):
x, y = txt["pos"]
c.setFillColorRGB(0, 0, 0)
c.setFont("Helvetica", 6)
c.drawString(x, y, txt["text"])
# Draw dimensions (using legacy _dim_horiz and _dim_vert to preserve style)
for dim in geom.get("dimensions", []):
s, e = dim["start"], dim["end"]
if abs(s[1] - e[1]) < 0.1: # horizontal
val_in = abs(e[0] - s[0]) / scale_inch
val_cm = val_in * IN
_dim_horiz(c, s[0], s[1], e[0], val_cm, above=False)
else: # vertical
val_in = abs(e[1] - s[1]) / scale_inch
val_cm = val_in * IN
_dim_vert(c, s[0], s[1], e[1], val_cm, left=True)
# Draw title
c.setFont("Helvetica-Bold", 10)
c.setFillColorRGB(0, 0, 0)
c.drawString(ox, oy - 48, f"ELEVATION {elev_label}")
c.setFont("Helvetica", 6)
c.drawString(ox, oy - 58, kitchen_label)
c.restoreState()
def draw_kitchen_sheet(c,cfg,k_key,pg,total):
k_data=cfg.get("kitchen_types",{}).get(k_key,{})
k_label=k_data.get("label",k_key)
unit_ref=k_data.get("unit_ref","")
is_ada=k_data.get("is_ada",False)
wall_a=k_data.get("wall_a",{})
wall_b=k_data.get("wall_b",{})
ceiling_cm=243.84 # 96 inches = 8 ft standard ceiling
sheet_title="KITCHEN | VANITIES"
large_title=k_label
sub_title=unit_ref
# ── PAGE 1: FLOOR PLAN ───────────────────────────────────────────────────
pg+=1
_draw_border(c)
_draw_title_block(c,cfg,pg,total,f"A.{pg-2}",sheet_title,large_title,sub_title)
fp_area_w=(DA_R-DA_L)*0.65
fp_area_h=(DA_T-DA_B)*0.55
len_a_cm=wall_a.get("length_cm",300.0)
len_b_cm=wall_b.get("length_cm",0.0) if wall_b else 0.0
fp_scale=min(fp_area_w/max(len_a_cm,1),fp_area_h/max(len_b_cm+61.0,100.0))
fp_scale=min(fp_scale,1.8)
fp_ox=DA_L+60
fp_oy=DA_T-fp_area_h-30
_draw_floor_plan(c,k_data,fp_ox,fp_oy,fp_scale)
c.setFont(_FB,10)
c.setFillColor(BLACK)
c.drawString(fp_ox,fp_oy-40,'FLOOR PLAN SCALE 1/2"=1\'-0"')
c.setFont(_FR,7)
c.drawString(fp_ox,fp_oy-52,f"CASA FAMILIA {unit_ref} / {k_label}")
c.showPage()
# ── PAGE 2: ELEVATIONS A+B ────────────────────────────────────────────────
pg+=1
# Check if we need portrait mode (very long walls)
elev_a_len_cm = _get_actual_wall_length(wall_a)
elev_b_len_cm = _get_actual_wall_length(wall_b)
wall_b_cabs = (wall_b.get("cabinets", []) + wall_b.get("uppers", [])) if wall_b else []
has_b = elev_b_len_cm > 0 and len(wall_b_cabs) > 0
is_stacked = False # Force side-by-side layout
if is_stacked:
# TRUE PORTRAIT PAGE
c.setPageSize((PAGE_H, PAGE_W))
# Dimensions for Portrait
CUR_W = PAGE_H
CUR_H = PAGE_W
# Title Block at the BOTTOM
tb_h = 60
da_l = MARGIN
da_r = CUR_W - MARGIN
da_b = MARGIN + tb_h
da_t = CUR_H - MARGIN
c.setStrokeColor(NAVY)
c.setLineWidth(0.75)
# Border
c.rect(da_l, MARGIN, da_r - da_l, CUR_H - 2*MARGIN, fill=0, stroke=1)
# Title block separator
c.line(da_l, da_b, da_r, da_b)
# Draw bottom title block
company = cfg.get("company", {})
c.setFillColor(NAVY)
c.setFont(_FB, 8)
c.drawString(da_l + 10, MARGIN + 40, company.get("name", "ITALIAN KITCHEN AND BATH"))
c.setFont(_FR, 6)
c.drawString(da_l + 10, MARGIN + 30, company.get("tagline", "kitchen | bath | tile | closet"))
c.drawString(da_l + 10, MARGIN + 20, company.get("address", "1777 NW 72TH AVE. MIAMI FL, 33126"))
c.drawString(da_l + 10, MARGIN + 10, company.get("phone", "T. 305.599.9000"))
meta = [f"PROJECT #: {cfg.get('project_no', '')}", cfg.get("project_name", ""), sheet_title]
c.setFont(_FR, 7)
for i, line in enumerate(meta):
c.drawString(da_l + 250, MARGIN + 40 - i*12, line)
lm = [f"DATE: {cfg.get('date', '')}", f"REV: {cfg.get('revision', '')}", f"DIMENSION: {cfg.get('dimension', 'CM|INCHES')}", f"DRAWN BY: {cfg.get('drawn_by', 'A.C')}"]
for i, line in enumerate(lm):
c.drawString(da_l + 450, MARGIN + 40 - i*12, line)
c.setFont(_FR, 6)
c.drawString(da_r - 80, MARGIN + 40, "SHEET NUMBER")
c.setFont(_FB, 14)
c.drawRightString(da_r - 20, MARGIN + 20, f"A.{pg-2}")
canvas_w = da_r - da_l
canvas_h = da_t - da_b
half_h = canvas_h / 2.0
avail_h_per_elev = half_h - 60
scale_a = _auto_scale(elev_a_len_cm, canvas_w - 60, ceiling_cm, avail_h_per_elev)
scale_b = _auto_scale(elev_b_len_cm, canvas_w - 60, ceiling_cm, avail_h_per_elev)
elev_h_a = ceiling_cm * scale_a
elev_h_b = ceiling_cm * scale_b
# Override global DA bounds temporarily for drawing
old_DA_L, old_DA_B, old_DA_R, old_DA_T = globals()['DA_L'], globals()['DA_B'], globals()['DA_R'], globals()['DA_T']
globals()['DA_L'], globals()['DA_B'], globals()['DA_R'], globals()['DA_T'] = da_l, da_b, da_r, da_t
elev_a_oy = da_b + half_h + 40 + (avail_h_per_elev - elev_h_a) / 2.0
elev_b_oy = da_b + 40 + (avail_h_per_elev - elev_h_b) / 2.0
elev_a_ox = da_l + 30
elev_b_ox = da_l + 30
_draw_elevation_view(c, wall_a, elev_a_ox, elev_a_oy, scale_a, ceiling_cm, is_ada, "A", f"CASA FAMILIA {unit_ref} / {k_label}")
if has_b:
_draw_elevation_view(c, wall_b, elev_b_ox, elev_b_oy, scale_b, ceiling_cm, is_ada, "B", f"CASA FAMILIA {unit_ref} / {k_label}")
globals()['DA_L'], globals()['DA_B'], globals()['DA_R'], globals()['DA_T'] = old_DA_L, old_DA_B, old_DA_R, old_DA_T
c.setPageSize((PAGE_W, PAGE_H))
else:
_draw_border(c)
_draw_title_block(c,cfg,pg,total,f"A.{pg-2}",sheet_title,large_title,sub_title)
canvas_w = DA_R - DA_L
canvas_h = DA_T - DA_B
avail_elev_h = canvas_h - 80 - 50
if has_b:
half_w = canvas_w / 2.0 - 40
scale_a = _auto_scale(elev_a_len_cm, half_w, ceiling_cm, avail_elev_h)
scale_b = _auto_scale(elev_b_len_cm, half_w, ceiling_cm, avail_elev_h)
elev_h_a = ceiling_cm * scale_a
elev_h_b = ceiling_cm * scale_b
elev_a_oy = DA_B + 80 + (avail_elev_h - elev_h_a) / 2.0
elev_b_oy = DA_B + 80 + (avail_elev_h - elev_h_b) / 2.0
elev_a_ox = DA_L + 30
elev_b_ox = DA_L + canvas_w / 2.0 + 20
else:
half_w = canvas_w - 60
scale_a = _auto_scale(elev_a_len_cm, half_w, ceiling_cm, avail_elev_h)
elev_h_a = ceiling_cm * scale_a
elev_a_oy = DA_B + 80 + (avail_elev_h - elev_h_a) / 2.0
elev_a_ox = DA_L + 30
_draw_elevation_view(c, wall_a, elev_a_ox, elev_a_oy, scale_a, ceiling_cm, is_ada, "A", f"CASA FAMILIA {unit_ref} / {k_label}")
if has_b:
_draw_elevation_view(c, wall_b, elev_b_ox, elev_b_oy, scale_b, ceiling_cm, is_ada, "B", f"CASA FAMILIA {unit_ref} / {k_label}")
c.showPage()
return pg
def draw_vanity_sheet(c,cfg,v_key,pg,total):
v_data=cfg.get("vanity_types",{}).get(v_key,{})
v_label=v_data.get("label",v_key)
unit_ref=v_data.get("unit_ref","")
is_ada=v_data.get("is_ada",False)
wall_a=v_data.get("wall_a",{})
sheet_title="KITCHEN | VANITIES"
large_title=v_label
sub_title=unit_ref
# ── Determine vanity ceiling height from actual cabinet heights ────────
# Vanity base cabinets are ~32-34.5" tall; use actual max height + 8" overhead
# so the wall box closely frames the cabinets (not an 8-ft blank wall).
IN = 2.54
cabs_a = wall_a.get("cabinets", [])
if cabs_a:
max_cab_h_cm = max(c.get("height_cm", 81.28 if is_ada else 86.36) for c in cabs_a)
else:
max_cab_h_cm = 81.28 if is_ada else 86.36
# toe-kick 4" + cabinet body + 8" overhead clearance (for mirror/splash above)
vanity_ceiling_in = max_cab_h_cm / IN + 16.0 # ~16" overhead above cabinet
ceiling_cm = vanity_ceiling_in * IN
pg+=1
_draw_border(c)
_draw_title_block(c,cfg,pg,total,f"A.{pg-2}",sheet_title,large_title,sub_title)
canvas_w = DA_R - DA_L
canvas_h = DA_T - DA_B
# Floor plan occupies top ~35% of the canvas
fp_area_h = canvas_h * 0.35
fp_w_cm = v_data.get("floor_plan_width_cm", _get_actual_wall_length(wall_a))
fp_area_w = canvas_w * 0.55
fp_scale = min(fp_area_w / max(fp_w_cm, 1), 2.0)
fp_ox = DA_L + 60
fp_oy = DA_T - fp_area_h
vfp_data = {"wall_a": wall_a, "wall_b": {}, "layout": "straight"}
_draw_floor_plan(c, vfp_data, fp_ox, fp_oy, fp_scale, is_vanity=True)
c.setFont(_FB, 10)
c.setFillColor(BLACK)
c.drawString(fp_ox, fp_oy - 40, 'FLOOR PLAN SCALE 1/2"=1\'-0"')
c.setFont(_FR, 7)
c.drawString(fp_ox, fp_oy - 52, f"CASA FAMILIA {unit_ref} / {v_label}")
# Elevation occupies bottom ~60% of the canvas
avail_elev_h = canvas_h * 0.58 - 80
el_len_cm = _get_actual_wall_length(wall_a)
if is_ada:
# Split width into 3 sections: Elevation A (50%), Section (25%), Side View (25%)
elev_w = canvas_w * 0.45
sec_w = canvas_w * 0.20
side_w = canvas_w * 0.20
scale_el = _auto_scale(el_len_cm, elev_w, ceiling_cm, avail_elev_h)
elev_h = ceiling_cm * scale_el
elev_oy = DA_B + 80 + (avail_elev_h - elev_h) / 2.0
# 1. Elevation A
elev_ox = DA_L + 20
_draw_elevation_view(c, wall_a, elev_ox, elev_oy, scale_el, ceiling_cm, is_ada, "A",
f"CASA FAMILIA {unit_ref} / {v_label}", show_countertop=True)
# 2. Section
sec_ox = elev_ox + elev_w + 30
_draw_ada_profile(c, sec_ox, elev_oy, scale_el, ceiling_cm, is_section=True, label=f"CASA FAMILIA {unit_ref}/ {v_label}")
# 3. Side View
side_ox = sec_ox + sec_w + 30
_draw_ada_profile(c, side_ox, elev_oy, scale_el, ceiling_cm, is_section=False, label=f"CASA FAMILIA / {v_label}")
else:
elev_area_w = canvas_w * 0.90
scale_el = _auto_scale(el_len_cm, elev_area_w, ceiling_cm, avail_elev_h)
elev_h = ceiling_cm * scale_el
elev_ox = DA_L + 30
elev_oy = DA_B + 80 + (avail_elev_h - elev_h) / 2.0
_draw_elevation_view(c, wall_a, elev_ox, elev_oy, scale_el, ceiling_cm, is_ada, "A",
f"CASA FAMILIA {unit_ref} / {v_label}", show_countertop=True)
c.showPage()
return pg
def _draw_ada_profile(c, ox, oy, scale, ceiling_cm, is_section, label):
"""Draws the section or side profile of an ADA vanity."""
IN = 2.54
# Geometry constants (inches)
ctop_h = 34.0 # 86.36 cm
ctop_thick = 0.75 # 1.91 cm
ctop_depth = 24.0 # 61.0 cm
apron_h = 6.0 # 15.24 cm
knee_clear = 27.0 # 68.58 cm
# Back wall line
c.setLineWidth(1)
c.line(ox, oy, ox, oy + ceiling_cm / IN * scale)
# Countertop Profile
cx = ox
cy = oy + (ctop_h - ctop_thick) * scale
c.rect(cx, cy, ctop_depth * scale, ctop_thick * scale, stroke=1, fill=0)
if is_section:
# Apron/Panel (front drop)
c.rect(cx + (ctop_depth - 1) * scale, oy + knee_clear * scale, 1.0 * scale, apron_h * scale, stroke=1, fill=0)
# Bracket
c.setLineWidth(1.5)
c.line(cx, oy + (knee_clear + 3) * scale, cx + (ctop_depth - 3) * scale, oy + (knee_clear + 3) * scale) # Top horizontal
c.line(cx, oy + (knee_clear - 8) * scale, cx, oy + (knee_clear + 3) * scale) # Back vertical
c.line(cx, oy + (knee_clear - 8) * scale, cx + (ctop_depth - 3) * scale, oy + (knee_clear + 3) * scale) # Diagonal
c.setLineWidth(1)
# Annotation for bracket
c.setFont(_FR, 6)
c.drawString(cx + 8 * scale, oy + (knee_clear - 5) * scale, "BRACKET TO")
c.drawString(cx + 8 * scale, oy + (knee_clear - 6.5) * scale, "CLICK PANEL")
else:
# Side View (solid panel)
c.rect(cx, oy + 9 * scale, ctop_depth * scale, (ctop_h - ctop_thick - 9) * scale, stroke=1, fill=0)
c.setFont(_FR, 5)
c.drawCentredString(cx + ctop_depth/2 * scale, oy + 20 * scale, "FINISHED")
c.drawCentredString(cx + ctop_depth/2 * scale, oy + 18 * scale, "PANEL")
# Dimensions
dim_cx = ox + ctop_depth/2 * scale
_dim_horiz(c, ox, oy + (ctop_h + 4) * scale, ox + ctop_depth * scale, 61.00)
dim_y_right = ox + ctop_depth * scale + 15
_dim_vert(c, dim_y_right, oy + knee_clear * scale, oy + ctop_h * scale, 1.91, left=False) # ctop
if is_section:
_dim_vert(c, dim_y_right, oy + (knee_clear - apron_h) * scale, oy + knee_clear * scale, 15.24, left=False) # apron
# Title
title = "SECTION" if is_section else "SIDE VIEW"
c.setFont(_FB, 12)
c.drawString(ox, oy - 25, title)
c.setFont(_FB, 9)
c.drawString(ox + c.stringWidth(title, _FB, 12) + 5, oy - 25, 'SCALE 1/2"=1\'-0"')
c.setFont(_FR, 8)
c.drawString(ox, oy - 37, label)
+381 -200
View File
@@ -4,6 +4,15 @@
===========================================================================
Translates coordinate lines, annotations, and boxes into AutoCAD-compatible
dxf files using ezdxf.
B1 FIX: DASHED linetype + DOOR_PANEL layer registered so cabinet_renderer
swing/shelf lines (style="dashed") render correctly in CAD viewers
and matplotlib PDF export.
B2 FIX: char_height and dimtxt are now proportional to wall_length_in,
not hardcoded 2.5/2.0. Same _txt_h() logic as the ReportLab path.
B3 FIX: Each wall/elevation region gets its own named DXF Layout (paper
space), and qsave() is called per-layout so the exported PDF
contains one page per elevation instead of one giant merged strip.
===========================================================================
"""
from __future__ import annotations
@@ -16,227 +25,399 @@ try:
except ImportError:
qsave = None
class DXFDrawingGenerator:
"""
Generates dxf CAD vector files for units and elevations.
"""
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _txt_h(wall_length_in: float, base_scale: float = 0.012, minimum: float = 0.5) -> float:
"""Return a text/dim height proportional to wall_length_in."""
return max(wall_length_in * base_scale, minimum)
def _setup_doc(doc: "ezdxf.document.Drawing") -> None:
"""Register all layers and linetypes once on a fresh document."""
try:
doc.linetypes.add(
name="DASHED",
pattern=[0.5, 0.25, -0.125],
description="Dashed ____ ____ ____",
)
except Exception:
pass
_layers = [
("WALLS", 7),
("WALLS_HIDDEN", 8),
("WALLS_DEMO", 1),
("WALLS_SECTION", 7),
("CENTERLINES", 3),
("CABINETS_BASE", 4),
("CABINETS_UPPER", 2),
("CABINETS_SECTION", 4),
("COUNTERTOP_SECTION", 6),
("SOFFIT", 8),
("SOFFIT_SECTION", 8),
("BACKSPLASH_SECTION", 5),
("MOLDING_SECTION", 6),
("APPLIANCES", 7),
("SINK", 8),
("HANDLES", 7),
("SWING", 8),
("DOOR_PANEL", 4),
("GROUND", 8),
("CEILING", 8),
("DIMENSIONS", 8),
("TEXT", 7),
("ANNOTATION", 2),
("ANNOTATION_TEXT", 7),
("REVISIONS", 1),
("TITLEBLOCK", 7),
]
for name, color in _layers:
if name not in doc.layers:
doc.layers.add(name, dxfattribs={"color": color})
# Build Standard DXF Block Library
try:
if "REF_BLOCK" not in doc.blocks:
ref_blk = doc.blocks.new(name="REF_BLOCK")
# 1x1 base scaled on insertion
ref_blk.add_lwpolyline([(0,0), (1,0), (1,1), (0,1), (0,0)], dxfattribs={"layer": "APPLIANCES"})
ref_blk.add_line((0.5, 0), (0.5, 1), dxfattribs={"layer": "APPLIANCES"}) # door split
ref_blk.add_line((0.45, 0.4), (0.45, 0.6), dxfattribs={"layer": "HANDLES"})
ref_blk.add_line((0.55, 0.4), (0.55, 0.6), dxfattribs={"layer": "HANDLES"})
if "RANGE_BLOCK" not in doc.blocks:
range_blk = doc.blocks.new(name="RANGE_BLOCK")
range_blk.add_lwpolyline([(0,0), (1,0), (1,1), (0,1), (0,0)], dxfattribs={"layer": "APPLIANCES"})
range_blk.add_lwpolyline([(0.1,0.2), (0.9,0.2), (0.9,0.7), (0.1,0.7), (0.1,0.2)], dxfattribs={"layer": "APPLIANCES"}) # oven window
range_blk.add_circle((0.2, 0.85), 0.05, dxfattribs={"layer": "APPLIANCES"})
range_blk.add_circle((0.8, 0.85), 0.05, dxfattribs={"layer": "APPLIANCES"})
if "DW_BLOCK" not in doc.blocks:
dw_blk = doc.blocks.new(name="DW_BLOCK")
dw_blk.add_lwpolyline([(0,0), (1,0), (1,1), (0,1), (0,0)], dxfattribs={"layer": "APPLIANCES"})
dw_blk.add_line((0, 0.85), (1, 0.85), dxfattribs={"layer": "APPLIANCES"}) # control panel
if "SINK_BLOCK" not in doc.blocks:
sink_blk = doc.blocks.new(name="SINK_BLOCK")
sink_blk.add_lwpolyline([(0.05,0.05), (0.95,0.05), (0.95,0.95), (0.05,0.95), (0.05,0.05)], dxfattribs={"layer": "SINK"})
sink_blk.add_circle((0.5, 0.5), 0.08, dxfattribs={"layer": "SINK"}) # drain
except Exception as e:
print(f" [WARN] Could not setup standard DXF blocks: {e}")
def _write_geom_to_space(
geom: dict,
space,
y_offset: float,
x_offset: float,
wall_length_in: float,
) -> None:
th = _txt_h(wall_length_in)
dim_txt = max(th * 0.9, 0.4)
has_block_refs = len(geom.get("block_refs", [])) > 0
for line in geom.get("lines", []):
if has_block_refs and line.get("is_legacy_appliance"):
continue
layer = line.get("layer", "WALLS")
ltype = "DASHED" if line.get("style") == "dashed" else "CONTINUOUS"
s = (line["start"][0] + x_offset, line["start"][1] + y_offset)
e = (line["end"][0] + x_offset, line["end"][1] + y_offset)
space.add_line(s, e, dxfattribs={"layer": layer, "linetype": ltype})
for block in geom.get("blocks", []):
if has_block_refs and block.get("is_legacy_appliance"):
continue
layer = block.get("layer", "CABINETS_BASE")
ltype = "DASHED" if block.get("style") == "dashed" else "CONTINUOUS"
if block.get("type") == "circle":
cx, cy, r = block["coords"]
space.add_circle(
(cx + x_offset, cy + y_offset), r,
dxfattribs={"layer": layer}
)
else:
bx, by, bw, bh = block["coords"]
bx += x_offset
by += y_offset
pts = [(bx, by), (bx + bw, by), (bx + bw, by + bh), (bx, by + bh), (bx, by)]
space.add_lwpolyline(pts, dxfattribs={"layer": layer, "linetype": ltype})
for txt in geom.get("texts", []):
layer = txt.get("layer", "TEXT")
px = txt["pos"][0] + x_offset
py = txt["pos"][1] + y_offset
from ezdxf.enums import MTextEntityAlignment
align = MTextEntityAlignment.TOP_CENTER if txt.get("anchor") == "center" else MTextEntityAlignment.TOP_LEFT
space.add_mtext(
txt["text"],
dxfattribs={"layer": layer, "char_height": th}
).set_location((px, py), attachment_point=align)
for bref in geom.get("block_refs", []):
try:
name = bref.get("name")
bx, by = bref.get("coords", [0, 0])
sx, sy = bref.get("scale", [1, 1])
layer = bref.get("layer", "APPLIANCES")
space.add_blockref(
name,
(bx + x_offset, by + y_offset),
dxfattribs={"layer": layer, "xscale": sx, "yscale": sy}
)
except Exception as e:
pass
for dim in geom.get("dimensions", []):
s = (dim["start"][0] + x_offset, dim["start"][1] + y_offset)
e = (dim["end"][0] + x_offset, dim["end"][1] + y_offset)
angle = 90 if abs(s[0] - e[0]) < 0.1 else 0
try:
dim_string = dim.get("text", "")
if not dim_string:
dim_string = " "
de = space.add_linear_dim(
base=s, p1=s, p2=e,
angle=angle,
dimstyle="EZDXF",
override={"dimtxsty": "Standard", "dimtxt": dim_txt, "dimgap": dim_txt * 0.4},
text=dim_string,
dxfattribs={"layer": "DIMENSIONS"},
)
# Explicitly shift text off the line for vertical dimensions
if angle == 90:
mid_x = (s[0] + e[0]) / 2.0
mid_y = (s[1] + e[1]) / 2.0
# Use the start y-coord to deterministically stagger
# if y%2 or something? Actually, let's just use a static counter on the space/doc?
# A simple way to stagger: base it on the integer value of mid_y
stagger = 3.0 if int(mid_y) % 20 < 10 else 7.0
shift = -stagger if s[0] < x_offset + 100 else stagger
de.dimension.dxf.text_midpoint = (mid_x + shift, mid_y, 0.0)
de.render()
except Exception:
pass
class DXFDrawingGenerator:
def __init__(self):
pass
def generate(self, geometry: dict, output_path: str | Path):
"""
Generates plan and elevation views and saves to a dxf file.
"""
def generate(self, geometry: dict, output_path: str | Path) -> Path:
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
# Create drawing with standard styles
doc = ezdxf.new('R2010', setup=True)
msp = doc.modelspace()
doc = ezdxf.new("R2010", setup=True)
_setup_doc(doc)
# Add typical layers
doc.layers.add('WALLS', color=7) # White/Black
doc.layers.add('WALLS_HIDDEN', color=8)
doc.layers.add('WALLS_DEMO', color=1) # Red
doc.layers.add('WALLS_SECTION', color=7)
doc.layers.add('CENTERLINES', color=3) # Green
doc.layers.add('CABINETS_BASE', color=4) # Cyan
doc.layers.add('CABINETS_UPPER', color=2) # Yellow
doc.layers.add('CABINETS_SECTION', color=4)
doc.layers.add('COUNTERTOP_SECTION', color=6) # Magenta
doc.layers.add('SOFFIT', color=8)
doc.layers.add('SOFFIT_SECTION', color=8)
doc.layers.add('BACKSPLASH_SECTION', color=5) # Blue
doc.layers.add('MOLDING_SECTION', color=6)
doc.layers.add('APPLIANCES', color=7)
doc.layers.add('SINK', color=8)
doc.layers.add('HANDLES', color=7)
doc.layers.add('SWING', color=8)
doc.layers.add('GROUND', color=8)
doc.layers.add('CEILING', color=8)
doc.layers.add('DIMENSIONS', color=8)
doc.layers.add('TEXT', color=7)
doc.layers.add('ANNOTATION', color=2)
doc.layers.add('ANNOTATION_TEXT', color=7)
doc.layers.add('REVISIONS', color=1) # Red for revisions
doc.layers.add('TITLEBLOCK', color=7)
wall_length_in = 90.0
if geometry["elevation"]["lines"]:
max_x_geom = max(line["end"][0] for line in geometry["elevation"]["lines"])
wall_length_in = max_x_geom
ELEV_Y_OFFSET = 60.0
SIDE_X_OFFSET = max(90.0, wall_length_in) + 30.0
elev_lines = geometry.get("elevation", {}).get("lines", [])
if elev_lines:
xs = [l["end"][0] for l in elev_lines] + [l["start"][0] for l in elev_lines]
if xs:
wall_length_in = max(xs) - min(xs)
wall_length_in = max(wall_length_in, 24.0)
# Helper coordinate mapping functions (converting raw visual coordinates back to actual inches)
def to_plan_inch(pt):
return (pt[0], pt[1])
elev_wall_bounds = self._detect_wall_regions(
geometry.get("elevation", {}),
wall_length_in,
)
def to_elev_inch(pt):
return (pt[0], pt[1] + ELEV_Y_OFFSET)
if len(elev_wall_bounds) <= 1:
msp = doc.modelspace()
ELEV_Y = 120.0
self._write_plan_to_space(geometry, msp, wall_length_in)
_write_geom_to_space(geometry.get("elevation", {}), msp, ELEV_Y, 0.0, wall_length_in)
_write_geom_to_space(geometry.get("side", {}), msp, ELEV_Y,
max(wall_length_in, 90.0) + 70.0, wall_length_in)
else:
for i, (x_min, x_max) in enumerate(elev_wall_bounds):
layout_name = f"ELEVATION_{i + 1}"
try:
layout = doc.layouts.new(layout_name)
except Exception:
layout = doc.layouts.get(layout_name)
def to_side_inch(pt):
return (pt[0] + SIDE_X_OFFSET, pt[1] + ELEV_Y_OFFSET)
w_len = max(x_max - x_min, 24.0)
shifted_elev = self._shift_geom(geometry.get("elevation", {}), -x_min, 0.0,
x_min, x_max)
shifted_plan = self._shift_geom(geometry.get("plan", {}), -x_min, 0.0,
x_min, x_max)
ELEV_Y = 120.0
self._write_plan_to_space({"plan": shifted_plan}, layout, w_len)
_write_geom_to_space(shifted_elev, layout, ELEV_Y, 0.0, w_len)
_write_geom_to_space(geometry.get("side", {}), layout, ELEV_Y,
max(w_len, 90.0) + 70.0, w_len)
# 1. Write Plan Geometry to model space
for line in geometry["plan"]["lines"]:
layer = line.get("layer", "WALLS")
ltype = "DASHED" if line.get("style") == "dashed" else "CONTINUOUS"
msp.add_line(to_plan_inch(line["start"]), to_plan_inch(line["end"]), dxfattribs={'layer': layer, 'linetype': ltype})
for block in geometry["plan"]["blocks"]:
layer = block.get("layer", "CABINETS_BASE")
ltype = "DASHED" if block.get("style") == "dashed" else "CONTINUOUS"
x, y, w, h = block["coords"]
if block.get("type") == "circle":
msp.add_circle(to_plan_inch((x, y)), w, dxfattribs={'layer': layer})
else:
x_in = x
y_in = y
w_in = w
h_in = h
msp.add_line((x_in, y_in), (x_in + w_in, y_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in + w_in, y_in), (x_in + w_in, y_in + h_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in + w_in, y_in + h_in), (x_in, y_in + h_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in, y_in + h_in), (x_in, y_in), dxfattribs={'layer': layer, 'linetype': ltype})
for txt in geometry["plan"]["texts"]:
layer = txt.get("layer", "TEXT")
pos_in = to_plan_inch(txt["pos"])
text_str = txt["text"]
msp.add_mtext(text_str, dxfattribs={'layer': layer, 'char_height': 2.5}).set_location(pos_in)
for dim in geometry["plan"]["dimensions"]:
layer = "DIMENSIONS"
s_in = to_plan_inch(dim["start"])
e_in = to_plan_inch(dim["end"])
dim_entity = msp.add_linear_dim(
base=s_in,
p1=s_in,
p2=e_in,
dimstyle='EZDXF',
override={'dimtxsty': 'Standard', 'dimtxt': 2.0},
text=dim["text"],
dxfattribs={'layer': layer}
)
dim_entity.render()
# 2. Write Elevation Geometry
for line in geometry["elevation"]["lines"]:
layer = line.get("layer", "WALLS")
ltype = "DASHED" if line.get("style") == "dashed" else "CONTINUOUS"
msp.add_line(to_elev_inch(line["start"]), to_elev_inch(line["end"]), dxfattribs={'layer': layer, 'linetype': ltype})
for block in geometry["elevation"]["blocks"]:
layer = block.get("layer", "CABINETS_BASE")
ltype = "DASHED" if block.get("style") == "dashed" else "CONTINUOUS"
x, y, w, h = block["coords"]
if block.get("type") == "circle":
msp.add_circle((x, y + ELEV_Y_OFFSET), w, dxfattribs={'layer': layer})
else:
x_in = x
y_in = y + ELEV_Y_OFFSET
w_in = w
h_in = h
msp.add_line((x_in, y_in), (x_in + w_in, y_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in + w_in, y_in), (x_in + w_in, y_in + h_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in + w_in, y_in + h_in), (x_in, y_in + h_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in, y_in + h_in), (x_in, y_in), dxfattribs={'layer': layer, 'linetype': ltype})
for txt in geometry["elevation"]["texts"]:
layer = txt.get("layer", "TEXT")
pos_in = to_elev_inch(txt["pos"])
text_str = txt["text"]
msp.add_mtext(text_str, dxfattribs={'layer': layer, 'char_height': 2.5}).set_location(pos_in)
for dim in geometry["elevation"]["dimensions"]:
layer = "DIMENSIONS"
s_in = to_elev_inch(dim["start"])
e_in = to_elev_inch(dim["end"])
# Use angled dimension if vertical
angle = 90 if abs(s_in[0] - e_in[0]) < 0.1 else 0
dim_entity = msp.add_linear_dim(
base=s_in,
p1=s_in,
p2=e_in,
angle=angle,
dimstyle='EZDXF',
override={'dimtxsty': 'Standard', 'dimtxt': 2.0},
text=dim["text"],
dxfattribs={'layer': layer}
)
dim_entity.render()
# 3. Write Side Section Geometry
for line in geometry.get("side", {}).get("lines", []):
layer = line.get("layer", "WALLS")
ltype = "DASHED" if line.get("style") == "dashed" else "CONTINUOUS"
msp.add_line(to_side_inch(line["start"]), to_side_inch(line["end"]), dxfattribs={'layer': layer, 'linetype': ltype})
for block in geometry.get("side", {}).get("blocks", []):
layer = block.get("layer", "CABINETS_BASE")
ltype = "DASHED" if block.get("style") == "dashed" else "CONTINUOUS"
x, y, w, h = block["coords"]
x_in = (x - 250.0) / 4.0 + SIDE_X_OFFSET
y_in = (y - 150.0) / 3.0 + ELEV_Y_OFFSET
w_in = w / 4.0
h_in = h / 3.0
msp.add_line((x_in, y_in), (x_in + w_in, y_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in + w_in, y_in), (x_in + w_in, y_in + h_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in + w_in, y_in + h_in), (x_in, y_in + h_in), dxfattribs={'layer': layer, 'linetype': ltype})
msp.add_line((x_in, y_in + h_in), (x_in, y_in), dxfattribs={'layer': layer, 'linetype': ltype})
for txt in geometry.get("side", {}).get("texts", []):
layer = txt.get("layer", "TEXT")
pos_in = to_side_inch(txt["pos"])
text_str = txt["text"].replace('\n', ' ')
msp.add_text(text_str, dxfattribs={'layer': layer, 'height': 2.5}).set_placement(pos_in)
for dim in geometry.get("side", {}).get("dimensions", []):
layer = "DIMENSIONS"
s_in = to_side_inch(dim["start"])
e_in = to_side_inch(dim["end"])
# Use angled dimension if vertical
angle = 90 if abs(s_in[0] - e_in[0]) < 0.1 else 0
dim_entity = msp.add_linear_dim(
base=s_in,
p1=s_in,
p2=e_in,
angle=angle,
dimstyle='EZDXF',
override={'dimtxsty': 'Standard', 'dimtxt': 2.0},
text=dim["text"],
dxfattribs={'layer': layer}
)
dim_entity.render()
# 4. Add view labels to DXF model space
# (Labels are now generated dynamically by the geometry engines for each wall)
# Save file
doc.saveas(str(output_path))
print(f" [SUCCESS] DXF drawing saved: {output_path}")
# Also save to PDF if matplotlib is available
if qsave:
from ezdxf.addons.drawing.config import Configuration, BackgroundPolicy, ColorPolicy
# We want a white background and monochrome black lines for printing
config = Configuration(
cfg = Configuration(
background_policy=BackgroundPolicy.WHITE,
color_policy=ColorPolicy.BLACK
color_policy=ColorPolicy.BLACK,
)
pdf_path = str(output_path).replace('.dxf', '.pdf')
pdf_path = str(output_path).replace(".dxf", ".pdf")
try:
# Specify high resolution and white background
qsave(doc.modelspace(), pdf_path, bg='#FFFFFF', config=config, dpi=300)
if len(elev_wall_bounds) <= 1:
qsave(doc.modelspace(), pdf_path, bg="#FFFFFF", config=cfg, dpi=300)
else:
import tempfile, os
page_paths = []
for i in range(len(elev_wall_bounds)):
layout_name = f"ELEVATION_{i+1}"
try:
lt = doc.layouts.get(layout_name)
tmp = output_path.parent / f"_tmp_{layout_name}_{i}.pdf"
qsave(lt, str(tmp), bg="#FFFFFF", config=cfg, dpi=300)
page_paths.append(tmp)
except Exception as pe:
print(f" [WARN] Layout {layout_name} export failed: {pe}")
if page_paths:
try:
import fitz
merged = fitz.open()
for pp in page_paths:
merged.insert_pdf(fitz.open(str(pp)))
merged.save(pdf_path)
merged.close()
for pp in page_paths:
try: pp.unlink()
except: pass
except ImportError:
import shutil
shutil.copy(str(page_paths[0]), pdf_path)
for pp in page_paths[1:]:
try: pp.unlink()
except: pass
print(f" [SUCCESS] DXF-based PDF drawing saved: {pdf_path}")
except Exception as e:
print(f" [WARN] Failed to export DXF to PDF: {e}")
return output_path
def _write_plan_to_space(self, geometry: dict, space, wall_length_in: float) -> None:
_write_geom_to_space(geometry.get("plan", {}), space, 0.0, 0.0, wall_length_in)
def _detect_wall_regions(
self,
elev_geom: dict,
nominal_wall_len: float,
) -> list[tuple[float, float]]:
wall_lines = [
l for l in elev_geom.get("lines", [])
if l.get("layer") == "WALLS"
]
if not wall_lines:
return [(0.0, nominal_wall_len)]
xs = sorted(set(
round(min(l["start"][0], l["end"][0]), 1)
for l in wall_lines
if abs(l["start"][1] - l["end"][1]) < 1.0
))
if not xs:
return [(0.0, nominal_wall_len)]
if len(xs) == 1:
pass # Removed early exit so single walls can be paginated
clusters: list[list[float]] = [[xs[0]]]
for x in xs[1:]:
if x - clusters[-1][-1] > 50.0:
clusters.append([x])
else:
clusters[-1].append(x)
# Build clusters into bounding boxes
cluster_bounds = []
for ci, cluster in enumerate(clusters):
x_start = cluster[0]
if ci + 1 < len(clusters):
x_end = clusters[ci + 1][0] - 50.0
else:
x_end = max(
(max(l["start"][0], l["end"][0])
for l in wall_lines
if min(l["start"][0], l["end"][0]) >= x_start),
default=x_start + nominal_wall_len,
)
cluster_bounds.append((x_start, x_end))
# Group clusters into pages based on MAX_PAGE_WIDTH
MAX_PAGE_WIDTH = 1500.0
pages = []
current_page_start = cluster_bounds[0][0]
current_page_end = cluster_bounds[0][1]
for i in range(1, len(cluster_bounds)):
c_start, c_end = cluster_bounds[i]
if c_end - current_page_start <= MAX_PAGE_WIDTH:
# Add to current page
current_page_end = c_end
else:
# Close current page and start a new one
pages.append((current_page_start, current_page_end))
current_page_start = c_start
current_page_end = c_end
pages.append((current_page_start, current_page_end))
# Enforce hard cap to prevent overflow
final_pages = []
for p_start, p_end in pages:
while p_end - p_start > MAX_PAGE_WIDTH:
final_pages.append((p_start, p_start + MAX_PAGE_WIDTH))
p_start += MAX_PAGE_WIDTH
if p_start < p_end:
final_pages.append((p_start, p_end))
return final_pages
def _shift_geom(
self,
geom: dict,
dx: float,
dy: float,
x_min: float,
x_max: float,
) -> dict:
def _in_range(v: float) -> bool:
return (x_min - 1.0) <= v <= (x_max + 1.0)
def shift_pt(pt):
return [pt[0] + dx, pt[1] + dy]
out: dict = {"lines": [], "blocks": [], "texts": [], "dimensions": []}
for l in geom.get("lines", []):
if _in_range(l["start"][0]) or _in_range(l["end"][0]):
out["lines"].append({**l, "start": shift_pt(l["start"]), "end": shift_pt(l["end"])})
for b in geom.get("blocks", []):
bx = b["coords"][0]
if _in_range(bx):
new_coords = [b["coords"][0] + dx, b["coords"][1] + dy] + list(b["coords"][2:])
out["blocks"].append({**b, "coords": new_coords})
for t in geom.get("texts", []):
if _in_range(t["pos"][0]):
out["texts"].append({**t, "pos": shift_pt(t["pos"])})
for d in geom.get("dimensions", []):
if _in_range(d["start"][0]):
out["dimensions"].append({**d, "start": shift_pt(d["start"]), "end": shift_pt(d["end"])})
return out
+76 -100
View File
@@ -248,7 +248,7 @@ def _draw_cover(c: canvas.Canvas, config: dict, unit_totals: dict, total_pages:
if not notes:
notes = [
"1. ALL CABINETS ARE 90CM DEPTH",
"2. FINISH: K019 SILVER LIBERTY ELM",
f"2. FINISH: {config.get('finish', 'STANDARD').upper()}",
"3. ALL HARDWARE CONCEALED",
"4. SOFT CLOSE DOORS AND DRAWERS STANDARD",
"5. ADA UNITS: BASE CABINET HEIGHT 864MM MAX / COUNTERTOP HEIGHT 34\" MAX",
@@ -339,17 +339,25 @@ def _draw_cover(c: canvas.Canvas, config: dict, unit_totals: dict, total_pages:
def _draw_matrix_page(c: canvas.Canvas, config: dict, unit_schedules: dict,
unit_totals: dict, total_pages: int):
"""Draw the project unit matrix page."""
project_name = config.get("project_name", "").upper()
if "CASA FAMILIA" in project_name:
_draw_casa_familia_matrix(c, config, unit_totals, total_pages)
elif "HERITAGE" in project_name:
_draw_heritage_matrix(c, config, unit_totals, total_pages)
"""Draw the project unit matrix page.
Routes to the correct table format via config['matrix_format'].
Supported values: 'v_matrix' (V1-V4/kitchen-type client format),
'generic_matrix' (Upper/Base/Pantry breakdown).
Defaults to 'generic_matrix' if the flag is absent.
"""
matrix_format = config.get("matrix_format", "generic_matrix")
if matrix_format == "v_matrix":
_draw_v_matrix(c, config, unit_totals, total_pages)
else:
_draw_generic_matrix(c, config, unit_schedules, unit_totals, total_pages)
def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict, total_pages: int):
def _draw_v_matrix(c: canvas.Canvas, config: dict, unit_totals: dict, total_pages: int):
"""Draws the 9-column V1-V4/Kitchen-type matrix format.
This is the client-expected format for projects like Casa Familia.
All row data is dynamically pulled from config['unit_matrix'] and
config['buildings'] — no hardcoded unit lists.
"""
_draw_page_border(c)
_draw_title_block(c, config, 2, total_pages, "PROJECT MATRIX")
@@ -359,7 +367,7 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
c.setFont(_FONT_BOLD, 11)
c.setFillColor(colors.black)
c.drawString(DA_L + 10, DA_T - 36, config.get("project_name", "CASA FAMILIA"))
c.drawString(DA_L + 10, DA_T - 36, config.get("project_name", ""))
# Table dimensions
cols = [120, 48, 38, 38, 38, 38, 95, 62.5, 62.5]
@@ -391,20 +399,20 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
c.line(col_x[3], ty - 32, col_x[3], ty - 16)
c.line(col_x[4], ty - 32, col_x[4], ty - 16)
c.line(col_x[5], ty - 32, col_x[5], ty - 16)
# Sub-columns TYPE-QTY vertical line
c.line(col_x[8], ty - 32, col_x[8], ty - 16)
# Horizontal lines inside header (start second line from col_x[2] to avoid crossing QTY TOTAL)
c.line(col_x[2], ty - 16, col_x[6], ty - 16)
c.line(col_x[2], ty - 32, col_x[6], ty - 32)
c.line(col_x[7], ty - 16, col_x[9], ty - 16)
c.line(col_x[7], ty - 32, col_x[9], ty - 32)
# Header texts
c.setFillColor(NAVY)
# Main headers
c.setFont(_FONT_BOLD, 9)
c.drawCentredString(tx + 60, ty - 28, "UNIT NAME")
@@ -421,66 +429,40 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
c.drawCentredString(col_x[4] + 19, ty - 26, "V3")
c.drawCentredString(col_x[5] + 19, ty - 26, "V4")
c.drawCentredString(col_x[2] + 76, ty - 42, "VANITIES")
c.drawCentredString(col_x[7] + 31.25, ty - 26, "TYPE")
c.drawCentredString(col_x[8] + 31.25, ty - 26, "QTY")
c.drawCentredString(col_x[7] + 62.5, ty - 42, "KITCHENS")
c.restoreState()
# Rows construction
building_a_units = [
{"unit": "UNIT A1", "v1": 1, "v2": 0, "v3": 0, "v4": 0, "kitchen": "K1", "ut_key": "A1"},
{"unit": "UNIT A2 FA", "v1": 0, "v2": 1, "v3": 0, "v4": 0, "kitchen": "K2", "ut_key": "A2-ADA"},
{"unit": "UNIT A3", "v1": 0, "v2": 0, "v3": 1, "v4": 0, "kitchen": "K1", "ut_key": "A3"},
{"unit": "UNIT B1", "v1": 1, "v2": 0, "v3": 0, "v4": 1, "kitchen": "K3", "ut_key": "B1"},
{"unit": "UNIT B2 FA", "v1": 0, "v2": 1, "v3": 0, "v4": 1, "kitchen": "K4", "ut_key": "B2-ADA"}
]
# --- Build row data from config, not hardcoded lists ---
unit_matrix = config.get("unit_matrix", [])
buildings = config.get("buildings", {})
building_b_units = [
{"unit": "UNIT A1", "v1": 1, "v2": 0, "v3": 0, "v4": 0, "kitchen": "K1", "ut_key": "A1"},
{"unit": "UNIT A2 FA", "v1": 0, "v2": 1, "v3": 0, "v4": 0, "kitchen": "K2", "ut_key": "A2-ADA"},
{"unit": "UNIT A3", "v1": 0, "v2": 0, "v3": 1, "v4": 0, "kitchen": "K1", "ut_key": "A3"},
{"unit": "UNIT B1", "v1": 1, "v2": 0, "v3": 0, "v4": 1, "kitchen": "K3", "ut_key": "B1"},
{"unit": "UNIT B2 FA", "v1": 0, "v2": 1, "v3": 0, "v4": 1, "kitchen": "K4", "ut_key": "B2-ADA"}
]
# Build a lookup from unit key -> unit_matrix entry
unit_lookup = {row["key"]: row for row in unit_matrix}
v1_tot = 0
v2_tot = 0
v3_tot = 0
v4_tot = 0
kt_totals = {"K1": 0, "K2": 0, "K3": 0, "K4": 0}
v1_tot = 0; v2_tot = 0; v3_tot = 0; v4_tot = 0
kt_totals: dict = {}
tot_kitchens = 0
# Sum counts for Building A
for item in building_a_units:
qty = unit_totals.get(item["ut_key"], 0)
item["qty"] = qty
v1_tot += qty * item["v1"]
v2_tot += qty * item["v2"]
v3_tot += qty * item["v3"]
v4_tot += qty * item["v4"]
kt_totals[item["kitchen"]] += qty
tot_kitchens += qty
# Count totals across all buildings
for keys in buildings.values():
for key in keys:
u = unit_lookup.get(key, {})
qty = unit_totals.get(key, u.get("qty", 0))
v1_tot += qty * u.get("v1", 0)
v2_tot += qty * u.get("v2", 0)
v3_tot += qty * u.get("v3", 0)
v4_tot += qty * u.get("v4", 0)
k = u.get("kitchen", "")
if k:
kt_totals[k] = kt_totals.get(k, 0) + qty
tot_kitchens += qty
# Sum counts for Building B
for item in building_b_units:
qty = unit_totals.get(item["ut_key"], 0)
item["qty"] = qty
v1_tot += qty * item["v1"]
v2_tot += qty * item["v2"]
v3_tot += qty * item["v3"]
v4_tot += qty * item["v4"]
kt_totals[item["kitchen"]] += qty
tot_kitchens += qty
# Kitchen summary list
kit_summary = [
("K1", kt_totals["K1"]),
("K2", kt_totals["K2"]),
("K3", kt_totals["K3"]),
("K4", kt_totals["K4"])
]
# Build kitchen summary list (sorted for deterministic column layout)
kit_summary = sorted(kt_totals.items()) # e.g. [("K1", 32), ("K2", 6), ...]
ry = ty - 48
rh = 16
@@ -515,48 +497,42 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
c.restoreState()
# 1. Building Type A row
k_type_0 = kit_summary[0][0]
k_qty_0 = kit_summary[0][1]
draw_row(ry - rh, ["BUILDING TYPE A", "-", "", "", "", "", "", k_type_0, k_qty_0], bold=True, is_building_header=True)
ry -= rh
# --- Render rows dynamically from config['buildings'] ---
ry = ty - 48
rh = 16
# 2. Building A units
for idx, item in enumerate(building_a_units):
kit_iter = iter(kit_summary)
for bldg_idx, (bldg_name, unit_keys) in enumerate(buildings.items()):
# Building header row
try:
k_type_h, k_qty_h = next(kit_iter)
except StopIteration:
k_type_h, k_qty_h = "", ""
draw_row(ry - rh, [bldg_name.upper(), "-", "", "", "", "", "", k_type_h, k_qty_h],
bold=True, is_building_header=True)
ry -= rh
k_type = kit_summary[idx+1][0] if idx+1 < len(kit_summary) else ""
k_qty = kit_summary[idx+1][1] if idx+1 < len(kit_summary) else ""
draw_row(ry, [
item["unit"],
item["qty"],
item["v1"] or "",
item["v2"] or "",
item["v3"] or "",
item["v4"] or "",
item["kitchen"],
k_type,
k_qty
])
# 3. Building Type B row
ry -= rh
draw_row(ry, ["BUILDING TYPE B", "-", "", "", "", "", "", "", ""], bold=True, is_building_header=True)
# 4. Building B units
for item in building_b_units:
ry -= rh
draw_row(ry, [
item["unit"],
item["qty"],
item["v1"] or "",
item["v2"] or "",
item["v3"] or "",
item["v4"] or "",
item["kitchen"],
"",
""
])
for key in unit_keys:
u = unit_lookup.get(key, {})
qty = unit_totals.get(key, u.get("qty", 0))
try:
k_type_r, k_qty_r = next(kit_iter)
except StopIteration:
k_type_r, k_qty_r = "", ""
ry -= rh
draw_row(ry, [
u.get("unit", key),
qty,
u.get("v1", 0) or "",
u.get("v2", 0) or "",
u.get("v3", 0) or "",
u.get("v4", 0) or "",
u.get("kitchen", ""),
k_type_r,
k_qty_r,
])
# 5. Table outer border
c.saveState()
+3 -3
View File
@@ -1127,7 +1127,7 @@ def run_pipeline(
# Or just assign X dynamically based on type.
def cab_sort_key(c):
is_upper = c.cabinet_type in ("upper", "microwave", "hood") or (c.cabinet_id or "").upper().startswith(("W", "U"))
is_upper = c.cabinet_type in ("upper", "upper_wall", "microwave_shelf", "corner_upper", "medicine_cabinet", "hood")
return 1 if is_upper else 0
sorted_cabs = sorted(ev.cabinets, key=cab_sort_key)
@@ -1140,8 +1140,8 @@ def run_pipeline(
h_in = round(float(cab.height_in))
d_in = round(float(cab.depth_in)) if getattr(cab, 'depth_in', None) else 0
is_upper = cab.cabinet_type in ("upper", "microwave", "hood") or (cab.cabinet_id or "").upper().startswith(("W", "U"))
is_tall_or_app = cab.cabinet_type in ("pantry", "refrigerator", "range", "linen") or (cab.cabinet_id or "").upper().startswith("P")
is_upper = cab.cabinet_type in ("upper", "upper_wall", "microwave_shelf", "corner_upper", "medicine_cabinet", "hood")
# is_tall_or_app is unused in this block, removing dead code
cab_dict = {
"id": cab.cabinet_id or cab.code,
+5
View File
@@ -11,3 +11,8 @@ python-dotenv>=1.0.0
Pillow>=10.0.0
numpy>=1.24.0
ultralytics>=8.4.0
langgraph>=0.0.60
langchain>=0.2.0
langchain-openai>=0.1.0
langchain-core>=0.2.0
pydantic>=2.0.0
@@ -0,0 +1,6 @@
import json
import ezdxf
def main():
print("Testing new DXF layout structure...")
@@ -0,0 +1,209 @@
"""
scripts/validate_all_layouts.py
================================
CI-style regression harness that runs ElevationLayout.build_two_tier() +
validate() across every kitchen and vanity type defined in project_config.json.
Exit code:
0 — all layouts pass (hard errors = 0)
1 — one or more hard structural errors detected
Usage:
python scripts/validate_all_layouts.py
python scripts/validate_all_layouts.py --config "Casa familia/project_config.json"
python scripts/validate_all_layouts.py --json # machine-readable output
python scripts/validate_all_layouts.py --wall K1.wall_a # single wall
Output format (text, default):
[PASS] K1.wall_a — base=126.0" / wall=126.0" 0 errors 1 NKBA warnings
[WARN] K1.wall_a flag NKBA GUIDELINE: Range/Stove at x=...
[ERROR] K4.wall_b — width mismatch: base=71.0" but wall=79.0"
This runs in ~0.2 s for the full Casa Familia dataset (no PDF parsing).
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
# Allow running from repo root or scripts/ directory
_REPO = Path(__file__).parent.parent
sys.path.insert(0, str(_REPO))
from core.engines.elevation_layout import ElevationLayout
CM_TO_IN = 1.0 / 2.54
def _cm_to_in(v: float) -> float:
return v * CM_TO_IN # no per-value rounding — accumulation must stay precise
def _normalize_cab(c: dict) -> dict:
"""Convert a project_config cabinet dict to the standard format expected by ElevationLayout."""
out = dict(c)
if "width_cm" in c:
out["width"] = _cm_to_in(c["width_cm"])
elif "width_in" in c:
out["width"] = float(c["width_in"])
elif "width" in c:
out["width"] = float(c["width"])
else:
out["width"] = 0.0
if "height_cm" in c:
out["height"] = _cm_to_in(c["height_cm"])
elif "height_in" in c:
out["height"] = float(c["height_in"])
elif "height" in c:
out["height"] = float(c["height"])
else:
out["height"] = 0.0
out["id"] = c.get("id", c.get("cabinet_id", "CAB"))
out["type"] = c.get("type", c.get("cabinet_type", "base"))
return out
def _wall_length_in(wall: dict) -> float:
if "length_cm" in wall:
return _cm_to_in(wall["length_cm"])
if "length_in" in wall:
return float(wall["length_in"])
return float(wall.get("length", 0.0))
def _validate_wall(
type_key: str,
wall_key: str,
wall: dict,
is_ada: bool = False,
) -> dict:
key = f"{type_key}.{wall_key}"
base_cfg = [_normalize_cab(c) for c in wall.get("cabinets", [])]
upper_cfg = [_normalize_cab(c) for c in wall.get("uppers", [])]
wall_len = _wall_length_in(wall)
result: dict[str, Any] = {
"key": key,
"hard_error": None,
"warnings": [],
"base_sum": 0.0,
"wall_len": wall_len,
}
layout = None
try:
layout = ElevationLayout.build_two_tier(
base_cfg=base_cfg,
upper_cfg=upper_cfg,
wall_length_in=wall_len,
is_ada=is_ada,
)
layout.validate()
base_segs = [s for s in layout.segments if s.tier == "base"]
result["base_sum"] = round(sum(s.width_in for s in base_segs), 4)
result["warnings"] = list(layout.warnings)
except ValueError as exc:
result["hard_error"] = str(exc)
if layout is not None:
result["warnings"] = list(getattr(layout, "warnings", []))
return result
def _load_config(path: str) -> dict:
with open(path, encoding="utf-8") as f:
return json.load(f)
def _run(config_path: str, wall_filter: str | None = None, json_out: bool = False) -> int:
cfg = _load_config(config_path)
results = []
for type_key, k_data in cfg.get("kitchen_types", {}).items():
is_ada = "ada" in type_key.lower()
for wall_key, wall in k_data.items():
if not isinstance(wall, dict):
continue
if wall_filter and f"{type_key}.{wall_key}" != wall_filter:
continue
results.append(_validate_wall(type_key, wall_key, wall, is_ada=is_ada))
for type_key, v_data in cfg.get("vanity_types", {}).items():
is_ada = "ada" in type_key.lower()
for wall_key, wall in v_data.items():
if not isinstance(wall, dict):
continue
if wall_filter and f"{type_key}.{wall_key}" != wall_filter:
continue
results.append(_validate_wall(type_key, wall_key, wall, is_ada=is_ada))
hard_error_count = sum(1 for r in results if r["hard_error"])
warn_count = sum(len(r["warnings"]) for r in results)
if json_out:
print(json.dumps(results, indent=2))
return 1 if hard_error_count else 0
WIDTH_TOL = 0.5
for r in results:
key = r["key"]
wall_len = r["wall_len"]
base_sum = r["base_sum"]
delta = base_sum - wall_len
if r["hard_error"]:
print(f"[ERROR] {key:<20} {r['hard_error']}")
else:
if base_sum < 0.1:
delta_str = "(empty base tier)"
else:
delta_str = f"delta={delta:+.2f}\"" if abs(delta) > WIDTH_TOL else "delta OK"
nkba_str = f" {len(r['warnings'])} NKBA warn" if r["warnings"] else ""
print(f"[PASS] {key:<20} base={base_sum:.1f}\" wall={wall_len:.1f}\" {delta_str}{nkba_str}")
for w in r["warnings"]:
print(f" flag {w}")
print()
print(f"{'=' * 60}")
print(f" Walls checked : {len(results)}")
print(f" Hard errors : {hard_error_count}")
print(f" NKBA warnings : {warn_count}")
print(f"{'=' * 60}")
if hard_error_count:
print(f"\n CI RESULT: FAIL -- {hard_error_count} hard layout error(s)")
return 1
else:
print(f"\n CI RESULT: PASS")
return 0
def main() -> None:
parser = argparse.ArgumentParser(description="Validate all ElevationLayouts from project_config.json")
parser.add_argument(
"--config",
default="Casa familia/project_config.json",
help="Path to project_config.json",
)
parser.add_argument(
"--wall",
default=None,
help="Only validate one wall, e.g. K1.wall_a",
)
parser.add_argument(
"--json",
action="store_true",
dest="json_out",
help="Emit machine-readable JSON",
)
args = parser.parse_args()
sys.exit(_run(args.config, wall_filter=args.wall, json_out=args.json_out))
if __name__ == "__main__":
main()
+5
View File
@@ -1,4 +1,9 @@
import pytest
import os
import sys
# Add the project root to sys.path so we can import core
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core.bimlite.models import UnitModel, KitchenModel, VanityModel, RoomModel, WallModel, CabinetNode
from core.bimlite.parser import ModelBuilder
from core.bimlite.engines import ValidationEngine
+44
View File
@@ -0,0 +1,44 @@
import pytest
import os
import sys
# Add the project root to sys.path so we can import core
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
from core.engines.elevation_generator import ElevationGenerator
from core.engines.dimension_engine import DimensionEngine
from core.engines.appliance_library import ApplianceLibrary
from core.engines.cabinet_library_resolver import CabinetLibraryResolver
def test_cabinet_library_resolver():
resolved = CabinetLibraryResolver.resolve_cabinet("ADA-B30")
assert resolved["family"] == "BASE"
assert resolved["render_style"] == "standard"
resolved_dw = CabinetLibraryResolver.resolve_cabinet("ADA-DW")
assert resolved_dw["family"] == "BASE"
def test_appliance_library_dishwasher():
# Test the dishwasher rendering geometry to ensure it generates lines/blocks
geom = ApplianceLibrary.draw_dishwasher_elevation(0, 0, 24, 30, scale_x=4.0, scale_y=3.0)
assert "blocks" in geom
assert "lines" in geom
assert "texts" in geom
# Verify a text block is generated for the D/W
texts = geom["texts"]
assert any("D/W" in t["text"] for t in texts)
def test_dimension_engine_horizontal():
# Provide simple item widths
items = [{"width": 24.0}, {"width": 30.0}]
dim_geom = DimensionEngine.generate_horizontal_chain(items, 0, 0, scale=4.0)
# We expect a list of segments
assert isinstance(dim_geom, list)
assert len(dim_geom) == 2
# Check segment content
assert "start" in dim_geom[0]
assert "end" in dim_geom[0]
assert "text" in dim_geom[0]
+89
View File
@@ -0,0 +1,89 @@
import pytest
from core.geometry_engine import GeometryEngine
from generators.shop_drawing_dxf import DXFDrawingGenerator
def test_dxf_pagination_no_split():
geom_engine = GeometryEngine()
# A single wall of 140 inches should NOT be split since max is 200
walls_info = [{
"name": "A",
"length": 140.0,
"cabinets": [
{"id": "base1", "type": "base", "width": 40.0, "height": 34.0, "x": 0.0},
{"id": "base2", "type": "base", "width": 100.0, "height": 34.0, "x": 40.0}
]
}]
geom_data = geom_engine.generate_layout_geometry(
walls=walls_info,
appliances=[],
ceiling_height=108.0,
soffit_height=96.0
)
generator = DXFDrawingGenerator()
regions = generator._detect_wall_regions(geom_data["elevation"], 140.0)
# Should be exactly 1 region
assert len(regions) == 1
assert regions[0][1] - regions[0][0] >= 140.0
def test_dxf_pagination_overflow_split():
geom_engine = GeometryEngine()
# A single wall of 250 inches SHOULD be split (max is 200)
walls_info = [{
"name": "A",
"length": 250.0,
"cabinets": [
{"id": "base1", "type": "base", "width": 125.0, "height": 34.0, "x": 0.0},
{"id": "base2", "type": "base", "width": 125.0, "height": 34.0, "x": 125.0}
]
}]
geom_data = geom_engine.generate_layout_geometry(
walls=walls_info,
appliances=[],
ceiling_height=108.0,
soffit_height=96.0
)
generator = DXFDrawingGenerator()
regions = generator._detect_wall_regions(geom_data["elevation"], 250.0)
# Should be exactly 2 regions
assert len(regions) == 2
assert regions[0][1] - regions[0][0] == 200.0
def test_dxf_pagination_multiple_walls_grouping():
geom_engine = GeometryEngine()
# Two small walls (40 inches each) should fit on the same page, but since they have a 100 inch gap in model space:
# 40 (wall A) + 100 (gap) + 40 (wall B) = 180 total span. This fits in 200.
walls_info = [
{
"name": "A",
"length": 40.0,
"cabinets": [{"id": "base1", "type": "base", "width": 40.0, "height": 34.0, "x": 0.0}]
},
{
"name": "B",
"length": 40.0,
"cabinets": [{"id": "base2", "type": "base", "width": 40.0, "height": 34.0, "x": 0.0}]
}
]
geom_data = geom_engine.generate_layout_geometry(
walls=walls_info,
appliances=[],
ceiling_height=108.0,
soffit_height=96.0
)
generator = DXFDrawingGenerator()
regions = generator._detect_wall_regions(geom_data["elevation"], 180.0)
# Should be exactly 1 region
assert len(regions) == 1
assert regions[0][1] - regions[0][0] >= 180.0
@@ -0,0 +1,366 @@
"""
tests/test_elevation_layout.py
Unit + integration tests for ElevationLayout, ElevationGenerator, format_dimension,
and the _draw_elevation_view seam.
Previously 38/38 passed despite the two-tier bug because:
1. Tests exercised ElevationLayout.build() in isolation with pre-merged flat lists.
2. test_upper_after_spacer_starts_at_spacer_right_edge asserted the WRONG value
(72" = double-counted) as the expected result.
3. No test went through _draw_elevation_view / ElevationGenerator.generate with a
real two-list wall dict — the seam with zero coverage.
These tests now cover all of that.
"""
import sys
import os
import pytest
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
from core.engines.elevation_layout import (
ElevationLayout,
RefLines,
Segment,
_compute_ref_lines,
_boxes_overlap,
)
from core.engines.dimension_engine import DimensionEngine
from core.engines.elevation_generator import ElevationGenerator
# ─────────────────────────────────────────────────────────────────────────────
# DimensionEngine.format_dimension — rounding & formatting
# ─────────────────────────────────────────────────────────────────────────────
class TestFormatDimension:
def test_exact_foot(self):
assert DimensionEngine.format_dimension(36.0) == "3'-0\""
def test_feet_and_inches(self):
assert DimensionEngine.format_dimension(30.0) == "2'-6\""
def test_sub_foot(self):
assert DimensionEngine.format_dimension(6.0) == '6"'
def test_fraction(self):
assert DimensionEngine.format_dimension(6.5) == '6 1/2"'
def test_quarter_inch(self):
assert DimensionEngine.format_dimension(6.25) == '6 1/4"'
def test_float_safety_rounds_to_nearest_sixteenth(self):
# 76.2 cm / 2.54 = 29.999999... inches — must round to 30" = 2'-6"
inches = 76.2 / 2.54
assert DimensionEngine.format_dimension(inches) == "2'-6\""
def test_no_raw_floats_in_output(self):
for raw in [29.9999, 30.00001, 36.0, 22.8346]:
label = DimensionEngine.format_dimension(raw)
assert "." not in label, f"Raw float leaked into label: {label!r}"
def test_zero_is_safe(self):
assert DimensionEngine.format_dimension(0.0) == '0"'
# ─────────────────────────────────────────────────────────────────────────────
# ElevationLayout.build_two_tier — cursor placement
# ─────────────────────────────────────────────────────────────────────────────
_BASE_CABS = [
{"id": "DW24", "type": "dw", "width": 24.0, "height": 34.5},
{"id": "SB36", "type": "sink_base", "width": 36.0, "height": 34.5},
{"id": "B30", "type": "base", "width": 30.0, "height": 34.5},
{"id": "B36", "type": "base", "width": 36.0, "height": 34.5},
]
_UPPER_CABS = [
{"id": "W24", "type": "upper", "width": 24.0, "height": 30.0},
{"id": "W36", "type": "upper", "width": 36.0, "height": 30.0},
{"id": "W30", "type": "upper", "width": 30.0, "height": 30.0},
{"id": "W36b", "type": "upper", "width": 36.0, "height": 30.0},
]
_WALL_LEN = 126.0 # sum of base widths above
class TestTwoTierCursorPlacement:
def setup_method(self):
self.layout = ElevationLayout.build_two_tier(
base_cfg = _BASE_CABS,
upper_cfg = _UPPER_CABS,
wall_length_in = _WALL_LEN,
ceiling_h_in = 96.0,
)
def test_base_first_segment_starts_at_zero(self):
base = [s for s in self.layout.segments if not s.is_upper]
assert base[0].x_in == 0.0
def test_base_segments_are_contiguous(self):
base = [s for s in self.layout.segments if not s.is_upper]
for i in range(1, len(base)):
assert abs(base[i].x_in - base[i-1].x1_in) < 1e-9, (
f"Gap between base[{i-1}] and base[{i}]"
)
def test_upper_first_segment_starts_at_zero_no_tall_column(self):
"""Without a REF/tall column the upper cursor must start at x=0."""
uppers = [s for s in self.layout.segments if s.is_upper]
assert abs(uppers[0].x_in - 0.0) < 1e-9, (
f"Upper[0] x={uppers[0].x_in:.4f}, expected 0.0 (no REF/tall column)"
)
def test_upper_segments_are_contiguous(self):
uppers = [s for s in self.layout.segments if s.is_upper]
for i in range(1, len(uppers)):
assert abs(uppers[i].x_in - uppers[i-1].x1_in) < 1e-9, (
f"Gap between upper[{i-1}] and upper[{i}]"
)
def test_upper_end_does_not_exceed_wall_length(self):
uppers = [s for s in self.layout.segments if s.is_upper]
if uppers:
assert max(s.x1_in for s in uppers) <= _WALL_LEN + 0.5
def test_no_bounding_box_overlaps(self):
base = [s for s in self.layout.segments if not s.is_upper]
for i, a in enumerate(base):
for b in base[i+1:]:
assert not _boxes_overlap(a.bbox(), b.bbox()), (
f"Overlap: {a.label!r} and {b.label!r}"
)
def test_base_width_sum_matches_wall_length(self):
base = [s for s in self.layout.segments if not s.is_upper]
total = sum(s.width_in for s in base)
assert abs(total - _WALL_LEN) < 0.5
def test_validate_passes(self):
self.layout.validate() # must not raise
class TestTwoTierWithREFColumn:
"""Mode B: wall has a REF/tall column — uppers must start at REF right edge."""
def setup_method(self):
base_cfg = [
{"id": "REF28", "type": "ref", "width": 28.0, "height": 72.0},
{"id": "B30", "type": "base", "width": 30.0, "height": 34.5},
{"id": "B36", "type": "base", "width": 36.0, "height": 34.5},
]
upper_cfg = [
{"id": "W30", "type": "upper", "width": 30.0, "height": 30.0},
{"id": "W36", "type": "upper", "width": 36.0, "height": 30.0},
]
self.layout = ElevationLayout.build_two_tier(
base_cfg = base_cfg,
upper_cfg = upper_cfg,
wall_length_in = 94.0,
ceiling_h_in = 96.0,
)
def test_upper_starts_at_ref_right_edge(self):
"""Uppers must start at x=28" (REF right edge), not at x=94" or x=122"."""
uppers = [s for s in self.layout.segments if s.is_upper]
assert abs(uppers[0].x_in - 28.0) < 1e-9, (
f"Upper[0] x={uppers[0].x_in:.4f}, expected 28.0 (REF right edge)"
)
def test_upper_end_within_wall(self):
uppers = [s for s in self.layout.segments if s.is_upper]
upper_end = max(s.x1_in for s in uppers)
assert upper_end <= 94.0 + 0.5, f"upper_end={upper_end:.4f} > wall_length=94.0"
def test_validate_passes(self):
self.layout.validate() # must not raise (previously crashed with delta +28")
def test_ref_top_flushes_to_upper_top(self):
ref_seg = next(s for s in self.layout.segments if s.is_ref)
upper_seg = next(s for s in self.layout.segments if s.is_upper)
assert abs(ref_seg.y1_in - 72.0) < 0.01, (
f"REF y1={ref_seg.y1_in:.3f} ≠ 72.0"
)
# ─────────────────────────────────────────────────────────────────────────────
# Regression: the old UPPER_SPACER double-counting test (now asserting correct values)
# Previously asserted upper.x_in == 72.0 — that was the bug encoded as the spec.
# Correct value: upper starts at 36.0 (= REF right edge after a 36" base cabinet).
# ─────────────────────────────────────────────────────────────────────────────
class TestUpperStartsAtTallRightEdge:
def test_upper_after_ref_starts_at_ref_right_edge(self):
"""
Wall: [B36-as-REF][W30 upper]
Upper cursor must start at 36" (REF right edge), NOT at 72" (old double-count).
"""
base_cfg = [{"id": "REF36", "type": "ref", "width": 36.0, "height": 72.0}]
upper_cfg = [{"id": "W3030", "type": "upper", "width": 30.0, "height": 30.0}]
layout = ElevationLayout.build_two_tier(base_cfg, upper_cfg, wall_length_in=36.0)
upper = next(s for s in layout.segments if s.is_upper)
assert abs(upper.x_in - 36.0) < 1e-9, (
f"upper.x_in={upper.x_in:.4f}, expected 36.0 (REF right edge). "
f"Was 72.0 under the old double-counting UPPER_SPACER model."
)
def test_upper_after_base_only_starts_at_zero(self):
"""
Wall: [B36][W30 upper] — no tall column, upper must start at x=0.
"""
base_cfg = [{"id": "B36", "type": "base", "width": 36.0, "height": 34.5}]
upper_cfg = [{"id": "W3030", "type": "upper", "width": 30.0, "height": 30.0}]
layout = ElevationLayout.build_two_tier(base_cfg, upper_cfg, wall_length_in=36.0)
upper = next(s for s in layout.segments if s.is_upper)
assert abs(upper.x_in - 0.0) < 1e-9, (
f"upper.x_in={upper.x_in:.4f}, expected 0.0 (no REF, upper aligns to x=0)"
)
# ─────────────────────────────────────────────────────────────────────────────
# validate() — enhanced upper-tier bounds checking
# ─────────────────────────────────────────────────────────────────────────────
class TestValidation:
def test_valid_layout_does_not_raise(self):
layout = ElevationLayout.build_two_tier(_BASE_CABS, _UPPER_CABS, _WALL_LEN)
layout.validate()
def test_width_mismatch_raises(self):
layout = ElevationLayout.build_two_tier(_BASE_CABS, _UPPER_CABS, wall_length_in=999.0)
with pytest.raises(ValueError, match="width mismatch"):
layout.validate()
def test_upper_overflow_raises(self):
"""Upper run that overflows past wall right edge must raise."""
base_cfg = [{"id": "B30", "type": "base", "width": 30.0, "height": 34.5}]
upper_cfg = [{"id": "W60", "type": "upper", "width": 60.0, "height": 30.0}]
# wall_length=30, upper starts at 0 and ends at 60 — overflows by 30"
layout = ElevationLayout.build_two_tier(base_cfg, upper_cfg, wall_length_in=30.0)
with pytest.raises(ValueError, match="upper run overflows"):
layout.validate()
def test_overlapping_base_segs_raises(self):
ref = _compute_ref_lines(96.0, False)
segs = [
Segment(0, "A", "base", 30.0, 34.5, x_in=0.0, y0_in=4.0, y1_in=34.5),
Segment(1, "B", "base", 30.0, 34.5, x_in=10.0, y0_in=4.0, y1_in=34.5),
]
layout = ElevationLayout(segs, ref, wall_length_in=60.0)
with pytest.raises(ValueError, match="overlap"):
layout.validate()
# ─────────────────────────────────────────────────────────────────────────────
# Integration: ElevationGenerator.generate() with real two-list wall dict
# This is the seam that had ZERO coverage and where both Mode A and Mode B
# failures occurred in the real K1–K4 project config.
# ─────────────────────────────────────────────────────────────────────────────
class TestElevationGeneratorIntegration:
"""
Tests go through ElevationGenerator.generate() with realistic wall dicts
(like those built by _draw_elevation_view) to catch the full two-list merge path.
"""
def _make_wall(self, base_cfg, upper_cfg, length_in):
return {
"name": "TEST",
"length": length_in,
"base_cfg": base_cfg,
"upper_cfg": upper_cfg,
}
def test_mode_a_no_ref_column_uppers_within_wall(self):
"""
Mode A regression: wall with 5 base cabs + 5 uppers (no REF/tall).
Uppers must stay within [0, wall_length] — previously they landed at
[wall_length, 2*wall_length] off the right side of the drawing.
"""
base_cfg = [{"id": f"B{i}", "type": "base", "width": 30.0, "height": 34.5} for i in range(5)]
upper_cfg= [{"id": f"W{i}", "type": "upper", "width": 30.0, "height": 30.0} for i in range(5)]
wall_len = 150.0 # 5 × 30"
geom = ElevationGenerator.generate(
walls = [self._make_wall(base_cfg, upper_cfg, wall_len)],
start_ox = 0.0,
start_oy = 0.0,
ceiling_height = 96.0,
scale_x = 1.0,
scale_y = 1.0,
)
# Check that no block or line extends past the wall right edge (+ 1pt tolerance)
for block in geom["blocks"]:
if block.get("type") == "rect":
bx, by, bw, bh = block["coords"]
assert bx + bw <= wall_len + 1.0, (
f"Block extends past wall right edge: x={bx:.1f}+w={bw:.1f}={bx+bw:.1f} > {wall_len}"
)
def test_mode_b_with_ref_column_no_crash(self):
"""
Mode B regression: wall with REF + base cabs + uppers.
Previously raised ValueError (spurious delta +28" from UPPER_SPACER double-count).
Must now complete without raising.
"""
base_cfg = [
{"id": "REF28", "type": "ref", "width": 28.0, "height": 72.0},
{"id": "B30", "type": "base", "width": 30.0, "height": 34.5},
{"id": "B36", "type": "base", "width": 36.0, "height": 34.5},
]
upper_cfg = [
{"id": "W30", "type": "upper", "width": 30.0, "height": 30.0},
{"id": "W36", "type": "upper", "width": 36.0, "height": 30.0},
]
# Must not raise
geom = ElevationGenerator.generate(
walls = [self._make_wall(base_cfg, upper_cfg, 94.0)],
start_ox = 0.0,
start_oy = 0.0,
ceiling_height = 96.0,
scale_x = 1.0,
scale_y = 1.0,
)
# Must produce some geometry
assert len(geom["blocks"]) + len(geom["lines"]) > 0
def test_legacy_flat_list_still_works(self):
"""
Backward compatibility: walls using old "cabinets" key (flat list,
base-only) still work via the legacy build() path.
"""
geom = ElevationGenerator.generate(
walls = [{
"name": "LEGACY",
"length": 60.0,
"cabinets": [
{"id": "B30", "type": "base", "width": 30.0, "height": 34.5},
{"id": "B30b","type": "base", "width": 30.0, "height": 34.5},
],
}],
start_ox=0.0, start_oy=0.0, ceiling_height=96.0, scale_x=1.0, scale_y=1.0,
)
assert len(geom["lines"]) > 0
# ─────────────────────────────────────────────────────────────────────────────
# Ref lines
# ─────────────────────────────────────────────────────────────────────────────
class TestRefLineAlignment:
def test_standard_ref_lines(self):
ref = _compute_ref_lines(96.0, is_ada=False)
assert ref.counter_top_y == 34.5
assert ref.wall_cab_bot_y == 54.0
def test_ada_ref_lines(self):
ref = _compute_ref_lines(96.0, is_ada=True)
assert ref.counter_top_y == 32.5
assert ref.wall_cab_bot_y == 48.0
def test_ref_col_top_matches_upper_top(self):
"""REF column y1 must match upper cabinet y1 (flush tops)."""
base_cfg = [{"id": "REF36", "type": "ref", "width": 36.0, "height": 72.0}]
upper_cfg = [{"id": "W30", "type": "upper", "width": 30.0, "height": 30.0}]
layout = ElevationLayout.build_two_tier(base_cfg, upper_cfg, wall_length_in=36.0)
ref_seg = next(s for s in layout.segments if s.is_ref)
upper_seg = next(s for s in layout.segments if s.is_upper)
assert abs(ref_seg.y1_in - 72.0) < 0.01
+5 -5
View File
@@ -111,7 +111,7 @@ def test_centered_sink_120():
print(f" Cabinet total (non-filler): {cabinet_total}\"")
print("\n [PASS] OK Centered sink test passed")
return True
def test_empty_wall_90():
@@ -133,7 +133,7 @@ def test_empty_wall_90():
assert abs(total - 90.0) < 0.01, f"Total width {total} != 90"
print(" [PASS] OK Empty wall fill test passed")
return True
def test_wall_with_window():
@@ -167,7 +167,7 @@ def test_wall_with_window():
assert abs(total - 84.0) < 0.01, f"Total width {total} != 84"
print(" [PASS] OK Window obstruction test passed")
return True
def test_wall_with_ref_and_range():
@@ -205,7 +205,7 @@ def test_wall_with_ref_and_range():
print(f" Total cabinet: {total_placed:.1f}\" (available: {available:.0f}\")")
print(" [PASS] OK REF + range test passed")
return True
def test_constraint_extraction():
@@ -249,7 +249,7 @@ def test_constraint_extraction():
print(f" [{run.x_start:.0f}\" - {run.x_end:.0f}\"] = {run.length:.0f}\"")
print(" [PASS] OK Constraint extraction test passed")
return True
if __name__ == "__main__":
+362
View File
@@ -0,0 +1,362 @@
"""
Dataset Audit Script — Cabinetries Floor Plan Dataset
======================================================
Checks the following open risks identified during Phase 1 analysis:
A. Polygon vs bbox format — counts polygon rows per class, checks
whether ultralytics 8.4+ auto-converts them via segments2boxes().
B. Degenerate box — finds the near-zero-area Legends_Symbols instance.
C. Pantry/microwave testability — confirms 0 val/test instances.
D. Legends_Symbols box-size distribution — confirms mean/max coverage.
E. ultralytics segments2boxes() behaviour — actually calls the function
and shows before/after for a real polygon label line.
Usage:
python tools/audit_dataset.py
"""
import sys
from pathlib import Path
from collections import defaultdict
import statistics
# ── Paths ──────────────────────────────────────────────────────────────────
DATASET_ROOT = Path(r"C:\Users\abhil\Desktop\Cabinetries_dataset")
SPLITS = {
"train": DATASET_ROOT / "train" / "labels",
"valid": DATASET_ROOT / "valid" / "labels",
"test": DATASET_ROOT / "test" / "labels",
}
CLASS_NAMES = [
"Legends_Symbols", # 0
"bath_region", # 1
"bathtub_symbol", # 2
"dw_symbol", # 3
"fridge_symbol", # 4
"kitchen_region", # 5
"microwave_symbol", # 6
"pantry_symbol", # 7
"range_symbol", # 8
"sink_symbol", # 9
"toilet_symbol", # 10
"vanity_sink_symbol", # 11
]
# ──────────────────────────────────────────────────────────────────────────
# helpers
# ──────────────────────────────────────────────────────────────────────────
def parse_labels(label_dir: Path):
"""
Returns list of (cls_idx, fields_count, cx, cy, w, h_or_None) per row.
For polygon rows: fields_count > 5, bbox estimated as min-enclosing rect.
"""
rows = []
for lf in label_dir.glob("*.txt"):
for line in lf.read_text(encoding="utf-8").splitlines():
parts = line.strip().split()
if not parts:
continue
cls_idx = int(parts[0])
coords = [float(x) for x in parts[1:]]
n = len(coords) + 1 # total field count including class
if n == 5:
# standard bbox: class cx cy w h (normalized)
cx, cy, bw, bh = coords
rows.append((cls_idx, n, cx, cy, bw, bh, lf.name, line))
else:
# polygon: class x1 y1 x2 y2 ...
xs = coords[0::2]
ys = coords[1::2]
min_x, max_x = min(xs), max(xs)
min_y, max_y = min(ys), max(ys)
cx = (min_x + max_x) / 2
cy = (min_y + max_y) / 2
bw = max_x - min_x
bh = max_y - min_y
rows.append((cls_idx, n, cx, cy, bw, bh, lf.name, line))
return rows
def poly_to_box(coords: list[float]):
"""Convert polygon coord list [x1,y1,x2,y2,...] → (cx,cy,w,h)."""
xs = coords[0::2]
ys = coords[1::2]
x0, x1 = min(xs), max(xs)
y0, y1 = min(ys), max(ys)
return (x0+x1)/2, (y0+y1)/2, x1-x0, y1-y0
# ──────────────────────────────────────────────────────────────────────────
# A. Count polygon vs bbox per class per split
# ──────────────────────────────────────────────────────────────────────────
def audit_format(all_rows):
print("\n" + "═"*70)
print(" A. LABEL FORMAT BREAKDOWN (bbox=5 fields, polygon>5 fields)")
print("═"*70)
bbox_by_cls = defaultdict(int)
poly_by_cls = defaultdict(int)
poly_examples = [] # (cls, n_fields, line) — save up to 3 examples
for row in all_rows:
cls_idx, n, *_ , lf, line = row
if n == 5:
bbox_by_cls[cls_idx] += 1
else:
poly_by_cls[cls_idx] += 1
if len(poly_examples) < 3:
poly_examples.append((cls_idx, n, lf, line[:80]))
print(f"\n {'CLASS':<22} {'BBOX':>6} {'POLYGON':>8} {'%POLY':>7}")
print(f" {'-'*48}")
total_bbox = total_poly = 0
for i, name in enumerate(CLASS_NAMES):
b = bbox_by_cls[i]
p = poly_by_cls[i]
total_bbox += b
total_poly += p
pct = f"{100*p/(b+p):.0f}%" if (b+p) > 0 else "—"
flag = " ⚠" if p > 0 else ""
print(f" {name:<22} {b:>6} {p:>8} {pct:>7}{flag}")
print(f" {'TOTAL':<22} {total_bbox:>6} {total_poly:>8} "
f"{100*total_poly/(total_bbox+total_poly):.1f}%")
print(f"\n Sample polygon rows (truncated to 80 chars):")
for cls_idx, n, lf, line in poly_examples:
print(f" cls={CLASS_NAMES[cls_idx]} fields={n} file={lf}")
print(f" {line}")
return poly_examples
# ──────────────────────────────────────────────────────────────────────────
# B. Degenerate near-zero-area boxes
# ──────────────────────────────────────────────────────────────────────────
def audit_degenerate(all_rows):
print("\n" + "═"*70)
print(" B. DEGENERATE / NEAR-ZERO-AREA BOXES (area < 0.001 of image)")
print("═"*70)
found = []
for row in all_rows:
cls_idx, n, cx, cy, bw, bh, lf, line = row
area = bw * bh
if area < 0.001:
found.append((area, CLASS_NAMES[cls_idx], lf, line[:100]))
if not found:
print(" ✅ No degenerate boxes found.")
else:
found.sort()
for area, cls, lf, line in found:
print(f" ⚠️ {cls:<22} area={area:.6f} file={lf}")
print(f" {line}")
return found
# ──────────────────────────────────────────────────────────────────────────
# C. Per-split instance counts — pantry / microwave testability
# ──────────────────────────────────────────────────────────────────────────
def audit_split_counts():
print("\n" + "═"*70)
print(" C. PER-SPLIT INSTANCE COUNTS")
print("═"*70)
split_counts = {}
for split, label_dir in SPLITS.items():
counts = defaultdict(int)
if label_dir.exists():
for lf in label_dir.glob("*.txt"):
for line in lf.read_text(encoding="utf-8").splitlines():
parts = line.strip().split()
if parts:
counts[int(parts[0])] += 1
split_counts[split] = counts
print(f"\n {'CLASS':<22} {'TRAIN':>7} {'VALID':>7} {'TEST':>7} STATUS")
print(f" {'-'*60}")
for i, name in enumerate(CLASS_NAMES):
tr = split_counts["train"][i]
va = split_counts["valid"][i]
te = split_counts["test"][i]
flags = []
if va == 0: flags.append("no-val")
if te == 0: flags.append("no-test")
if tr <= 5: flags.append("tiny-train")
status = ", ".join(flags) if flags else "✅"
print(f" {name:<22} {tr:>7} {va:>7} {te:>7} {status}")
return split_counts
# ──────────────────────────────────────────────────────────────────────────
# D. Legends_Symbols box-size distribution
# ──────────────────────────────────────────────────────────────────────────
def audit_legends_size(all_rows):
print("\n" + "═"*70)
print(" D. LEGENDS_SYMBOLS BOX-AREA DISTRIBUTION")
print("═"*70)
areas = []
for row in all_rows:
cls_idx, n, cx, cy, bw, bh, lf, line = row
if cls_idx == 0: # Legends_Symbols
areas.append(bw * bh)
if not areas:
print(" No Legends_Symbols instances found.")
return
areas.sort()
print(f"\n Total instances : {len(areas)}")
print(f" Min area : {areas[0]:.4f} ({areas[0]*100:.2f}% of image)")
print(f" Median area : {statistics.median(areas):.4f} ({statistics.median(areas)*100:.2f}%)")
print(f" Mean area : {statistics.mean(areas):.4f} ({statistics.mean(areas)*100:.2f}%)")
print(f" Max area : {areas[-1]:.4f} ({areas[-1]*100:.2f}%)")
print(f"\n ℹ At mean={statistics.mean(areas)*100:.0f}% image coverage, any spatial")
print(f" containment check using Legends_Symbols would be meaningless.")
print(f" Current code correctly excludes it from cabinet logic.")
# Near-zero degenerate
tiny = [a for a in areas if a < 0.001]
if tiny:
print(f"\n ⚠️ {len(tiny)} near-zero area instance(s) — recommend deleting in Roboflow.")
# ──────────────────────────────────────────────────────────────────────────
# E. ultralytics segments2boxes() live demo
# ──────────────────────────────────────────────────────────────────────────
def audit_ultralytics_conversion(poly_examples):
print("\n" + "═"*70)
print(" E. ULTRALYTICS segments2boxes() LIVE CHECK")
print("═"*70)
try:
from ultralytics.utils.ops import segments2boxes
import numpy as np
print(f"\n ✅ ultralytics.utils.ops.segments2boxes found.")
print(f" This confirms modern auto-conversion IS available.\n")
if poly_examples:
cls_idx, n, lf, line = poly_examples[0]
# Rebuild full line from the label file
for split, label_dir in SPLITS.items():
lf_path = label_dir / lf
if lf_path.exists():
for raw in lf_path.read_text().splitlines():
parts = raw.strip().split()
if parts and int(parts[0]) == cls_idx and len(parts) > 5:
coords = [float(x) for x in parts[1:]]
xs = np.array(coords[0::2])
ys = np.array(coords[1::2])
seg = np.stack([xs, ys], axis=1)
# segments2boxes expects list of arrays
box = segments2boxes([seg])[0]
print(f" Example polygon → bbox conversion:")
print(f" class : {CLASS_NAMES[cls_idx]}")
print(f" polygon : {len(coords)//2} points")
print(f" raw pts : x∈[{xs.min():.3f},{xs.max():.3f}] "
f"y∈[{ys.min():.3f},{ys.max():.3f}]")
print(f" → bbox : cx={box[0]:.4f} cy={box[1]:.4f} "
f"w={box[2]:.4f} h={box[3]:.4f}")
print(f" ✅ Conversion matches manual calc: "
f"expected w≈{xs.max()-xs.min():.4f}")
break
break
except ImportError as e:
print(f"\n ❌ Could not import segments2boxes: {e}")
print(f" If using ultralytics < 8.0, polygon rows may NOT be converted.")
print(f" Upgrade: pip install ultralytics>=8.4")
# ──────────────────────────────────────────────────────────────────────────
# F. Decision table for pantry / microwave
# ──────────────────────────────────────────────────────────────────────────
def print_decisions():
print("\n" + "═"*70)
print(" F. RECOMMENDED DECISIONS")
print("═"*70)
print("""
1. PANTRY_SYMBOL (1 train, 0 val, 0 test)
─────────────────────────────────────────
Options (pick one):
[A] Collect ≥30 examples, re-annotate, retrain ← best long-term
[B] Remove class from dataset entirely; fall back to text-matching
('PANTRY', 'P', cabinet label heuristic in pipeline)
[C] Accept: keep conf=0.75 gate, document as "best-effort"
Recommendation → [B] for now: the class literally cannot generalize
from 1 example. Remove it from data.yaml (rename to "unknown" in
Roboflow, re-export), retrain without it. Add it back when you have
≥30 diverse examples.
2. MICROWAVE_SYMBOL (13 train, 2 val, 0 test)
──────────────────────────────────────────────
Options:
[A] Collect ≥30 examples, retrain ← proper fix
[B] Keep conf=0.65 gate + accept low recall
Recommendation → [B] short-term is defensible (microwave location
rarely drives cabinet schedule). But label 20 more and retrain for
Phase 4 to get meaningful mAP.
3. POLYGON ROWS (~20% of instances)
──────────────────────────────────
ultralytics 8.4+ handles these safely via segments2boxes().
Action: pin ultralytics>=8.4.0 in requirements.txt ← ALREADY DONE.
No code changes needed. Optionally re-export as bboxes from Roboflow
if you want uniform label files (cleaner, but not required).
4. DEGENERATE LEGENDS_SYMBOLS BOX (near-zero area)
──────────────────────────────────────────────────
Delete in Roboflow / label-studio and re-export. One bad annotation
won't break training but it does confuse the anchor calculator.
""")
# ──────────────────────────────────────────────────────────────────────────
# main
# ──────────────────────────────────────────────────────────────────────────
if __name__ == "__main__":
print("=" * 70)
print(" DATASET AUDIT — Cabinetries Floor Plan (12-class YOLO11)")
print(f" Dataset root: {DATASET_ROOT}")
print("=" * 70)
# Check dataset exists
if not DATASET_ROOT.exists():
print(f"\n❌ Dataset not found at: {DATASET_ROOT}")
print(" Update DATASET_ROOT at the top of this script.")
sys.exit(1)
# Load all labels across splits
all_rows = []
for split, label_dir in SPLITS.items():
if label_dir.exists():
rows = parse_labels(label_dir)
all_rows.extend(rows)
print(f" Loaded {len(rows):>5} annotations from {split}/labels")
else:
print(f" ⚠️ {split}/labels not found at {label_dir}")
print(f" {'TOTAL':>12} {len(all_rows)} annotations")
poly_examples = audit_format(all_rows)
audit_degenerate(all_rows)
audit_split_counts()
audit_legends_size(all_rows)
audit_ultralytics_conversion(poly_examples)
print_decisions()
print("\n" + "=" * 70)
print(" Audit complete.")
print("=" * 70)
+63
View File
@@ -0,0 +1,63 @@
import argparse
import json
import sys
from pathlib import Path
# Add project root to sys.path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from core.agents.config_extractor_graph import build_extractor_graph
def main():
parser = argparse.ArgumentParser(description="Auto-extract project configuration from a PDF.")
parser.add_argument("--pdf", required=True, help="Path to the architectural PDF file.")
parser.add_argument("--out", help="Path to save the extracted project_config.json.")
args = parser.parse_args()
pdf_path = Path(args.pdf)
if not pdf_path.exists():
print(f"[ERROR] PDF not found: {pdf_path}")
sys.exit(1)
print(f"Loading and analyzing PDF: {pdf_path.name}...")
graph = build_extractor_graph()
initial_state = {
"pdf_path": str(pdf_path),
"extracted_text": "",
"parsed_config": None,
"errors": [],
"retry_count": 0
}
print("Running LangGraph extractor agent...")
final_state = graph.invoke(initial_state)
errors = final_state.get("errors", [])
if errors:
print("\n[WARNING] Extraction finished with errors:")
for err in errors:
print(f" - {err}")
parsed_config = final_state.get("parsed_config")
if parsed_config:
# Convert pydantic model to dict
config_dict = parsed_config.model_dump()
if args.out:
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
with open(out_path, "w", encoding="utf-8") as f:
json.dump(config_dict, f, indent=2)
print(f"\n[SUCCESS] Extracted config saved to: {out_path}")
else:
print("\n=== EXTRACTED CONFIG ===")
print(json.dumps(config_dict, indent=2))
else:
print("\n[ERROR] Failed to extract configuration.")
sys.exit(1)
if __name__ == "__main__":
main()
+125
View File
@@ -0,0 +1,125 @@
{
"hits_above_threshold": [
[
"SINK",
"VANITY_SINK",
0.6425748467445374
]
],
"hits_below_threshold": [
[
"REFRIGERATOR",
"REF",
0.11997854709625244
]
],
"misses": [
"RANGE",
"MICROWAVE",
"DISHWASHER"
],
"all_detections": [
{
"type": "SINK",
"confidence": 0.26091715693473816,
"bbox": null,
"notes": "YOLO sink_symbol conf=0.26"
},
{
"type": "REF",
"confidence": 0.11997854709625244,
"bbox": null,
"notes": "YOLO fridge_symbol conf=0.12"
},
{
"type": "REF",
"confidence": 0.11166147142648697,
"bbox": null,
"notes": "YOLO fridge_symbol conf=0.11"
},
{
"type": "VANITY_SINK",
"confidence": 0.6425748467445374,
"bbox": null,
"notes": "YOLO vanity_sink_symbol conf=0.64"
},
{
"type": "TOILET",
"confidence": 0.5174180269241333,
"bbox": null,
"notes": "YOLO toilet_symbol conf=0.52"
},
{
"type": "VANITY_SINK",
"confidence": 0.437142550945282,
"bbox": null,
"notes": "YOLO vanity_sink_symbol conf=0.44"
},
{
"type": "TOILET",
"confidence": 0.4315090775489807,
"bbox": null,
"notes": "YOLO toilet_symbol conf=0.43"
},
{
"type": "TOILET",
"confidence": 0.4249436557292938,
"bbox": null,
"notes": "YOLO toilet_symbol conf=0.42"
},
{
"type": "BATHTUB",
"confidence": 0.4143821597099304,
"bbox": null,
"notes": "YOLO bathtub_symbol conf=0.41"
},
{
"type": "BATHTUB",
"confidence": 0.2543748915195465,
"bbox": null,
"notes": "YOLO bathtub_symbol conf=0.25"
},
{
"type": "BATHTUB",
"confidence": 0.20119225978851318,
"bbox": null,
"notes": "YOLO bathtub_symbol conf=0.20"
},
{
"type": "BATHTUB",
"confidence": 0.19444428384304047,
"bbox": null,
"notes": "YOLO bathtub_symbol conf=0.19"
},
{
"type": "BATHTUB",
"confidence": 0.15934553742408752,
"bbox": null,
"notes": "YOLO bathtub_symbol conf=0.16"
},
{
"type": "BATHTUB",
"confidence": 0.13526932895183563,
"bbox": null,
"notes": "YOLO bathtub_symbol conf=0.14"
},
{
"type": "BATHTUB",
"confidence": 0.11975958198308945,
"bbox": null,
"notes": "YOLO bathtub_symbol conf=0.12"
},
{
"type": "TOILET",
"confidence": 0.10177969932556152,
"bbox": null,
"notes": "YOLO toilet_symbol conf=0.10"
},
{
"type": "TOILET",
"confidence": 0.10144027322530746,
"bbox": null,
"notes": "YOLO toilet_symbol conf=0.10"
}
]
}
@@ -0,0 +1,216 @@
"""
evaluate_appliance_detection.py
================================
Runs the YOLO model against the Casa Familia A-6.00 floor plan at a
deliberately low confidence threshold (0.10) and reports every candidate
detection result for the 5 known ground-truth kitchen appliances.
Ground-truth appliances (5 items, Unit A1 kitchen):
- SINK
- RANGE
- REFRIGERATOR
- MICROWAVE
- DISHWASHER
NOTE ON DICT SHAPE:
detect_floor_plan() returns plain dicts, not dataclass objects.
Each detection dict uses "type" and "confidence" keys, e.g.:
{'type': 'SINK', 'x_in': ..., 'confidence': 0.261, 'notes': '...'}
All reads in this script use dict.get(), NOT getattr().
The low threshold (0.10 vs default 0.30) exposes candidates the model
"almost detected", allowing us to decide:
- Score 0.10-0.29 -> threshold-tuning fix (model sees it, just low conf)
- Score absent -> training-data gap (no candidate at all)
Usage:
python -m tools.evaluate_appliance_detection
python -m tools.evaluate_appliance_detection <path_to_pdf>
"""
from __future__ import annotations
import sys
import json
import logging
from pathlib import Path
logging.basicConfig(level=logging.WARNING, format="%(levelname)s %(message)s")
# ── Paths ─────────────────────────────────────────────────────────────────────
ROOT = Path(__file__).parents[1]
DEFAULT_PDF = (
ROOT / "Casa familia" / "01_Architectural_Drawings"
/ "Unit_Plans_FHA_ADA"
/ "A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf"
)
# ── Ground truth ──────────────────────────────────────────────────────────────
# Canonical keyword -> maps to the "type" values detect_floor_plan() emits
GROUND_TRUTH = {
"SINK": ["SINK"],
"RANGE": ["RANGE"],
"REFRIGERATOR": ["REF", "FRIDGE", "REFRIGERATOR"],
"MICROWAVE": ["MICROWAVE", "MW"],
"DISHWASHER": ["DW", "DISHWASHER"],
}
# ── Detection thresholds ──────────────────────────────────────────────────────
EVAL_CONF = 0.10 # lowered eval threshold -- surfaces near-misses
NORMAL_CONF = 0.30 # production threshold
def _load_image_from_pdf(pdf_path: Path, dpi: int = 300) -> bytes:
import fitz
doc = fitz.open(str(pdf_path))
page = doc[0]
pix = page.get_pixmap(dpi=dpi)
return pix.tobytes("png")
def _det_type(det: dict) -> str:
"""Extract the class label from a detection dict."""
return str(det.get("type", det.get("class_name", det.get("label", "")))).upper()
def _det_conf(det: dict) -> float | str:
"""Extract the confidence from a detection dict."""
return det.get("confidence", "?")
def run_evaluation(pdf_path: Path) -> dict:
"""Run YOLO at EVAL_CONF and return structured results."""
import core.yolo_extractor as yolo_mod
from core.yolo_extractor import YOLOExtractor
print(f"\n{'='*65}")
print(f" APPLIANCE DETECTION EVALUATION -- Casa Familia A-6.00")
print(f"{'='*65}")
print(f" PDF path : {pdf_path}")
print(f" Eval conf : {EVAL_CONF} (production default: {NORMAL_CONF})")
print(f"{'='*65}\n")
if not pdf_path.exists():
print(f"[ERROR] PDF not found: {pdf_path}")
print(" Pass a valid path as: python -m tools.evaluate_appliance_detection <path>")
sys.exit(1)
img_bytes = _load_image_from_pdf(pdf_path)
# Override threshold for this evaluation run only
original_conf = getattr(yolo_mod, "DETECTION_CONF", NORMAL_CONF)
yolo_mod.DETECTION_CONF = EVAL_CONF
yolo = YOLOExtractor()
try:
result = yolo.detect_floor_plan(img_bytes, dpi=300.0)
finally:
yolo_mod.DETECTION_CONF = original_conf # always restore
appliances: list = result.get("appliances", [])
fixtures: list = result.get("fixtures", [])
all_detections: list[dict] = appliances + fixtures
# ── Print raw candidates sorted by confidence ─────────────────────────────
print(f"{'─'*65}")
print(f" ALL CANDIDATES (confidence >= {EVAL_CONF})")
print(f"{'─'*65}")
if not all_detections:
print(" (none -- model returned zero detections at this threshold)")
else:
sorted_dets = sorted(
all_detections,
key=lambda d: _det_conf(d) if isinstance(_det_conf(d), float) else -1,
reverse=True,
)
for det in sorted_dets:
label = _det_type(det)
conf = _det_conf(det)
conf_str = f"{conf:.3f}" if isinstance(conf, float) else str(conf)
above = "[above 0.30]" if isinstance(conf, float) and conf >= NORMAL_CONF else "[below 0.30]"
bbox = det.get("bbox", det.get("box", "(no bbox)"))
print(f" {label:<28} conf={conf_str} {above} bbox={bbox}")
# ── Match against ground truth ────────────────────────────────────────────
print(f"\n{'─'*65}")
print(f" GROUND TRUTH MATCH (5 expected kitchen appliances)")
print(f"{'─'*65}")
hits_above_prod: list = []
hits_below_prod: list = []
misses: list = []
# Build a flat list of (type_str, conf_float) for matching
det_pairs = [((_det_type(d)), _det_conf(d)) for d in all_detections]
for gt_name, aliases in GROUND_TRUTH.items():
# Find best confidence match across aliases
best_match = None
best_conf = -1.0
for alias in aliases:
for det_type, det_conf in det_pairs:
if alias in det_type or det_type in alias:
if isinstance(det_conf, float) and det_conf > best_conf:
best_conf = det_conf
best_match = det_type
if best_match is not None and best_conf >= 0:
if best_conf >= NORMAL_CONF:
hits_above_prod.append((gt_name, best_match, best_conf))
print(f" [FOUND above 0.30] GT={gt_name:<15} matched={best_match:<20} conf={best_conf:.3f}")
else:
hits_below_prod.append((gt_name, best_match, best_conf))
print(f" [FOUND below 0.30] GT={gt_name:<15} matched={best_match:<20} conf={best_conf:.3f} <- threshold-tuning candidate")
else:
misses.append(gt_name)
print(f" [MISSING] GT={gt_name:<15} (no candidate even at conf={EVAL_CONF}) <- training data gap")
# ── Summary ───────────────────────────────────────────────────────────────
print(f"\n{'─'*65}")
print(f" SUMMARY")
print(f"{'─'*65}")
total_gt = len(GROUND_TRUTH)
print(f" Ground truth items : {total_gt}")
print(f" Detected >= 0.30 : {len(hits_above_prod)} <- production threshold (work today)")
print(f" Detected 0.10-0.29 : {len(hits_below_prod)} <- threshold-tuning can recover")
print(f" Not detected at all : {len(misses)} <- require training data")
if hits_below_prod:
print(f"\n Threshold-tuning candidates:")
for gt, lbl, conf in hits_below_prod:
headroom = NORMAL_CONF - conf
print(f" {gt:<15} detected as '{lbl}' at {conf:.3f} ({headroom:.3f} below 0.30 cutoff)")
print(f" -> Try lowering DETECTION_CONF from {NORMAL_CONF} to ~{NORMAL_CONF - 0.08:.2f}")
print(f" and re-run to check false-positive rate before committing.")
if misses:
print(f"\n Training gap candidates: {', '.join(misses)}")
print(f" -> Before re-annotating, test on a cleaner single-view sheet.")
print(f" A-6.00 is a dense multi-view sheet -- harder for small symbols.")
print(f"\n{'='*65}\n")
return {
"hits_above_threshold": [(g, m, c) for g, m, c in hits_above_prod],
"hits_below_threshold": [(g, m, c) for g, m, c in hits_below_prod],
"misses": misses,
"all_detections": [
{
"type": _det_type(d),
"confidence": _det_conf(d),
"bbox": d.get("bbox", d.get("box")),
"notes": d.get("notes", ""),
}
for d in all_detections
],
}
if __name__ == "__main__":
pdf_path = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_PDF
results = run_evaluation(pdf_path)
out_path = Path(__file__).parent / "eval_results_a600.json"
with open(out_path, "w", encoding="utf-8") as f:
json.dump(results, f, indent=2, default=str)
print(f"Raw results written to: {out_path}")
@@ -0,0 +1,143 @@
import argparse
from pathlib import Path
import sys
# Ensure root is in sys.path
ROOT = Path(__file__).resolve().parent.parent
if str(ROOT) not in sys.path:
sys.path.insert(0, str(ROOT))
from core.engines.yolo_intent_adapter import YoloIntentAdapter
from pipeline import UnitSchedule
from core.bimlite.parser import ModelBuilder
from core.engines.constraint_solver import ConstraintExtractor, ConstraintSolver
from core.engines.placement_engine import PlacementEngine
from generators.shop_drawing_pdf import generate_shop_drawings
def _nodes_to_constraint_dicts(nodes) -> list[dict]:
"""Convert BIM-lite geometry nodes → the dict shape ConstraintExtractor reads."""
out = []
for n in nodes:
width_in = getattr(n, "width_in", 0.0)
if hasattr(width_in, "inches"):
width_in = width_in.inches
md = getattr(n, "metadata", {}) or {}
out.append({
"type": getattr(n, "node_type", ""),
"width_in": width_in,
"x_in": md.get("x_in", 0.0) or 0.0,
"notes": md.get("notes", ""),
})
return out
def main():
parser = argparse.ArgumentParser(description="Generate shop drawings deterministically using YOLO + Native Text.")
parser.add_argument("--pdf", type=str, required=True, help="Path to floor plan PDF")
parser.add_argument("--unit-type", type=str, default="A1", help="Unit type name")
parser.add_argument("--output", type=str, default="outputs/shop_drawing_yolo.pdf", help="Output PDF path")
args = parser.parse_args()
pdf_path = Path(args.pdf)
if not pdf_path.exists():
print(f"File not found: {pdf_path}")
sys.exit(1)
print(f"--- Running YOLO Intent Adapter on {pdf_path.name} ---")
elevations = YoloIntentAdapter.extract_from_floor_plan(pdf_path, dpi=300.0)
print(f"Extracted {len(elevations)} elevations/rooms from floor plan.")
for ev in elevations:
print(f" {ev.elevation_label}: {len(ev.walls)} walls, {len(ev.appliances)} appliances, {len(ev.fixtures)} fixtures")
# Create UnitSchedule
schedule = UnitSchedule(
unit_type=args.unit_type,
elevations=elevations,
is_ada=False,
)
# Build Project Model
print("\n--- Building BIM-lite Project Model ---")
config = {"project_name": "Deterministic YOLO Test"}
unit_totals = {args.unit_type: 1}
unit_schedules = {args.unit_type: schedule}
project_model = ModelBuilder.build_project(
config.get("project_name", "Test"),
config,
unit_schedules,
unit_totals
)
placement_engine = PlacementEngine()
print("\n--- Running Constraint Solver & Placement Engine ---")
for bldg in project_model.buildings:
for fl in bldg.floors:
for unit in fl.units:
for room in unit.rooms:
for wall in room.walls:
try:
constraints = ConstraintExtractor.extract(
wall_name = wall.name,
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),
structural = _nodes_to_constraint_dicts(wall.structural),
is_ada = room.is_ada,
)
solved = ConstraintSolver.solve(constraints)
placed_cabs = placement_engine.place_wall(solved)
# Find the matching ElevationResult to populate for PDF generator
matching_ev = next((ev for ev in schedule.elevations if ev.elevation_label == room.name), None)
# Transfer placed cabinets back to WallModel and ElevationResult
from core.bimlite.models import CabinetNode
from core.ai_vision_classifier import CabinetItem
wall.cabinets = []
for i, cab in enumerate(placed_cabs):
w = cab.filler_width if cab.is_filler else cab.width
md = {"x_in": cab.x_start}
if cab.notes:
md["notes"] = cab.notes
# Populate BIM-lite model
wall.cabinets.append(CabinetNode(
cab_type=cab.cabinet_type,
width=w,
height=cab.height,
depth=24.0, # default base depth
metadata=md
))
# Populate ElevationResult for PDF generator tables
if matching_ev is not None:
matching_ev.cabinets.append(CabinetItem(
item_num=i + 1,
cabinet_type=cab.cabinet_type,
width_in=w,
height_in=cab.height,
depth_in=24.0,
location=f"Wall {wall.name}",
elevation_ref=matching_ev.elevation_label,
confidence=1.0,
is_ada=room.is_ada,
notes=cab.notes or "",
source="placement_engine",
cabinet_id=""
))
print(f" Placed {len(placed_cabs)} cabinets on {wall.name} in {room.__class__.__name__}")
except Exception as e:
print(f" [ERROR] Placement Engine failed on {wall.name}: {e}")
print(f"\n--- Generating Shop Drawing PDF ---")
out_path = Path(args.output)
generate_shop_drawings(config, unit_schedules, unit_totals, out_path)
print(f"Shop drawing generated at: {out_path}")
if __name__ == "__main__":
main()
+199
View File
@@ -0,0 +1,199 @@
"""
Phase 1 Inference Test — Option 1 (tiled) + Option 2 (300 DPI)
===============================================================
Run the YOLO model against a real floor plan PDF with:
- Tiled sliding-window inference (Option 1): tiles the page into
overlapping 1280x1280 crops so every symbol appears at training-scale.
- Configurable DPI (Option 2): 300 DPI catches smaller symbols.
Usage:
python tools/test_inference.py # defaults: tiled + 200 DPI
python tools/test_inference.py --dpi 300 # Option 2 only
python tools/test_inference.py --dpi 300 --tiled # Both options combined (best)
python tools/test_inference.py --pdf "path/to/custom.pdf" --dpi 300 --conf 0.30
"""
import sys
import os
import argparse
from pathlib import Path
# ── Make sure project root is on sys.path ─────────────────────────────────
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT))
# ── Default test PDF (Unit A1 — has kitchen + bath) ───────────────────────
DEFAULT_PDF = (
ROOT
/ "Casa familia"
/ "01_Architectural_Drawings"
/ "Unit_Plans_FHA_ADA"
/ "A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf"
)
# ── Output directory for annotated images ─────────────────────────────────
OUT_DIR = ROOT / "outputs" / "phase1_inference_test"
OUT_DIR.mkdir(parents=True, exist_ok=True)
def render_pdf_page(pdf_path: Path, page_idx: int, dpi: int) -> bytes:
"""Render a single PDF page to PNG bytes via PyMuPDF (fitz)."""
import fitz # PyMuPDF
doc = fitz.open(str(pdf_path))
page = doc[page_idx]
mat = fitz.Matrix(dpi / 72, dpi / 72)
pix = page.get_pixmap(matrix=mat, alpha=False)
return pix.tobytes("png")
def annotate_and_save(img_bytes: bytes, detections: list, out_path: Path):
"""Draw bounding boxes + labels on the image and save it."""
from PIL import Image, ImageDraw
import io
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
draw = ImageDraw.Draw(img)
COLOR_MAP = {
"kitchen_region": "#00BFFF",
"bath_region": "#FF69B4",
"Legends_Symbols": "#FFD700",
"bathtub_symbol": "#FF6347",
"dw_symbol": "#32CD32",
"fridge_symbol": "#00FA9A",
"microwave_symbol": "#FF8C00",
"pantry_symbol": "#DA70D6",
"range_symbol": "#FF4500",
"sink_symbol": "#1E90FF",
"toilet_symbol": "#8A2BE2",
"vanity_sink_symbol": "#DC143C",
}
for det in detections:
cls = det["class"]
conf = det["confidence"]
x0, y0, x1, y1 = det["bbox_px"]
color = COLOR_MAP.get(cls, "#FFFFFF")
draw.rectangle([x0, y0, x1, y1], outline=color, width=3)
label = f"{cls} {conf:.2f}"
draw.rectangle([x0, y0 - 18, x0 + len(label) * 7, y0], fill=color)
draw.text((x0 + 2, y0 - 16), label, fill="black")
img.save(out_path)
print(f" Annotated image saved -> {out_path.name}")
def run_test(pdf_path: Path, dpi: int, conf_threshold: float):
print("=" * 70)
print(" PHASE 1 INFERENCE TEST")
print(f" PDF : {pdf_path.name}")
print(f" DPI : {dpi}")
print(f" Conf : {conf_threshold}")
print("=" * 70)
# ── Check best.pt exists ──────────────────────────────────────────────
from core.yolo_extractor import FLOOR_PLAN_MODEL_PATH, FLOOR_PLAN_CLASSES
weights = Path(FLOOR_PLAN_MODEL_PATH)
if not weights.exists():
print(f"\n[ERROR] Weights not found at: {weights}")
print(" Copy best.pt to: models/yolo_floor_plan/weights/best.pt")
sys.exit(1)
print(f"\n[OK] Weights found ({weights.stat().st_size / 1_000_000:.1f} MB)")
print(f"[OK] Classes in model: {len(FLOOR_PLAN_CLASSES)}")
print(f" {FLOOR_PLAN_CLASSES}\n")
# ── Load model once ───────────────────────────────────────────────────
print(" Loading YOLO model ...")
from ultralytics import YOLO
model = YOLO(str(weights))
print(" [OK] Model loaded\n")
# ── Check PDF exists ──────────────────────────────────────────────────
if not pdf_path.exists():
print(f"[ERROR] PDF not found: {pdf_path}")
sys.exit(1)
import fitz
doc = fitz.open(str(pdf_path))
total_pages = len(doc)
doc.close()
print(f" PDF has {total_pages} page(s)\n")
grand_total = 0
for page_idx in range(total_pages):
print(f" --- Page {page_idx + 1} / {total_pages} ---")
img_bytes = render_pdf_page(pdf_path, page_idx, dpi)
# ── Run raw YOLO inference ────────────────────────────────────────
import numpy as np
from PIL import Image
import io
img_pil = Image.open(io.BytesIO(img_bytes)).convert("RGB")
img_arr = np.array(img_pil)
raw = model(img_arr, conf=conf_threshold, verbose=False)[0]
all_dets_raw = []
for box in raw.boxes:
cls_name = raw.names[int(box.cls)]
conf_val = float(box.conf)
x0, y0, x1, y1 = (float(v) for v in box.xyxy[0])
all_dets_raw.append({
"class": cls_name,
"confidence": conf_val,
"bbox_px": (x0, y0, x1, y1),
})
# ── Print detection table ─────────────────────────────────────────
if not all_dets_raw:
print(" (no detections above threshold)")
else:
print(f" {'CLASS':<25} {'CONF':>6} BBOX (px)")
print(f" {'-'*60}")
for d in sorted(all_dets_raw, key=lambda x: x["class"]):
x0, y0, x1, y1 = d["bbox_px"]
print(f" {d['class']:<25} {d['confidence']:>6.3f} "
f"({x0:.0f},{y0:.0f}) -> ({x1:.0f},{y1:.0f})")
print(f" {'='*60}")
print(f" Total detections this page: {len(all_dets_raw)}")
grand_total += len(all_dets_raw)
# ── Save annotated image ──────────────────────────────────────────
out_img = OUT_DIR / f"{pdf_path.stem}_page{page_idx+1:02d}.png"
annotate_and_save(img_bytes, all_dets_raw, out_img)
# ── Run pipeline extractor and print summary ──────────────────────
from core.yolo_extractor import YOLOExtractor
extractor = YOLOExtractor()
result = extractor.detect_floor_plan(img_bytes, dpi=dpi)
print(f"\n PIPELINE SUMMARY (after conf filtering):")
print(f" kitchen_regions : {len(result.get('kitchen_regions', []))}")
print(f" bath_regions : {len(result.get('bath_regions', []))}")
print(f" legend_regions : {len(result.get('legend_regions', []))}")
print(f" appliances : {len(result.get('appliances', []))}")
for ap in result.get("appliances", []):
print(f" -> {ap['type']:<12} x={ap['x_in']:.1f}\" w={ap['width_in']:.1f}\" "
f"conf={ap['confidence']:.2f}")
print(f" fixtures : {len(result.get('fixtures', []))}")
for fx in result.get("fixtures", []):
print(f" -> {fx['type']:<12} x={fx['x_in']:.1f}\" w={fx['width_in']:.1f}\" "
f"conf={fx['confidence']:.2f}")
print()
print("=" * 70)
print(f" [DONE] Grand total detections: {grand_total}")
print(f" Annotated images saved in: {OUT_DIR}")
print("=" * 70)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Phase 1 YOLO inference test")
parser.add_argument("--pdf", default=str(DEFAULT_PDF), help="Path to floor plan PDF")
parser.add_argument("--dpi", type=int, default=200, help="Render DPI (default 200)")
parser.add_argument("--conf", type=float, default=0.35, help="Confidence threshold (default 0.35)")
args = parser.parse_args()
run_test(Path(args.pdf), args.dpi, args.conf)
+73
View File
@@ -0,0 +1,73 @@
import sys
from pathlib import Path
from core.pdf_extractor import PDFExtractor
from core.yolo_extractor import YOLOExtractor
# Test file
PDF_PATH = Path("Casa familia/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf")
def main():
if not PDF_PATH.exists():
print(f"File not found: {PDF_PATH}")
sys.exit(1)
print(f"--- Extracting native text from {PDF_PATH.name} ---")
# 1. Run YOLO Extractor
print("Running YOLO Extraction (200 DPI)...")
import fitz
doc = fitz.open(PDF_PATH)
page = doc[0]
pix = page.get_pixmap(dpi=300)
img_bytes = pix.tobytes("png")
import core.yolo_extractor
core.yolo_extractor.DETECTION_CONF = 0.30
yolo = YOLOExtractor()
yolo_res = yolo.detect_floor_plan(img_bytes, dpi=300.0)
kitchens = yolo_res.get("kitchen_regions", [])
if not kitchens:
print("No kitchen regions found by YOLO.")
else:
print(f"Found {len(kitchens)} kitchen region(s).")
for k in kitchens:
print(f" {k}")
baths = yolo_res.get("bath_regions", [])
print(f"Found {len(baths)} bath region(s).")
# 2. Run PDFExtractor
print("\nRunning PDFExtractor...")
with PDFExtractor(PDF_PATH) as ex:
spans = ex.extract_spans(0)
print(f"Total text spans on page: {len(spans)}")
# 3. Filter spans by YOLO regions
for region_name, regions in [("Kitchen", kitchens), ("Bath", baths)]:
for i, r in enumerate(regions):
print(f"\n--- Text Spans inside {region_name} {i+1} ---")
# YOLO boxes are in pixels at 200 DPI
x0_px, y0_px, x1_px, y1_px = r.bbox_px
# Convert to PDF points
x0_pt = x0_px * 72.0 / 300.0
y0_pt = y0_px * 72.0 / 300.0
x1_pt = x1_px * 72.0 / 300.0
y1_pt = y1_px * 72.0 / 300.0
# Expand the box slightly to catch dimensions on the outside of walls
pad = 40.0
x0_pt -= pad
y0_pt -= pad
x1_pt += pad
y1_pt += pad
for s in spans:
# Check if span center is inside the expanded region
if x0_pt <= s.cx <= x1_pt and y0_pt <= s.cy <= y1_pt:
print(f" {s.text} (x={s.cx:.1f}, y={s.cy:.1f})")
if __name__ == "__main__":
main()

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