feat: Fix v_matrix parsing and add HITL layout rendering support

This commit is contained in:
Atharv1705
2026-09-29 11:05:50 +05:30
parent 7ebae8a4a5
commit e003fce9d8
5 changed files with 364 additions and 54 deletions
@@ -0,0 +1,56 @@
from typing import List, Dict, Optional, Any
from pydantic import BaseModel, Field
class CompanyInfo(BaseModel):
name: str = Field(default="ITALIAN KITCHEN AND BATH")
tagline: str = Field(default="kitchen | bath | tile | closet")
address: str = Field(default="1777 NW 72TH AVE. MIAMI FL, 33126")
phone: str = Field(default="T. 305.599.9000 F. 305.599.9870")
class RevisionInfo(BaseModel):
rev: str = Field(..., description="Revision number, e.g. '1.0'")
date: str = Field(..., description="Date of revision")
initials: str = Field(..., description="Initials of the drafter")
desc: str = Field(default="", description="Description of the revision")
class UnitMatrixRow(BaseModel):
unit: str = Field(..., description="Full unit name, e.g. 'UNIT A1'")
qty: int = Field(..., description="Quantity of this unit")
v1: int = Field(default=0, description="Quantity of V1 vanities")
v2: int = Field(default=0, description="Quantity of V2 vanities")
v3: int = Field(default=0, description="Quantity of V3 vanities")
v4: int = Field(default=0, description="Quantity of V4 vanities")
kitchen: str = Field(..., description="Kitchen type key, e.g. 'K1' or 'K2'")
is_ada: bool = Field(default=False, description="True if unit is ADA accessible")
key: str = Field(..., description="Short key identifier, e.g. 'A1' or 'A2-ADA'")
class ExtractedConfigMetadata(BaseModel):
"""
Extracted top-level metadata from an architectural PDF cover page.
"""
class Config:
extra = "allow"
project_id: str = Field(default="new_project", description="Short ID without spaces")
project_name: str = Field(default="New Project", description="Full name of the project")
project_no: str = Field(default="", description="Project number, if any")
matrix_format: str = Field(default="v_matrix")
client_name: str = Field(default="")
project_address: str = Field(default="")
date: str = Field(default="")
revision: str = Field(default="1.0")
drawn_by: str = Field(default="")
dimension: str = Field(default="CM|INCHES")
finish: str = Field(default="", description="e.g. K019 SILVER LIBERTY ELM")
door_style: str = Field(default="Slab")
company: CompanyInfo = Field(default_factory=CompanyInfo)
revisions: List[RevisionInfo] = Field(default_factory=list)
appliances_regular: List[str] = Field(default_factory=list, description="List of regular appliances")
appliances_ada: List[str] = Field(default_factory=list, description="List of ADA appliances")
general_notes: List[str] = Field(default_factory=list, description="List of general notes")
buildings: Dict[str, List[str]] = Field(default_factory=dict, description="Map of building names to a list of unit keys")
unit_matrix: List[UnitMatrixRow] = Field(default_factory=list, description="Rows of the unit matrix table")
unit_counts: Dict[str, int] = Field(default_factory=dict, description="Auto-computed: Maps unit key to quantity.")
unit_plan_pdfs: Dict[str, str] = Field(default_factory=dict, description="TODO: Needs manual intervention. Maps unit key to PDF file path.")
kitchen_types: Dict[str, Any] = Field(default_factory=dict, description="TODO: Vision extraction for V2")
vanity_types: Dict[str, Any] = Field(default_factory=dict, description="TODO: Vision extraction for V2")
+3 -1
View File
@@ -35,10 +35,12 @@ class ProjectConfig(BaseModel):
price_list_path: str = ""
unit_plan_pdfs: dict[str, str] = Field(default_factory=dict)
buildings: dict[str, dict] = Field(default_factory=dict)
buildings: dict[str, list[str]] | dict[str, dict] = Field(default_factory=dict)
class Config:
populate_by_name = True
extra = "allow"
def load_project_config(config_path: str | Path) -> dict:
"""Load and validate project configuration JSON, returning a normalized dict."""
+179 -53
View File
@@ -143,6 +143,7 @@ def process_unit(
skip_ai: bool = False,
demo_mode: bool = False,
force_ocr: bool = False,
deterministic: bool = False,
) -> UnitSchedule:
"""
Process one unit type PDF: extract → detect → crop → AI → validate.
@@ -187,6 +188,17 @@ def process_unit(
print(f"\n [{unit_type}] Processing: {pdf_path.name}")
if deterministic:
print(f" [{unit_type}] Using Deterministic YoloIntentAdapter...")
from core.engines.yolo_intent_adapter import YoloIntentAdapter
elevations = YoloIntentAdapter.extract_from_floor_plan(pdf_path, dpi=200.0)
schedule.elevations = elevations
for ev in schedule.elevations:
ev.is_ada = is_ada
ev.unit_type = unit_type
ev.project_name = project_name
return schedule
# Initialize YOLO once per unit
from core.yolo_extractor import YOLOExtractor
yolo = YOLOExtractor()
@@ -504,7 +516,7 @@ def compute_pricing(
(total_material_cost_usd, total_cabinet_count).
"""
price_list_path = project_root / config.get("price_list_path", "")
use_fallback = not price_list_path.exists()
use_fallback = not (price_list_path.exists() and price_list_path.is_file())
if use_fallback:
print(f"\n [WARN] Price list not found — using fallback USD catalog: {price_list_path}")
@@ -559,6 +571,7 @@ def run_pipeline(
dry_run: bool = False,
demo_mode: bool = False,
force_ocr: bool = False,
deterministic: bool = False,
) -> PipelineResult:
"""
Run the complete cabinet estimation pipeline.
@@ -626,37 +639,47 @@ def run_pipeline(
print(f"\n STEP 1: PDF Extraction + AI Classification")
print(f" {'-' * 50}")
for unit_type, pdf_paths in unit_plan_pdfs.items():
if unit_filter and unit_type != unit_filter:
continue
print(f" [DEBUG] matrix_format is: {repr(config.get('matrix_format'))}")
if config.get("matrix_format") == "v_matrix":
print(f" [V-MATRIX MODE] Building unit schedules from project_config.json manual mapping...")
try:
from v_matrix_adapter import populate_v_matrix
unit_schedules = populate_v_matrix(config, project_name)
except Exception as e:
print(f" [WARN] Failed to populate v_matrix: {e}")
else:
for unit_type, pdf_paths in unit_plan_pdfs.items():
if unit_filter and unit_type != unit_filter:
continue
is_ada = unit_type in ada_units
if isinstance(pdf_paths, str):
pdf_paths = [pdf_paths]
combined_schedule = None
for path_str in pdf_paths:
pdf_path = project_root / path_str
schedule = process_unit(
unit_type = unit_type,
pdf_path = pdf_path,
project_name = project_name,
is_ada = is_ada,
output_dir = output_dir,
classifier = classifier,
validator = validator,
skip_ai = skip_ai,
demo_mode = demo_mode,
force_ocr = force_ocr,
)
if combined_schedule is None:
combined_schedule = schedule
else:
combined_schedule.elevations.extend(schedule.elevations)
combined_schedule.review_flags.extend(schedule.review_flags)
combined_schedule.legend_map.update(schedule.legend_map)
is_ada = unit_type in ada_units
if isinstance(pdf_paths, str):
pdf_paths = [pdf_paths]
unit_schedules[unit_type] = combined_schedule
combined_schedule = None
for path_str in pdf_paths:
pdf_path = project_root / path_str
schedule = process_unit(
unit_type = unit_type,
pdf_path = pdf_path,
project_name = project_name,
is_ada = is_ada,
output_dir = output_dir,
classifier = classifier,
validator = validator,
skip_ai = skip_ai,
demo_mode = demo_mode,
force_ocr = force_ocr,
deterministic = deterministic,
)
if combined_schedule is None:
combined_schedule = schedule
else:
combined_schedule.elevations.extend(schedule.elevations)
combined_schedule.review_flags.extend(schedule.review_flags)
combined_schedule.legend_map.update(schedule.legend_map)
unit_schedules[unit_type] = combined_schedule
# ── Step 2: Unit Count Matrix ──────────────────────────────────────────
print(f"\n STEP 2: Unit Count Matrix")
@@ -674,6 +697,11 @@ def run_pipeline(
matrix.print_summary()
unit_totals = matrix.totals
# If matrix extraction found nothing, default to 1 per schedule so pricing works
if not unit_totals:
print(" [WARN] No unit counts extracted. Defaulting to 1 per unit type for estimation.")
unit_totals = {ut: 1 for ut in unit_schedules.keys()}
# ── Step 2.5: BIM-Lite Model Construction & Placement Engine ─────────
print(f"\n STEP 2.5: BIM-Lite Placement Engine & Validation")
@@ -685,6 +713,7 @@ def run_pipeline(
from core.engines.layout_fingerprint_engine import LayoutFingerprintEngine
from core.bimlite.bom_engine import BOMEngine
from core.ai_vision_classifier import CabinetItem
from core.bimlite.models import VanityModel, KitchenModel
# 1. Build Project Model
project_model = ModelBuilder.build_project(project_name, config, unit_schedules, unit_totals)
@@ -717,15 +746,25 @@ def run_pipeline(
placement_engine = PlacementEngine()
mfg = placement_engine.mfg # manufacturing rules (heights/depths)
processed_units = set()
for bldg in project_model.buildings:
for fl in bldg.floors:
for unit in fl.units:
if unit.name in processed_units:
continue
processed_units.add(unit.name)
schedule = unit_schedules.get(unit.name)
if not schedule:
continue
kitchen_placed = []
vanity_placed = []
# Guard: each ElevationResult may only be written into once
# (base + upper injection). Without this, the fuzzy _elev_matches
# fires on every wall in a multi-wall room, multiplying cabs.
matched_elevs: set = set()
for room in unit.rooms:
for wall in room.walls:
try:
@@ -769,31 +808,57 @@ def run_pipeline(
else:
kitchen_placed.extend(placed_cabs)
# Match back to the AI schedule for UI rendering
# Match back to the AI schedule for UI rendering.
# Deterministic labels: "KITCHEN 1 (Deterministic)" must match
# room.name="KITCHEN" or wall.name="wall_a" — use substring/prefix
# matching in addition to exact match.
def _elev_matches(ev_label: str, wall_n: str, room_n: str) -> bool:
clean = ev_label.replace("ELEVATION ", "").strip().upper()
for target in (wall_n.upper(), room_n.upper()):
if clean == target:
return True
# Deterministic: "KITCHEN 1 (Deterministic)" starts with "KITCHEN"
if clean.startswith(target) or target.startswith(clean.split()[0]):
return True
return False
matching_elev = next(
(ev for ev in schedule.elevations
if ev.elevation_label.replace("ELEVATION ", "").strip() == wall.name),
if id(ev) not in matched_elevs
and _elev_matches(ev.elevation_label, wall.name, room.name)),
None,
)
if not matching_elev:
continue
matched_elevs.add(id(matching_elev))
base_height = mfg.ada_base_height if room.is_ada else mfg.base_height
# Reset elevation cabinets before writing deterministic placement output.
# Without this, AI-extracted cabinets and placement-engine cabinets
# accumulate in the same list — corrupting counts and shop drawing output.
matching_elev.cabinets = []
for idx, pc in enumerate(placed_cabs, start=1):
# Preserve non-base items (uppers, pantries, appliances) from AI extraction
preserved_cabs = [
c for c in matching_elev.cabinets
if c.cabinet_type not in ("base", "sink_base", "drawer_base", "vanity", "filler", "blind_base")
and not (c.cabinet_id or "").upper().startswith("B")
]
matching_elev.cabinets = preserved_cabs
# ── Write cabinets (Base & Upper from Placement Engine) ───────────────
for idx, pc in enumerate(placed_cabs, start=len(preserved_cabs) + 1):
width_in = pc.filler_width if pc.is_filler else float(pc.width)
is_upper = pc.cabinet_type in ("upper_wall", "microwave_shelf", "corner_upper", "medicine_cabinet")
cab_height = float(pc.height) if pc.height else (mfg.upper_height if is_upper else base_height)
cab_depth = mfg.upper_depth if is_upper else mfg.base_depth
matching_elev.cabinets.append(CabinetItem(
item_num = idx,
cabinet_type = pc.cabinet_type,
width_in = width_in,
height_in = base_height,
depth_in = mfg.base_depth,
height_in = cab_height,
depth_in = cab_depth,
location = f"{unit.name} / {matching_elev.elevation_label}",
elevation_ref = matching_elev.elevation_label,
confidence = 1.0, # deterministic — not an AI guess
confidence = 1.0,
is_ada = room.is_ada,
notes = pc.notes,
source = "placement_engine",
@@ -931,6 +996,15 @@ def run_pipeline(
gp_target_pct = config.get("gp_target_pct", 0.35),
commission_pct = config.get("commission_pct", 0.05),
bond_pct = config.get("bond_pct", 0.015),
local_use_tax_pct = config.get("local_use_tax_pct"),
ocean_freight_per_container = config.get("ocean_freight_per_container"),
inland_delivery = config.get("inland_delivery"),
installation_per_cabinet = config.get("installation_per_cabinet"),
warehousing_pct = config.get("warehousing_pct"),
material_protection_pct = config.get("material_protection_pct"),
insurance_pct = config.get("insurance_pct"),
misc_allowance = config.get("misc_allowance"),
cabinets_per_container = config.get("cabinets_per_container"),
)
jc_result = calculate_selling_price(jc_input)
@@ -1039,18 +1113,38 @@ def run_pipeline(
geom_engine = GeometryEngine()
dxf_generator = DXFDrawingGenerator()
hitl_layouts = {}
for ut, schedule in unit_schedules.items():
walls_info = []
for ev in schedule.elevations:
cabs_list = []
base_x = 0
for cab in ev.cabinets:
w_in = round(cab.width_in)
h_in = round(cab.height_in)
d_in = round(cab.depth_in) if getattr(cab, 'depth_in', None) else 0
cabs_list.append({
base_x = 0.0
upper_x = 0.0
# Sort cabinets: first base/tall/appliances, then uppers so we can stack them nicely
# 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"))
return 1 if is_upper else 0
sorted_cabs = sorted(ev.cabinets, key=cab_sort_key)
base_cfg = []
upper_cfg = []
for cab in sorted_cabs:
w_in = round(float(cab.width_in))
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")
cab_dict = {
"id": cab.cabinet_id or cab.code,
"x": base_x,
"width": w_in,
"height": h_in,
"depth": d_in,
@@ -1058,8 +1152,13 @@ def run_pipeline(
"is_ada": cab.is_ada,
"location": cab.location,
"notes": cab.notes
})
base_x += w_in
}
if is_upper:
upper_cfg.append(cab_dict)
else:
base_cfg.append(cab_dict)
base_x += w_in
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
# Ensure we keep the actual name (e.g. KITCHEN, BATHROOM) instead of renaming everything to A
@@ -1069,13 +1168,14 @@ def run_pipeline(
msg = (f"[{ut}] Wall '{wall_name}' accumulated length {base_x:.1f}"
f' — no real cabinets placed, defaulting to 90". Mark for REVIEW.')
print(f" [WARN] {msg}")
result.warnings.append(msg)
pipeline_errors.append(msg)
base_x = 90.0
walls_info.append({
"name": wall_name,
"length": base_x,
"cabinets": cabs_list
"base_cfg": base_cfg,
"upper_cfg": upper_cfg,
})
if not walls_info:
@@ -1090,13 +1190,28 @@ def run_pipeline(
if ev.ceiling_height_in is not None:
ceiling_height = ev.ceiling_height_in
break
if isinstance(ceiling_height, dict):
ceiling_height = max([float(v) for v in ceiling_height.values() if v]) if ceiling_height else 96.0
elif isinstance(ceiling_height, list):
ceiling_height = max([float(v) for v in ceiling_height if v]) if ceiling_height else 96.0
try:
ceiling_height = float(ceiling_height)
except (ValueError, TypeError):
ceiling_height = 96.0
if ceiling_height is None:
ceiling_height = 108.0
ceiling_height = 96.0
msg = (f"[{ut}] Ceiling height not extracted from drawings "
f'— defaulting to 108". Mark for REVIEW.')
f'— defaulting to 96". Mark for REVIEW.')
print(f" [WARN] {msg}")
result.warnings.append(msg)
pipeline_errors.append(msg)
hitl_layouts[ut] = {
"walls": walls_info,
"ceiling_height": ceiling_height
}
geom_data = geom_engine.generate_layout_geometry(
walls = walls_info,
@@ -1107,6 +1222,12 @@ def run_pipeline(
dxf_path = dxf_dir / f"{ut.replace(' ', '_')}.dxf"
dxf_generator.generate(geom_data, dxf_path)
hitl_path = output_dir / "json" / "hitl_layouts.json"
hitl_path.parent.mkdir(parents=True, exist_ok=True)
hitl_path.write_text(json.dumps(hitl_layouts, indent=2), encoding="utf-8")
print(f" [SUCCESS] HITL layout saved: {hitl_path}")
except Exception as e:
msg = f"DXF generation failed: {e}"
print(f" [ERROR] {msg}")
@@ -1266,6 +1387,10 @@ Examples:
"--ocr", action="store_true",
help="Force OCR text extraction on all pages using PaddleOCR"
)
parser.add_argument(
"--deterministic", action="store_true",
help="Use deterministic RegionDetector + YOLO layout extraction instead of Gemini Vision"
)
return parser.parse_args()
@@ -1278,4 +1403,5 @@ if __name__ == "__main__":
dry_run = args.dry_run,
demo_mode = args.demo,
force_ocr = args.ocr,
deterministic = args.deterministic,
)
@@ -0,0 +1,60 @@
import argparse
from pathlib import Path
import json
from core.geometry_engine import GeometryEngine
from generators.shop_drawing_dxf import DXFDrawingGenerator
from generators.shop_drawing_pdf import generate_shop_drawings
from core.config_loader import load_project_config
def main():
parser = argparse.ArgumentParser(description="Render DXF and PDF from HITL JSON.")
parser.add_argument("--project", required=True, help="Path to project config JSON")
parser.add_argument("--hitl", required=True, help="Path to hitl_layouts.json")
parser.add_argument("--output-dir", required=False, help="Directory to save outputs")
args = parser.parse_args()
config_path = Path(args.project)
hitl_path = Path(args.hitl)
if not hitl_path.exists():
print(f"File not found: {hitl_path}")
return
config = load_project_config(config_path)
output_dir = Path(args.output_dir) if args.output_dir else config_path.parent / "outputs" / config.get("project_id", "project")
dxf_dir = output_dir / "dxf"
dxf_dir.mkdir(parents=True, exist_ok=True)
geom_engine = GeometryEngine()
dxf_generator = DXFDrawingGenerator()
hitl_layouts = json.loads(hitl_path.read_text(encoding="utf-8"))
# Render DXFs
for ut, layout in hitl_layouts.items():
walls_info = layout.get("walls", [])
ceiling_height = layout.get("ceiling_height", 96.0)
geom_data = geom_engine.generate_layout_geometry(
walls = walls_info,
appliances = [],
ceiling_height = ceiling_height,
soffit_height = ceiling_height - 12.0
)
dxf_path = dxf_dir / f"{ut.replace(' ', '_')}.dxf"
dxf_generator.generate(geom_data, dxf_path)
print(f"Generated DXF for {ut}: {dxf_path}")
# PDF generation requires unit_schedules and unit_totals from config
# In a real HITL, we might also need to update the cost estimation, but for now we'll just mock unit_schedules.
# The PDF generator relies on unit_schedules. Since we only have HITL layouts, we can either re-run step 1,
# or adapt PDF generator to read HITL json.
print("\nTo generate PDF with updated layouts, please use the main pipeline, or modify generators/shop_drawing_pdf.py to accept hitl_layouts.")
if __name__ == "__main__":
main()
+66
View File
@@ -0,0 +1,66 @@
from core.ai_vision_classifier import CabinetItem
from pipeline import UnitSchedule, ElevationResult
def _extract_walls(cfg_obj):
walls = []
for key, val in cfg_obj.items():
if key.startswith("wall_"):
walls.append(val)
return walls
def populate_v_matrix(config, project_name):
unit_schedules = {}
k_types = config.get("kitchen_types", {})
v_types = config.get("vanity_types", {})
unit_matrix_cfg = config.get("unit_matrix", [])
for um_entry in unit_matrix_cfg:
unit_key = um_entry.get("key")
is_ada = um_entry.get("is_ada", False)
schedule = UnitSchedule(unit_type=unit_key, is_ada=is_ada)
k_key = um_entry.get("kitchen")
if k_key and k_key in k_types:
for wall in _extract_walls(k_types[k_key]):
er = ElevationResult(elevation_label=wall.get("label", "KITCHEN"), unit_type=unit_key, project_name=project_name, is_ada=is_ada, cabinets=[])
for cab in wall.get("cabinets", []):
w_in = float(cab.get("width_cm", 0)) / 2.54 if "width_cm" in cab else float(cab.get("width", cab.get("width_in", 0)))
cab_item = CabinetItem(
item_num=1,
cabinet_type=cab.get("type", "base"),
width_in=w_in,
height_in=0.0,
depth_in=0.0,
location="",
elevation_ref="",
confidence=1.0,
cabinet_id=cab.get("id")
)
er.cabinets.append(cab_item)
schedule.elevations.append(er)
for v_idx in range(1, 5):
v_count = um_entry.get(f"v{v_idx}", 0)
v_key = f"V{v_idx}"
if v_count > 0 and v_key in v_types:
for _ in range(v_count):
for wall in _extract_walls(v_types[v_key]):
er = ElevationResult(elevation_label=wall.get("label", "BATH"), unit_type=unit_key, project_name=project_name, is_ada=is_ada, cabinets=[])
for cab in wall.get("cabinets", []):
w_in = float(cab.get("width_cm", 0)) / 2.54 if "width_cm" in cab else float(cab.get("width", cab.get("width_in", 0)))
cab_item = CabinetItem(
item_num=1,
cabinet_type=cab.get("type", "base"),
width_in=w_in,
height_in=0.0,
depth_in=0.0,
location="",
elevation_ref="",
confidence=1.0,
cabinet_id=cab.get("id")
)
er.cabinets.append(cab_item)
schedule.elevations.append(er)
unit_schedules[unit_key] = schedule
return unit_schedules