Refactor LayoutFingerprintEngine and fix Shop Drawing Matrix formatting

- Introduce LayoutFingerprintEngine for topological hashing

- Remove KitchenLayoutClassifier overrides in pipeline

- Update MatrixBuilder to use the new FingerprintEngine

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

- Fix Matrix Page alignment, font hierarchy, and border widths
This commit is contained in:
Atharv1705
2026-07-01 16:44:00 +05:30
parent ee2a024ff0
commit 1074a112e8
6 changed files with 326 additions and 121 deletions
@@ -0,0 +1,120 @@
import json
import hashlib
from typing import Dict, Any, List
class LayoutFingerprintEngine:
"""
Engine to generate a deterministic, hierarchical architectural fingerprint
for kitchens and vanities. This signature is based on layout topology,
cabinet geometry, appliance placements, and ADA requirements.
"""
@staticmethod
def _infer_layout_topology(cabinets: List[Dict[str, Any]]) -> str:
"""
Infer if the layout is Straight, L-Shape, U-Shape, etc.
based on corner cabinets and bounding boxes.
"""
corner_count = 0
for cab in cabinets:
cab_type = cab.get('cabinet_type', '').lower()
notes = cab.get('notes', '').lower()
if 'corner' in cab_type or 'blind' in cab_type or 'corner' in notes:
corner_count += 1
if corner_count == 0:
return "Straight"
elif corner_count == 1:
return "L-Shape"
elif corner_count >= 2:
return "U-Shape"
return "Complex"
@staticmethod
def _extract_cabinets(cabinets: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Extract purely cabinet geometry and types."""
extracted = []
for cab in cabinets:
cab_type = cab.get('cabinet_type', '')
if 'appliance' in cab_type or 'microwave' in cab_type:
continue
extracted.append({
"type": cab_type,
"width": cab.get('width_in', 0.0),
"height": cab.get('height_in', 0.0),
"depth": cab.get('depth_in', 0.0),
"position_hint": cab.get('location', '')
})
return extracted
@staticmethod
def _extract_appliances(cabinets: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Extract appliance spaces from the sequence."""
extracted = []
for cab in cabinets:
cab_type = cab.get('cabinet_type', '')
if 'appliance' in cab_type or 'microwave' in cab_type or 'ref' in cab.get('notes', '').lower() or 'range' in cab.get('notes', '').lower():
extracted.append({
"type": cab_type,
"width": cab.get('width_in', 0.0),
"notes": cab.get('notes', '')
})
return extracted
@staticmethod
def _extract_openings(cabinets: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Extract explicit openings (windows/doors/columns) if mentioned."""
openings = []
for cab in cabinets:
notes = cab.get('notes', '').lower()
if 'window' in notes:
openings.append({"type": "Window", "near": cab.get('location', '')})
if 'door' in notes:
openings.append({"type": "Door", "near": cab.get('location', '')})
if 'column' in notes:
openings.append({"type": "Column", "near": cab.get('location', '')})
return openings
@staticmethod
def generate_fingerprint(unit_elevation: Dict[str, Any]) -> str:
"""
Generates the MD5 hash of the hierarchical fingerprint for an elevation.
"""
cabinets = unit_elevation.get('cabinets', [])
is_ada = unit_elevation.get('is_ada', False)
# 1. Layout Topology
layout = LayoutFingerprintEngine._infer_layout_topology(cabinets)
# 2. Cabinets
cabs_fingerprint = LayoutFingerprintEngine._extract_cabinets(cabinets)
# 3. Appliances
apps_fingerprint = LayoutFingerprintEngine._extract_appliances(cabinets)
# 4. Openings
openings = LayoutFingerprintEngine._extract_openings(cabinets)
# 5. Overall dimensions
total_width = sum(c.get('width_in', 0.0) for c in cabinets if c.get('cabinet_type') not in ['upper_wall'])
# Build hierarchy
fingerprint_dict = {
"Layout": layout,
"Cabinets": cabs_fingerprint,
"Appliances": apps_fingerprint,
"Openings": openings,
"Countertop": {
"Topology": layout,
"CornerCount": sum(1 for c in cabinets if 'corner' in c.get('cabinet_type', '').lower())
},
"ADA": is_ada,
"Overall": {
"TotalBaseWidth": total_width
}
}
# Hash
sig_str = json.dumps(fingerprint_dict, sort_keys=True)
return hashlib.md5(sig_str.encode()).hexdigest()
@@ -2,36 +2,9 @@ import json
import os
from typing import Dict, List, Any
from collections import defaultdict
import hashlib
from core.engines.layout_fingerprint_engine import LayoutFingerprintEngine
class UnitMatrixBuilder:
@staticmethod
def _generate_signature(unit: Dict[str, Any], type_key: str) -> str:
"""Generates a unique deterministic signature based on physical layout properties."""
components = unit.get(type_key, [])
if not components:
return "NONE"
try:
sorted_comps = sorted(components, key=lambda c: c.get('x', 0))
except KeyError:
sorted_comps = components
sequence = []
for c in sorted_comps:
nom = c.get('nomenclature', c.get('id', ''))
sequence.append(nom)
is_ada = unit.get('is_ada', False)
signature_dict = {
"sequence": sequence,
"ada": is_ada
}
sig_str = json.dumps(signature_dict, sort_keys=True)
return hashlib.md5(sig_str.encode()).hexdigest()
@staticmethod
def save_signatures(signatures_map: Dict[str, str], filepath: str = "data/layout_signatures.json"):
os.makedirs(os.path.dirname(filepath), exist_ok=True)
@@ -61,8 +34,13 @@ class UnitMatrixBuilder:
unit_qty = unit.get('quantity', 1)
is_ada = unit.get('is_ada', False)
k_sig = UnitMatrixBuilder._generate_signature(unit, 'kitchen')
v_sig = UnitMatrixBuilder._generate_signature(unit, 'vanity')
k_sig = "NONE"
if 'kitchen' in unit:
k_sig = LayoutFingerprintEngine.generate_fingerprint({'cabinets': unit['kitchen'], 'is_ada': is_ada})
v_sig = "NONE"
if 'vanity' in unit:
v_sig = LayoutFingerprintEngine.generate_fingerprint({'cabinets': unit['vanity'], 'is_ada': is_ada})
k_type = "NONE"
if k_sig != "NONE":
@@ -0,0 +1,4 @@
{
"K1": "af03461580dcef194124a51ad1f3a329",
"K2": "53346be807b8a6380437803c0b0a4877"
}
@@ -0,0 +1,4 @@
{
"V1": "6b441dd38d7a568334689994cf729b49",
"V2": "1d2899eb249fef8aa8627102687f3f88"
}
+128 -32
View File
@@ -202,34 +202,126 @@ def _draw_cover(c: canvas.Canvas, config: dict, unit_totals: dict, total_pages:
# Project Info Block
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 22)
c.drawCentredString((DA_L + DA_R) / 2, PAGE_H * 0.44,
c.drawCentredString((DA_L + DA_R) / 2, PAGE_H * 0.65,
"CABINET SHOP DRAWINGS")
c.setFont(_FONT_BOLD, 18)
c.drawCentredString((DA_L + DA_R) / 2, PAGE_H * 0.37,
c.drawCentredString((DA_L + DA_R) / 2, PAGE_H * 0.60,
config.get("project_name", "PROJECT"))
c.setFont(_FONT_REG, 11)
c.drawCentredString((DA_L + DA_R) / 2, PAGE_H * 0.31,
c.drawCentredString((DA_L + DA_R) / 2, PAGE_H * 0.56,
config.get("address", ""))
# Info table
info_items = [
("Project No:", config.get("project_id", "")),
("Date:", config.get("date", "")),
("Finish:", config.get("finish", "Standard 1")),
("Door Style:", config.get("door_style", "Shaker")),
("Total Units:", str(sum(unit_totals.values()))),
("Revision:", config.get("revision", "1.0")),
]
start_y = PAGE_H * 0.25
col_x = (DA_L + DA_R) / 2 - 120
for i, (label, val) in enumerate(info_items):
y = start_y - i * 16
c.setFont(_FONT_BOLD, 9)
c.drawRightString(col_x + 80, y, label)
c.setFont(_FONT_REG, 9)
c.drawString(col_x + 85, y, val)
# Finish Box
finish_x = DA_L + 60
finish_y = PAGE_H * 0.45
c.setStrokeColor(NAVY)
c.setLineWidth(1.0)
c.rect(finish_x, finish_y - 60, 240, 60, stroke=1, fill=0)
# Title "FINISH" with dark background in the box header
c.setFillColor(NAVY)
c.rect(finish_x, finish_y - 18, 240, 18, stroke=1, fill=1)
c.setFillColor(WHITE)
c.setFont(_FONT_BOLD, 10)
c.drawCentredString(finish_x + 120, finish_y - 12, "FINISH")
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 12)
c.drawCentredString(finish_x + 120, finish_y - 42, config.get("finish", "Standard 1"))
# Door style underneath
c.setFont(_FONT_REG, 10)
c.drawCentredString(finish_x + 120, finish_y - 55, f"Door Style: {config.get('door_style', 'Shaker')}")
# General Notes Section
notes_x = DA_L + 60
notes_y = PAGE_H * 0.30
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 12)
c.drawString(notes_x, notes_y, "GENERAL NOTES:")
c.setFont(_FONT_REG, 9)
y_offset = notes_y - 15
notes = config.get("general_notes", [])
if not notes:
notes = [
"1. ALL CABINETS ARE 90CM DEPTH",
"2. FINISH: K019 SILVER LIBERTY ELM",
"3. ALL HARDWARE CONCEALED",
"4. SOFT CLOSE DOORS AND DRAWERS STANDARD",
"5. ADA UNITS: BASE CABINET HEIGHT 864MM MAX / COUNTERTOP HEIGHT 34\" MAX",
"6. ALL DIMENSIONS MUST BE VERIFIED IN FIELD PRIOR TO FABRICATION.",
"7. ALL SHOP DRAWINGS ARE SUBJECT TO ARCHITECTURAL APPROVAL.",
"8. INSTALLATION AS PER MANUFACTURER'S SPECIFICATIONS.",
"9. REFER TO ARCHITECTURAL PLANS FOR FINISHED WALL / FINISHED FLOOR REFERENCES.",
"10. ELECTRICAL, PLUMBING & HVAC EXCLUDED FROM MILLWORK SCOPE.",
"11. COMPLIANCE WITH ADA GUIDELINES IS THE RESPONSIBILITY OF THE GC/ARCHITECT."
]
for note in notes:
c.drawString(notes_x + 10, y_offset, note)
y_offset -= 12
# Appliance Schedule
app_x = DA_L + 400
app_y = PAGE_H * 0.45
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 12)
c.drawString(app_x, app_y, "APPLIANCE SCHEDULE:")
c.setFont(_FONT_BOLD, 9)
c.drawString(app_x + 10, app_y - 15, "REGULAR UNITS:")
c.setFont(_FONT_REG, 8)
ay = app_y - 25
for app in config.get("appliances_regular", []):
c.drawString(app_x + 20, ay, app)
ay -= 10
ay -= 10
c.setFont(_FONT_BOLD, 9)
c.drawString(app_x + 10, ay, "ADA UNITS:")
c.setFont(_FONT_REG, 8)
ay -= 10
for app in config.get("appliances_ada", []):
c.drawString(app_x + 20, ay, app)
ay -= 10
# Revision Log
rev_x = DA_R - 350
rev_y = PAGE_H * 0.45
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 12)
c.drawString(rev_x, rev_y, "REVISIONS:")
# Table header
c.setStrokeColor(NAVY)
c.setLineWidth(1.0)
c.rect(rev_x, rev_y - 150, 300, 140, stroke=1, fill=0)
# Draw cols
c.line(rev_x + 30, rev_y - 10, rev_x + 30, rev_y - 150)
c.line(rev_x + 80, rev_y - 10, rev_x + 80, rev_y - 150)
c.line(rev_x + 140, rev_y - 10, rev_x + 140, rev_y - 150)
# Draw rows
for i in range(11):
ry = (rev_y - 10) - (14 * i)
c.line(rev_x, ry, rev_x + 300, ry)
c.setFont(_FONT_BOLD, 8)
c.drawString(rev_x + 5, rev_y - 20, "NO.")
c.drawString(rev_x + 35, rev_y - 20, "INITIALS")
c.drawString(rev_x + 90, rev_y - 20, "DATE")
c.drawString(rev_x + 150, rev_y - 20, "DESCRIPTION")
# Insert current revision
c.setFont(_FONT_REG, 8)
c.drawString(rev_x + 5, rev_y - 34, config.get("revision", "1.0"))
c.drawString(rev_x + 35, rev_y - 34, config.get("drawn_by", "A.C"))
c.drawString(rev_x + 90, rev_y - 34, config.get("date", ""))
c.drawString(rev_x + 150, rev_y - 34, "INITIAL ISSUE / FOR APPROVAL")
# Footer
c.setFont(_FONT_REG, 8)
@@ -262,12 +354,12 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
_draw_title_block(c, config, 2, total_pages, "PROJECT MATRIX")
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 14)
c.setFont(_FONT_BOLD, 18)
c.drawString(DA_L + 10, DA_T - 20, "PROJECT CABINET MATRIX")
c.setFont(_FONT_REG, 8)
c.setFont(_FONT_BOLD, 11)
c.setFillColor(colors.black)
c.drawString(DA_L + 10, DA_T - 32, config.get("project_name", "CASA FAMILIA"))
c.drawString(DA_L + 10, DA_T - 36, config.get("project_name", "CASA FAMILIA"))
# Table dimensions
cols = [120, 48, 38, 38, 38, 38, 95, 62.5, 62.5]
@@ -287,13 +379,15 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
c.setStrokeColor(NAVY)
c.setLineWidth(0.5)
# Draw vertical lines in header
# Draw vertical lines in header (Outer group border)
c.setLineWidth(1.0)
c.line(col_x[1], ty - 48, col_x[1], ty)
c.line(col_x[2], ty - 48, col_x[2], ty)
c.line(col_x[6], ty - 48, col_x[6], ty)
c.line(col_x[7], ty - 48, col_x[7], ty)
# Sub-columns V1-V4 vertical lines
# Sub-columns V1-V4 vertical lines (Inner cell border)
c.setLineWidth(0.5)
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)
@@ -310,23 +404,24 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
# Header texts
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 8)
# Main headers
c.setFont(_FONT_BOLD, 9)
c.drawCentredString(tx + 60, ty - 28, "UNIT NAME")
c.drawCentredString(col_x[1] + 24, ty - 10, "QTY")
c.drawCentredString(col_x[1] + 24, ty - 35, "TOTAL")
c.drawCentredString(col_x[2] + 76, ty - 12, "VANITY TYPE")
c.drawCentredString(col_x[6] + 47.5, ty - 28, "KITCHEN TYPE")
c.drawCentredString(col_x[7] + 62.5, ty - 12, "KITCHEN TYPE")
# Sub-headers
c.setFont(_FONT_BOLD, 8)
c.drawCentredString(col_x[2] + 19, ty - 26, "V1")
c.drawCentredString(col_x[3] + 19, ty - 26, "V2")
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[6] + 47.5, ty - 28, "KITCHEN TYPE")
c.drawCentredString(col_x[7] + 62.5, ty - 12, "KITCHEN TYPE")
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")
@@ -472,7 +567,7 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
# 6. Summary Totals below table (just like in the image)
sum_y = ry - 20
c.setFont(_FONT_BOLD, 8)
c.setFont(_FONT_BOLD, 10)
c.setFillColor(colors.black)
# Totals numbers centered under respective columns
@@ -486,6 +581,7 @@ def _draw_casa_familia_matrix(c: canvas.Canvas, config: dict, unit_totals: dict,
# Vanity labels below totals numbers
lbl_y = sum_y - 12
c.setFont(_FONT_BOLD, 9)
c.drawCentredString(tx + sum(cols[:2]) + cols[2] / 2, lbl_y, "V1")
c.drawCentredString(tx + sum(cols[:3]) + cols[3] / 2, lbl_y, "V2")
c.drawCentredString(tx + sum(cols[:4]) + cols[4] / 2, lbl_y, "V3")
+62 -59
View File
@@ -640,18 +640,70 @@ def run_pipeline(
for ut, cnt in unit_totals.items():
matrix_counts[(first_bldg, 1, ut)] = cnt
# Build unit data for UnitMatrixBuilder
unit_data = []
for (bldg, fl, ut), cnt in matrix_counts.items():
if cnt > 0:
schedule = unit_schedules.get(ut)
if schedule:
# Convert Cabinet objects to dicts for the fingerprint engine
k_cabs = [vars(c) if hasattr(c, '__dict__') else c for c in schedule.kitchen_cabinets]
v_cabs = [vars(c) if hasattr(c, '__dict__') else c for c in schedule.bath_cabinets]
unit_data.append({
"name": ut,
"quantity": cnt,
"is_ada": ut in ada_units,
"building": bldg,
"floor": fl,
"kitchen": k_cabs,
"vanity": v_cabs
})
# Re-import UnitMatrixBuilder dynamically since it might not be at the top
from core.engines.unit_matrix_builder import UnitMatrixBuilder
# Process the units to get dynamic K and V types
built_matrix = UnitMatrixBuilder.build_unit_matrix(unit_data)
# Map back to unit_matrix_list
for row in built_matrix:
# built_matrix returns flat list but we originally tracked building/floor in unit_data
# Actually UnitMatrixBuilder drops building/floor. We should enrich it.
# Wait, build_unit_matrix preserves unit_name, unit_qty, kitchen_type, vanity_type.
pass
# Let's fix UnitMatrixBuilder integration.
# The original loop just appended to unit_matrix_list.
# We can run UnitMatrixBuilder to get the mapping of unit_type -> types
type_map = {}
for res in built_matrix:
type_map[res['unit_name']] = {
'kitchen_type': res['kitchen_type'],
'vanity_type': res['vanity_type']
}
for (bldg, fl, ut), cnt in matrix_counts.items():
if cnt > 0:
k_type = type_map.get(ut, {}).get('kitchen_type', 'K1')
v_type = type_map.get(ut, {}).get('vanity_type', 'V1')
unit_matrix_list.append({
"building": bldg,
"floor": fl,
"unit_type": ut,
"count": cnt,
"kitchen_type": "K1",
"bathroom_type": "V1",
"kitchen_type": k_type,
"bathroom_type": v_type,
"is_ada": ut in ada_units
})
# Save to JSON like it was expected
json_dir = output_dir / "json"
json_dir.mkdir(exist_ok=True)
with open(json_dir / "unit_matrix_final.json", "w") as f:
json.dump(unit_matrix_list, f, indent=2)
# ── Step 3–4: Pricing + Job Costing ───────────────────────────────────
print(f"\n STEP 3: Price Matching (Euro list -> USD)")
print(f" {'-' * 50}")
@@ -846,69 +898,20 @@ def run_pipeline(
from core.vanity_layout_classifier import VanityLayoutClassifier
from core.cabinet_graph_builder import CabinetGraphBuilder
kitchen_classifier = KitchenLayoutClassifier()
vanity_classifier = VanityLayoutClassifier()
# We can remove kitchen_classifier and vanity_classifier entirely since we rely on LayoutFingerprintEngine now.
graph_builder = CabinetGraphBuilder()
for ut, schedule in unit_schedules.items():
vanity_cabs_list = []
for ev in schedule.elevations:
for cab in ev.cabinets:
if cab.cabinet_type in ("vanity", "medicine_cabinet", "linen"):
vanity_cabs_list.append({
"type": cab.cabinet_type,
"width_in": cab.width_in,
"is_ada": cab.is_ada,
"notes": cab.notes,
"location": cab.location
})
bathroom_type = vanity_classifier.get_vanity_type(vanity_cabs_list)
walls_info = []
kitchen_appliances = []
for ev in schedule.elevations:
if ev.elevation_label.upper() in ("BATH", "VANITY", "MASTER_BATH"):
continue
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
if wall_name.upper() in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
wall_name = "A"
cabs_on_wall = []
for cab in ev.cabinets:
w_in = round(cab.width_in)
cabs_on_wall.append({
"id": cab.cabinet_id or cab.code,
"type": cab.cabinet_type,
"x": 0,
"notes": cab.notes
})
wall_len = sum(round(c.width_in) for c in ev.cabinets)
walls_info.append({
"name": wall_name,
"length": wall_len or 90.0,
"cabinets": cabs_on_wall
})
for app in ev.appliances:
kitchen_appliances.append({
"type": app.get("type", "REF"),
"wall": wall_name,
"x": app.get("x_in", 0)
})
if not walls_info:
walls_info.append({
"name": "A",
"length": 90.0,
"cabinets": []
})
kitchen_type = kitchen_classifier.get_kitchen_type(walls_info, kitchen_appliances, layout_shape="straight")
# Get types from the dynamically generated type_map built earlier
k_type = type_map.get(ut, {}).get('kitchen_type', 'K1')
v_type = type_map.get(ut, {}).get('vanity_type', 'V1')
# Build final schemas
shop_drawing = graph_builder.build_shop_drawing_schema(
unit_type = ut,
elevations = schedule.elevations,
kitchen_type = kitchen_type,
bathroom_type = bathroom_type,
kitchen_type = k_type,
bathroom_type = v_type,
layout_shape = "straight"
)
cost_drawing = graph_builder.build_cost_schema(
@@ -917,8 +920,8 @@ def run_pipeline(
is_ada = schedule.is_ada
)
schedule.kitchen_type = kitchen_type
schedule.bathroom_type = bathroom_type
schedule.kitchen_type = k_type
schedule.bathroom_type = v_type
schedule.shop_drawing_schema = shop_drawing
schedule.cost_schema = cost_drawing