Fix cabinet overlapping in shop drawings, update DXF styling, and fix PDF scaling

This commit is contained in:
Atharv1705
2026-06-23 15:20:57 +05:30
parent 985a1f0b85
commit 151e3f7e17
85 changed files with 279443 additions and 4737 deletions
-40
View File
@@ -1,40 +0,0 @@
# ── Python cache ──────────────────────────────────────────────────────────
__pycache__/
*.py[cod]
*.pyo
*.pyd
.Python
*.egg-info/
dist/
build/
*.egg
# ── Virtual environments ───────────────────────────────────────────────────
.venv/
venv/
env/
# ── OS files ──────────────────────────────────────────────────────────────
.DS_Store
Thumbs.db
desktop.ini
# ── Large binary / generated output files ─────────────────────────────────
# Keep source PDFs (architectural drawings) but skip large generated outputs
OUTPUT_ARCH_ANALYSIS.pdf
EXTRACTION_OUTPUT/
# ── Temporary Excel lock files ────────────────────────────────────────────
~$*.xlsx
~$*.xls
# ── API keys / secrets ────────────────────────────────────────────────────
.env
*.env
secrets.py
config_local.py
# ── IDE ───────────────────────────────────────────────────────────────────
.vscode/
.idea/
*.code-workspace
Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

+123
View File
@@ -0,0 +1,123 @@
#!/usr/bin/env python3
"""
===========================================================================
convert_dxf_to_pdf.py — DXF to PDF sheet conversion utility
===========================================================================
Converts AutoCAD DXF CAD drawing files into vector PDF sheets using
ezdxf and matplotlib.
Usage:
python convert_dxf_to_pdf.py --input outputs/23-045/dxf/A-1.dxf --output outputs/23-045/A-1_dxf.pdf
python convert_dxf_to_pdf.py --dir outputs/23-045/dxf/ --output-dir outputs/23-045/pdf_sheets/
===========================================================================
"""
from __future__ import annotations
import argparse
import sys
from pathlib import Path
try:
import ezdxf
from ezdxf.addons.drawing import RenderContext, Frontend
from ezdxf.addons.drawing.matplotlib import MatplotlibBackend
import matplotlib.pyplot as plt
except ImportError as e:
print(f" [ERROR] Missing required dependencies for DXF rendering: {e}")
print(" Please install them using: pip install ezdxf matplotlib")
sys.exit(1)
def convert_file(dxf_path: str | Path, pdf_path: str | Path) -> bool:
"""Converts a single DXF file to PDF."""
dxf_path = Path(dxf_path)
pdf_path = Path(pdf_path)
if not dxf_path.exists():
print(f" [ERROR] DXF file not found: {dxf_path}")
return False
pdf_path.parent.mkdir(parents=True, exist_ok=True)
print(f" Rendering: {dxf_path.name} -> {pdf_path.name}...")
try:
doc = ezdxf.readfile(str(dxf_path))
msp = doc.modelspace()
from ezdxf.addons.drawing.properties import LayoutProperties
# Set up a tabloid landscape sheet figure
fig = plt.figure(figsize=(17, 11))
ax = fig.add_axes([0, 0, 1, 1])
ax.set_axis_off()
ctx = RenderContext(doc)
out = MatplotlibBackend(ax)
# Force white background so colors adapt correctly (e.g. ACI 7 draws as black)
layout_props = LayoutProperties.from_layout(msp)
layout_props.set_colors(bg="#FFFFFF")
Frontend(ctx, out).draw_layout(msp, finalize=True, layout_properties=layout_props)
fig.savefig(str(pdf_path), dpi=300, bbox_inches='tight', pad_inches=0)
plt.close(fig)
print(f" [SUCCESS] Rendered to PDF: {pdf_path}")
return True
except Exception as e:
print(f" [ERROR] Rendering failed for {dxf_path.name}: {e}")
return False
def convert_directory(dxf_dir: str | Path, output_dir: str | Path):
"""Converts all DXF files inside a directory to PDF."""
dxf_dir = Path(dxf_dir)
output_dir = Path(output_dir)
if not dxf_dir.exists() or not dxf_dir.is_dir():
print(f" [ERROR] DXF directory not found: {dxf_dir}")
return
dxf_files = list(dxf_dir.glob("*.dxf"))
if not dxf_files:
print(f" [WARN] No .dxf files found in: {dxf_dir}")
return
output_dir.mkdir(parents=True, exist_ok=True)
print(f" Processing {len(dxf_files)} DXF files from: {dxf_dir.name}")
success_count = 0
for dxf_path in dxf_files:
pdf_path = output_dir / f"{dxf_path.stem}_dxf.pdf"
if convert_file(dxf_path, pdf_path):
success_count += 1
print(f"\n [COMPLETE] Successfully converted {success_count}/{len(dxf_files)} DXF files to: {output_dir}")
def main():
parser = argparse.ArgumentParser(description="AutoCAD DXF to PDF conversion utility")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--input", help="Path to single DXF file to convert")
group.add_argument("--dir", help="Path to directory containing DXF files to convert")
parser.add_argument("--output", help="Path to output PDF file (required for --input)")
parser.add_argument("--output-dir", help="Path to output PDF directory (required for --dir)")
args = parser.parse_args()
if args.input:
if not args.output:
print(" [ERROR] --output is required when using --input")
sys.exit(1)
convert_file(args.input, args.output)
elif args.dir:
if not args.output_dir:
# parser hyphens are converted to underscores in arg name
pass
out_dir = args.output_dir or str(Path(args.dir) / "pdf_sheets")
convert_directory(args.dir, out_dir)
if __name__ == "__main__":
main()
+322 -193
View File
@@ -18,9 +18,9 @@
Pipeline per elevation crop:
1. Receive: PNG image bytes (400 DPI crop) + pre-extracted dims + rects
2. Build: structured prompt with dimension context
2. Build: structured prompt with dimension context and legend mappings
3. Call: OpenRouter API (gemini-2.5-flash) with base64 image
4. Parse: JSON response → list[CabinetItem]
4. Parse: JSON response → detailed dict containing cabinets, openings, relationships
5. Retry with gemini-2.5-pro if JSON parse fails or confidence < 0.7
6. Exponential backoff on API errors
@@ -53,7 +53,7 @@ MAX_TOKENS = 4096
# Reduces cost from ~$0.0015/call → ~$0.0002/call (~85% savings)
DEMO_MODE: bool = os.getenv("DEMO_MODE", "false").lower() in ("1", "true", "yes")
DEMO_DPI = 150 # vs 400 in full mode — image tokens: ~88% smaller
DEMO_MAX_TOKENS = 800 # vs 4096 — output capped tightly
DEMO_MAX_TOKENS = 1200 # slightly larger for complex nested JSON output
DEMO_MAX_DIMS = 8 # vs 30 pre-extracted dims sent in context
DEMO_MAX_RECTS = 10 # vs 40 rectangle vectors sent in context
@@ -95,6 +95,7 @@ class CabinetItem:
is_ada: bool = False
notes: str = ""
source: str = "gemini" # "gemini" | "manual" | "fallback"
cabinet_id: str = "" # keynote ID (e.g. U10, U3)
@property
def code(self) -> str:
@@ -129,7 +130,7 @@ class CabinetItem:
@dataclass
class ElevationResult:
"""Result of classifying one elevation section."""
"""Result of classifying one elevation section with detailed schema support."""
elevation_label: str # "ELEVATION A"
unit_type: str # "A1", "B1-ADA"
project_name: str
@@ -140,6 +141,19 @@ class ElevationResult:
review_flags: list[str] = field(default_factory=list)
api_calls: int = 0
# Extended parsed details
appliances: list[dict] = field(default_factory=list)
doors: list[dict] = field(default_factory=list)
windows: list[dict] = field(default_factory=list)
fillers: list[str] = field(default_factory=list)
panels: list[str] = field(default_factory=list)
moldings: list[str] = field(default_factory=list)
relationships: list[dict] = field(default_factory=list)
ceiling_height_in: Optional[float] = None
soffit_present: bool = False
backsplash: str = ""
counter_material: str = ""
@property
def kitchen_cabinets(self) -> list[CabinetItem]:
return [c for c in self.cabinets
@@ -169,21 +183,99 @@ class ElevationResult:
def _build_system_prompt(demo: bool = False) -> str:
if demo:
# Compact prompt — ~250 tokens vs ~800 tokens
return (
"You are a cabinet estimator. Analyze this architectural elevation drawing and return "
"a JSON array of cabinets. Types: upper_wall, base, sink_base, dw_adjacent, "
"microwave_shelf, pantry, corner_upper, corner_base, vanity, medicine_cabinet, "
"linen, appliance_space, filler, unknown. "
"Each item: {item_num, cabinet_type, width_mm, height_mm, depth_mm, location, "
"elevation_ref, confidence, quantity, is_ada, notes}. "
"Std widths: 300,350,400,450,500,550,600,762,900mm. "
"Base h=720mm d=600mm. Wall h=300mm d=330mm. Pantry h=2130mm. "
"Return ONLY valid JSON array, no markdown."
"a JSON object with the following schema:\n"
"{\n"
" \"ceiling_height_in\": 108,\n"
" \"soffit_present\": false,\n"
" \"backsplash\": \"4\\\" backsplash\",\n"
" \"counter_material\": \"Quartz\",\n"
" \"cabinets\": [\n"
" { \"item_num\": 1, \"cabinet_type\": \"upper_wall\", \"cabinet_id\": \"U10\", \"width_mm\": 762, \"height_mm\": 720, \"depth_mm\": 330, \"location\": \"Left of range\", \"confidence\": 0.95, \"quantity\": 1, \"is_ada\": false, \"notes\": \"\" }\n"
" ],\n"
" \"appliances\": [\n"
" { \"type\": \"REF\", \"width_in\": 36, \"height_in\": 70, \"x_in\": 0, \"notes\": \"\" }\n"
" ],\n"
" \"doors\": [\n"
" { \"width_in\": 36, \"height_in\": 80, \"x_in\": 120, \"notes\": \"\" }\n"
" ],\n"
" \"windows\": [\n"
" { \"width_in\": 36, \"height_in\": 48, \"x_in\": 60, \"sill_height_in\": 36, \"notes\": \"\" }\n"
" ],\n"
" \"fillers\": [\"F3\"],\n"
" \"panels\": [\"EP24\"],\n"
" \"moldings\": [\"CM96\"],\n"
" \"relationships\": [\n"
" { \"type\": \"above\", \"item_a\": \"MIC\", \"item_b\": \"RANGE\", \"notes\": \"\" }\n"
" ]\n"
"}\n"
"Return ONLY valid JSON."
)
return """You are an expert cabinet estimator with 20+ years of experience reading architectural kitchen and bathroom elevation drawings for US residential construction projects (FHA/ADA housing).
Your job is to analyze architectural elevation drawings and extract a precise, complete cabinet schedule.
Your job is to analyze architectural elevation drawings and extract a precise, complete cabinet and appliance schedule with wall segmentation, ceiling details, opening dimensions, fillers, moldings, and spatial relationships.
You must return a single JSON object matching this schema:
{
"ceiling_height_in": 108, // Ceiling height in inches if visible or indicated, else null
"soffit_present": false, // true if a soffit (dropped ceiling bulkhead above cabinets) is present
"backsplash": "4\\" backsplash", // Wall finish backsplash description, or empty string
"counter_material": "Quartz", // Countertop material description, or empty string
"cabinets": [
{
"item_num": 1,
"cabinet_type": "upper_wall", // from cabinet types listed below
"cabinet_id": "U10", // Keynote code matching the KEYNOTE LEGEND MAPPING if specified
"width_mm": 762, // Width in mm
"height_mm": 720, // Height in mm
"depth_mm": 330, // Depth in mm
"location": "Left of range", // Position description
"confidence": 0.95, // Confidence score (0.0 to 1.0)
"quantity": 1,
"is_ada": false,
"notes": ""
}
],
"appliances": [
{
"type": "REF", // Refrigerator (REF), Dishwasher (DW), Range (RANGE), Microwave (MIC), Hood (HOOD), Oven (OVEN)
"width_in": 36,
"height_in": 70,
"x_in": 0, // Approximate offset in inches from left wall/boundary
"notes": ""
}
],
"doors": [
{
"width_in": 36,
"height_in": 80,
"x_in": 120, // Approximate offset in inches from left wall/boundary
"notes": ""
}
],
"windows": [
{
"width_in": 36,
"height_in": 48,
"x_in": 60, // Approximate offset in inches from left wall/boundary
"sill_height_in": 36, // Sill height in inches from floor
"notes": ""
}
],
"fillers": ["F3"], // Filler keynote codes (e.g. F3, F6) or dimensions (e.g. 3" Filler)
"panels": ["EP24"], // End panel keynote codes (e.g. EP24, WEP30)
"moldings": ["CM96"], // Crown molding/scribe keynote codes (e.g. CM, SCR)
"relationships": [
{
"type": "above", // "above" or "adjacent"
"item_a": "MIC", // item_num, appliance type, or cabinet_id (e.g., "MIC", "U10")
"item_b": "RANGE", // item_num, appliance type, or cabinet_id (e.g., "RANGE", "U12")
"notes": "Microwave above range"
}
]
}
CABINET TYPES you must classify:
- upper_wall: Wall-mounted cabinet (above countertop)
@@ -201,39 +293,20 @@ CABINET TYPES you must classify:
- filler: Filler panel (narrow strips between cabinets or walls)
- unknown: Cannot determine type with confidence
STANDARD DIMENSIONS (metric, 90cm depth standard):
- Base cabinets: height 720mm (34.5"), depth 600mm (24")
- ADA base: height 864mm (34" countertop max), depth 600mm
- Wall/upper cabinets: height 300mm (12"), 380mm (15"), 720mm (30"), depth 330mm (13")
- Pantry: height 2130mm (84"), depth 600mm
- Vanity: height 870mm (34.5"), depth 530mm (21")
- Standard widths: 150, 300, 350, 400, 450, 500, 550, 600mm (6",12",14",16",18",20",22",24")
and 762mm (30"), 900mm (35.4"), 1050mm (41.3"), 1200mm (47.2")
STANDARD DIMENSIONS (metric):
- Base cabinets: height 720mm, depth 600mm
- ADA base: height 864mm max, depth 600mm
- Wall/upper cabinets: height 300, 380, 460, 720, 900mm; depth 330mm
- Pantry: height 2130mm, depth 600mm
- Vanity: height 870mm, depth 530mm
- Standard widths: 150, 300, 350, 400, 450, 500, 550, 600, 762, 900, 1050, 1200mm
RULES:
1. Count ONLY cabinets. Do NOT count appliances (dishwasher, refrigerator, range, microwave).
2. Mark appliance positions as type "appliance_space" with the appliance name in "notes".
1. Try to match each cabinet/appliance to the provided KEYNOTE LEGEND MAPPING if it matches description and dimensions. Set "cabinet_id" to the keynote code (e.g. "U10").
2. Mark appliance positions as type "appliance_space" with the appliance name in "notes". Also add them to the "appliances" list.
3. If the drawing shows ADA text or 34" countertop, set is_ada: true.
4. Provide a confidence score (0.0-1.0) for EACH item. Be conservative — if unsure, score 0.7 or lower.
5. ALWAYS return valid JSON — no markdown, no explanation text around the JSON.
6. If you cannot determine a dimension precisely, use the nearest standard size and note your assumption.
OUTPUT FORMAT (JSON array, no other text):
[
{
"item_num": 1,
"cabinet_type": "upper_wall",
"width_mm": 762,
"height_mm": 300,
"depth_mm": 330,
"location": "Left of range, Elevation A",
"elevation_ref": "ELEVATION A",
"confidence": 0.92,
"quantity": 1,
"is_ada": false,
"notes": ""
}
]"""
4. Return ONLY valid JSON — no markdown, no explanation text around the JSON.
"""
def _build_user_prompt(
@@ -243,6 +316,7 @@ def _build_user_prompt(
pre_extracted_dims: list[dict],
pre_extracted_rects: list[dict],
is_ada: bool = False,
legend_map: Optional[dict[str, str]] = None,
demo: bool = False,
) -> str:
"""Build the user message with pre-extracted context."""
@@ -265,27 +339,40 @@ def _build_user_prompt(
rects_str += (f" R{i+1}: W={r.get('w',0):.0f}pt H={r.get('h',0):.0f}pt "
f"@ ({r.get('x0',0):.0f},{r.get('y0',0):.0f})\n")
legend_str = ""
if legend_map:
legend_str = "\nKEYNOTE LEGEND MAPPING:\n"
for k, v in sorted(legend_map.items(), key=lambda item: int(item[0][1:]) if item[0][1:].isdigit() else 999):
legend_str += f" - {k}: {v}\n"
if demo:
return (f"Project:{project_name} Unit:{unit_type}{ada_note} Section:{elevation_label}\n"
f"{dims_str}\nIdentify all cabinets. Return ONLY JSON array.")
f"{dims_str}\n{legend_str}\nIdentify all cabinets and features. Return ONLY a valid JSON object matching the requested schema.")
return f"""Project: {project_name}
Unit Type: {unit_type}{ada_note}
Section: {elevation_label}
I am showing you a cropped section of an architectural elevation drawing.
{dims_str}{rects_str}
{dims_str}{rects_str}{legend_str}
Please identify EVERY cabinet in this elevation drawing.
For each rectangle/cabinet shape visible:
Please identify EVERY cabinet and spatial feature in this elevation drawing.
For each cabinet shape visible:
1. Determine its type (upper_wall, base, sink_base, dw_adjacent, microwave_shelf, pantry, corner_upper, corner_base, vanity, medicine_cabinet, linen, appliance_space, filler, unknown)
2. Measure/estimate its width in mm (use pre-extracted dimensions if available)
3. Determine height and depth from standard sizes
4. Note its position
5. Score your confidence
4. Match it to a keynote code (cabinet_id) from the KEYNOTE LEGEND MAPPING above if applicable (e.g. U10, U3). If none match, leave blank.
5. Note its position and score confidence.
Include appliance spaces (dishwasher, range, refrigerator) as type "appliance_space".
Return ONLY the JSON array, nothing else."""
Also identify:
- Ceiling height if indicated, and whether a soffit is present.
- Doors and windows (with approximate widths/heights and offsets from left edge).
- Appliances (REF, DW, RANGE, MIC, HOOD, OVEN) with widths and offsets.
- Wall finishes (backsplash and countertop material).
- Accessories (fillers, end panels, moldings).
- Spatial relationship pairs (adjacent and above relationships).
Return ONLY the JSON object, nothing else."""
# ══════════════════════════════════════════════════════════════════════════
@@ -294,17 +381,8 @@ Return ONLY the JSON array, nothing else."""
class CabinetVisionClassifier:
"""
Classifies cabinets from architectural elevation drawing images
Classifies cabinets and layouts from architectural elevation drawing images
using Google Gemini vision models through OpenRouter.
Usage:
classifier = CabinetVisionClassifier()
result = classifier.classify_elevation(
image_bytes=png_bytes,
unit_type="A1",
elevation_label="ELEVATION A",
project_name="Casa Familia",
)
"""
def __init__(self):
@@ -330,24 +408,12 @@ class CabinetVisionClassifier:
pre_extracted_dims: Optional[list[dict]] = None,
pre_extracted_rects: Optional[list[dict]] = None,
is_ada: bool = False,
legend_map: Optional[dict[str, str]] = None,
max_retries: int = 3,
demo_mode: bool = None, # None = use global DEMO_MODE
) -> ElevationResult:
"""
Classify all cabinets in one elevation section.
Args:
image_bytes: PNG bytes of the cropped elevation (400 DPI)
unit_type: e.g. "A1", "B1-ADA"
elevation_label: e.g. "ELEVATION A", "KITCHEN EL."
project_name: e.g. "Casa Familia"
pre_extracted_dims: list of {text, type, x, y} from dimension_parser
pre_extracted_rects: list of {x0, y0, x1, y1, w, h} from pdf_extractor
is_ada: True if this unit is ADA/accessible
max_retries: number of API retry attempts on failure
Returns:
ElevationResult with list of CabinetItem
Classify all cabinets and features in one elevation section.
"""
# Resolve demo mode — argument overrides global flag
use_demo = DEMO_MODE if demo_mode is None else demo_mode
@@ -372,6 +438,7 @@ class CabinetVisionClassifier:
pre_extracted_dims = pre_extracted_dims or [],
pre_extracted_rects = pre_extracted_rects or [],
is_ada = is_ada,
legend_map = legend_map,
demo = use_demo,
)
@@ -396,25 +463,80 @@ class CabinetVisionClassifier:
return result
# Parse JSON response
cabinets = self._parse_cabinet_json(raw_json, elevation_label)
if cabinets is None and not use_demo:
data = self._parse_cabinet_json(raw_json, elevation_label)
if data is None and not use_demo:
# Full mode only: retry with fallback model (Gemini 2.5 Pro)
fix_prompt = (
f"{user_prompt}\n\nIMPORTANT: Return ONLY a valid JSON array. "
"No explanation text, no markdown fences, just the raw JSON array."
f"{user_prompt}\n\nIMPORTANT: Return ONLY a valid JSON object matching the requested schema. "
"No explanation text, no markdown fences, just the raw JSON."
)
print(f" [AI] Retrying with fallback {FALLBACK_MODEL}...")
raw_json2 = self._call_openrouter(
image_bytes, fix_prompt, model=FALLBACK_MODEL, max_retries=1
)
if raw_json2:
cabinets = self._parse_cabinet_json(raw_json2, elevation_label)
data = self._parse_cabinet_json(raw_json2, elevation_label)
if cabinets is None:
if data is None:
model_info = f"{PRIMARY_MODEL}" + ("" if use_demo else f" + {FALLBACK_MODEL}")
result.review_flags.append(f"Failed to parse AI JSON from {model_info}")
return result
# Populate result fields from parsed data
result.ceiling_height_in = data.get("ceiling_height_in")
result.soffit_present = bool(data.get("soffit_present", False))
result.backsplash = str(data.get("backsplash", ""))
result.counter_material = str(data.get("counter_material", ""))
result.appliances = data.get("appliances", [])
result.doors = data.get("doors", [])
result.windows = data.get("windows", [])
result.fillers = data.get("fillers", [])
result.panels = data.get("panels", [])
result.moldings = data.get("moldings", [])
result.relationships = data.get("relationships", [])
# Process cabinet list
cabinets = []
raw_cabs = data.get("cabinets", [])
if not isinstance(raw_cabs, list):
raw_cabs = []
for i, item in enumerate(raw_cabs, 1):
if not isinstance(item, dict):
continue
cab_type = item.get("cabinet_type", "unknown").lower().strip()
if cab_type not in VALID_CABINET_TYPES:
cab_type = _normalize_cabinet_type(cab_type)
width_mm = float(item.get("width_mm", 0) or 0)
height_mm = float(item.get("height_mm", 0) or 0)
depth_mm = float(item.get("depth_mm", 0) or 0)
# Apply standard defaults if missing
if height_mm == 0:
height_mm = _default_height(cab_type)
if depth_mm == 0:
depth_mm = _default_depth(cab_type)
confidence = float(item.get("confidence", 0.7))
confidence = max(0.0, min(1.0, confidence))
cabinets.append(CabinetItem(
item_num = item.get("item_num", i),
cabinet_type = cab_type,
width_mm = width_mm,
height_mm = height_mm,
depth_mm = depth_mm,
location = str(item.get("location", "")),
elevation_ref = item.get("elevation_ref", elevation_label),
confidence = confidence,
quantity = int(item.get("quantity", 1)),
is_ada = bool(item.get("is_ada", False)),
notes = str(item.get("notes", "")),
source = "gemini",
cabinet_id = str(item.get("cabinet_id", "")),
))
result.cabinets = cabinets
# Set auto-approve flag
@@ -438,12 +560,7 @@ class CabinetVisionClassifier:
max_retries: int = 3,
max_tokens: int = MAX_TOKENS,
) -> Optional[str]:
"""
Call OpenRouter vision API with any supported model.
Returns raw text response or None on failure.
"""
image_b64 = base64.standard_b64encode(image_bytes).decode("utf-8")
# Use compact system prompt if max_tokens budget is tight (demo mode)
use_demo_prompt = max_tokens <= DEMO_MAX_TOKENS
system_prompt = _build_system_prompt(demo=use_demo_prompt)
img_kb = len(image_bytes) / 1024
@@ -513,84 +630,50 @@ class CabinetVisionClassifier:
self,
raw_text: str,
elevation_label: str,
) -> Optional[list[CabinetItem]]:
) -> Optional[dict]:
"""
Parse JSON array from AI response.
Parse JSON object from AI response.
Handles: extra markdown fences, trailing commas, partial JSON.
"""
# Strip markdown code fences
text = raw_text.strip()
text = re.sub(r'^```(?:json)?\s*', '', text, flags=re.MULTILINE)
text = re.sub(r'\s*```\s*$', '', text, flags=re.MULTILINE)
text = text.strip()
# Find JSON array
start = text.find('[')
end = text.rfind(']')
# Find JSON object or array
start_obj = text.find('{')
start_arr = text.find('[')
if start_arr != -1 and (start_obj == -1 or start_arr < start_obj):
end_arr = text.rfind(']')
if end_arr != -1:
json_str = text[start_arr:end_arr+1]
json_str = re.sub(r',\s*([}\]])', r'\1', json_str) # trailing commas
try:
cabs = json.loads(json_str)
return {"cabinets": cabs}
except Exception as e:
# Fallback to object matching if array parse fails
pass
# Find JSON object
start = text.find('{')
end = text.rfind('}')
if start == -1 or end == -1:
# Try to find a JSON object
print(f" ⚠️ No JSON array found in response. Raw: {text[:200]}")
print(f" [WARN] No JSON object/array found in response. Raw text snippet: {text[:200]}")
return None
json_str = text[start:end+1]
# Fix common AI JSON mistakes
json_str = re.sub(r',\s*([}\]])', r'\1', json_str) # trailing commas
try:
data = json.loads(json_str)
return data
except json.JSONDecodeError as e:
print(f" ⚠️ JSON parse error: {e}")
print(f" [WARN] JSON parse error: {e}")
print(f" Raw snippet: {json_str[:300]}")
return None
if not isinstance(data, list):
print(f" ⚠️ Expected JSON array, got {type(data)}")
return None
cabinets = []
for i, item in enumerate(data, 1):
if not isinstance(item, dict):
continue
# Validate and normalize cabinet_type
cab_type = item.get("cabinet_type", "unknown").lower().strip()
if cab_type not in VALID_CABINET_TYPES:
# Try to map common variations
cab_type = _normalize_cabinet_type(cab_type)
width_mm = float(item.get("width_mm", 0) or 0)
height_mm = float(item.get("height_mm", 0) or 0)
depth_mm = float(item.get("depth_mm", 0) or 0)
# Apply standard defaults if missing
if height_mm == 0:
height_mm = _default_height(cab_type)
if depth_mm == 0:
depth_mm = _default_depth(cab_type)
confidence = float(item.get("confidence", 0.7))
confidence = max(0.0, min(1.0, confidence))
cabinets.append(CabinetItem(
item_num = item.get("item_num", i),
cabinet_type = cab_type,
width_mm = width_mm,
height_mm = height_mm,
depth_mm = depth_mm,
location = str(item.get("location", "")),
elevation_ref = item.get("elevation_ref", elevation_label),
confidence = confidence,
quantity = int(item.get("quantity", 1)),
is_ada = bool(item.get("is_ada", False)),
notes = str(item.get("notes", "")),
source = "gemini",
))
return cabinets
# (merge_results removed — single-model pipeline with Gemini)
# ══════════════════════════════════════════════════════════════════════════
# HELPERS
@@ -710,65 +793,111 @@ if __name__ == "__main__":
print("Testing JSON parser (no API key needed)...")
sample_response = """
```json
[
{
"item_num": 1,
"cabinet_type": "upper_wall",
"width_mm": 762,
"height_mm": 300,
"depth_mm": 330,
"location": "Left of range, Elevation A",
"elevation_ref": "ELEVATION A",
"confidence": 0.92,
"quantity": 1,
"is_ada": false,
"notes": ""
},
{
"item_num": 2,
"cabinet_type": "base",
"width_mm": 900,
"height_mm": 720,
"depth_mm": 600,
"location": "Sink base, Elevation A",
"elevation_ref": "ELEVATION A",
"confidence": 0.88,
"quantity": 1,
"is_ada": false,
"notes": "sink base cabinet"
},
{
"item_num": 3,
"cabinet_type": "appliance_space",
"width_mm": 610,
"height_mm": 720,
"depth_mm": 600,
"location": "Dishwasher slot",
"elevation_ref": "ELEVATION A",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "24\" dishwasher space — no cabinet"
}
]
```
{
"ceiling_height_in": 108,
"soffit_present": false,
"backsplash": "4\\\" backsplash",
"counter_material": "Quartz",
"cabinets": [
{
"item_num": 1,
"cabinet_type": "upper_wall",
"cabinet_id": "U10",
"width_mm": 762,
"height_mm": 300,
"depth_mm": 330,
"location": "Left of range, Elevation A",
"confidence": 0.92,
"quantity": 1,
"is_ada": false,
"notes": ""
},
{
"item_num": 2,
"cabinet_type": "base",
"cabinet_id": "U3",
"width_mm": 900,
"height_mm": 720,
"depth_mm": 600,
"location": "Sink base, Elevation A",
"confidence": 0.88,
"quantity": 1,
"is_ada": false,
"notes": "sink base cabinet"
}
],
"appliances": [
{
"type": "REF",
"width_in": 36,
"height_in": 70,
"x_in": 0,
"notes": "Refrigerator space"
}
],
"doors": [],
"windows": [],
"fillers": ["F3"],
"panels": ["EP24"],
"moldings": ["CM96"],
"relationships": [
{
"type": "above",
"item_a": "MIC",
"item_b": "RANGE",
"notes": "Microwave above range"
}
]
}
"""
# Test parsing (no API key needed for this test)
classifier = object.__new__(CabinetVisionClassifier) # skip __init__
classifier.__class__ = CabinetVisionClassifier
cabinets = classifier._parse_cabinet_json(sample_response, "ELEVATION A")
data = classifier._parse_cabinet_json(sample_response, "ELEVATION A")
if cabinets:
print(f"[PASS] Parsed {len(cabinets)} cabinets:")
if data:
print("[PASS] Parsed JSON successfully:")
print(f" Ceiling Height: {data.get('ceiling_height_in')} in")
print(f" Soffit: {data.get('soffit_present')}")
print(f" Backsplash: {data.get('backsplash')}")
print(f" Countertop: {data.get('counter_material')}")
print(f" Fillers: {data.get('fillers')}")
print(f" Panels: {data.get('panels')}")
print(f" Moldings: {data.get('moldings')}")
print(f" Relationships: {data.get('relationships')}")
# Test mapping to CabinetItem
cabinets = []
raw_cabs = data.get("cabinets", [])
for i, item in enumerate(raw_cabs, 1):
cab_type = item.get("cabinet_type", "unknown").lower().strip()
if cab_type not in VALID_CABINET_TYPES:
cab_type = _normalize_cabinet_type(cab_type)
cabinets.append(CabinetItem(
item_num = item.get("item_num", i),
cabinet_type = cab_type,
width_mm = float(item.get("width_mm", 0)),
height_mm = float(item.get("height_mm", 0)),
depth_mm = float(item.get("depth_mm", 0)),
location = str(item.get("location", "")),
elevation_ref = item.get("elevation_ref", "ELEVATION A"),
confidence = float(item.get("confidence", 0.7)),
quantity = int(item.get("quantity", 1)),
is_ada = bool(item.get("is_ada", False)),
notes = str(item.get("notes", "")),
source = "gemini",
cabinet_id = str(item.get("cabinet_id", "")),
))
for c in cabinets:
print(f" Item {c.item_num}: {c.cabinet_type:20s} {c.width_mm:.0f}mm "
f"confidence={c.confidence:.2f} code={c.code}")
f"confidence={c.confidence:.2f} code={c.code} id={c.cabinet_id}")
else:
print("[FAIL] Parsing failed")
# Test type normalization
print("\n=== Type Normalization ===")
for raw in ["wall cabinet", "lower", "dishwasher", "tall_cabinet", "mirror"]:
print(f" '{raw}' → '{_normalize_cabinet_type(raw)}'")
print(f" '{raw}' -> '{_normalize_cabinet_type(raw)}'")
@@ -0,0 +1,279 @@
"""
===========================================================================
core/cabinet_graph_builder.py — Spatial Layout Graph Builder
===========================================================================
Constructs the spatial layout graph of cabinets, appliances, and openings.
Calculates offsets, identifies adjacency, and builds the target schemas.
===========================================================================
"""
from __future__ import annotations
from typing import Any, Dict, List, Optional
from core.ai_vision_classifier import CabinetItem, ElevationResult
class CabinetGraphBuilder:
"""
Constructs spatial relationship graphs from elevation classification results
and builds the standard deliverables.
"""
def __init__(self):
pass
def build_shop_drawing_schema(
self,
unit_type: str,
elevations: list[ElevationResult],
kitchen_type: str,
bathroom_type: str,
layout_shape: str = "straight"
) -> dict:
"""
Builds the shop drawing JSON schema.
"""
walls_list = []
appliances_list = []
ceiling_height = 108.0
for ev in elevations:
# Standardize wall label name from elevation label
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
# If the label is KITCHEN or BATH, use a friendly shorthand
if wall_name.upper() in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
wall_name = "A"
# Parse ceiling height if reported
if ev.ceiling_height_in is not None:
ceiling_height = ev.ceiling_height_in
# Build wall info
# 1. Base run sequence
# Standardize cabinet items
base_items = []
upper_items = []
for cab in ev.cabinets:
# convert width_mm to inches
w_in = round(cab.width_mm / 25.4)
h_in = round(cab.height_mm / 25.4)
d_in = round(cab.depth_mm / 25.4)
cid = cab.cabinet_id or cab.code
cab_dict = {
"id": cid,
"type": cab.cabinet_type,
"width": w_in,
"height": h_in,
"depth": d_in,
"cabinet_type": cab.cabinet_type,
"notes": cab.notes,
"is_ada": cab.is_ada
}
if cab.cabinet_type in ("upper_wall", "microwave_shelf", "corner_upper", "medicine_cabinet"):
upper_items.append(cab_dict)
else:
base_items.append(cab_dict)
# Sequence base run
base_x = 0
sequenced_base_cabs = []
for b in base_items:
b["x"] = base_x
sequenced_base_cabs.append(b)
# If it's an appliance space, also add it 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():
app_type = t
break
appliances_list.append({
"type": app_type,
"wall": wall_name,
"x": base_x,
"width": b["width"]
})
base_x += b["width"]
# Sequence upper run
upper_x = 0
sequenced_upper_cabs = []
for u in upper_items:
u["x"] = upper_x
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"]
})
# Process openings
doors_output = []
for d in ev.doors:
doors_output.append({
"x": d.get("x_in", 0),
"width": d.get("width_in", 36),
"height": d.get("height_in", 80)
})
windows_output = []
for w in ev.windows:
windows_output.append({
"x": w.get("x_in", 0),
"width": w.get("width_in", 36),
"height": w.get("height_in", 48),
"sill_height": w.get("sill_height_in", 36)
})
wall_length = max(base_x, upper_x)
if wall_length == 0:
wall_length = 90.0 # default wall length
walls_list.append({
"name": wall_name,
"length": wall_length,
"doors": doors_output,
"windows": windows_output,
"cabinets": all_cabs_output
})
# Try to parse appliances list directly from elevations if none added from base run
if not appliances_list:
for ev in elevations:
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
if wall_name.upper() in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
wall_name = "A"
for app in ev.appliances:
appliances_list.append({
"type": app.get("type", "REF"),
"wall": wall_name,
"x": app.get("x_in", 0),
"width": app.get("width_in", 36)
})
# Normalize layout shape
layout_map = {
"K1": "single_wall",
"K2": "l_shape",
"K3": "galley"
}
layout_name = layout_map.get(kitchen_type, layout_shape.lower())
return {
"unit": unit_type,
"kitchen_type": kitchen_type,
"layout": layout_name,
"ceiling_height": ceiling_height,
"walls": walls_list,
"appliances": appliances_list
}
def build_cost_schema(
self,
unit_type: str,
elevations: list[ElevationResult],
is_ada: bool = False
) -> dict:
"""
Builds the cost estimation JSON schema.
"""
cabinets_summary = {}
fillers = []
panels = []
moldings = []
special_items = []
countertop_in = 0.0
upper_cabinet_in = 0.0
pantry_count = 0
has_island = False
for ev in elevations:
# Aggregate cabinets count
for cab in ev.cabinets:
w_in = round(cab.width_mm / 25.4)
cid = cab.cabinet_id or cab.code
# Check for special properties
if cab.cabinet_type == "pantry":
pantry_count += 1
if "island" in cab.location.lower() or "island" in cab.notes.lower():
has_island = True
# Skip appliance spaces and fillers in primary cabinet list
if cab.cabinet_type == "appliance_space":
continue
if cab.cabinet_type == "filler":
# track filler keynotes (e.g. F3)
fillers.append(cid)
continue
cabinets_summary[cid] = cabinets_summary.get(cid, 0) + cab.quantity
# Calculate linear feet dimensions
if cab.cabinet_type in ("upper_wall", "microwave_shelf", "corner_upper"):
upper_cabinet_in += w_in * cab.quantity
elif cab.cabinet_type in ("base", "sink_base", "dw_adjacent", "vanity"):
countertop_in += w_in * cab.quantity
# Gather other filler/panel/molding lists from elevation metadata
for f in ev.fillers:
if f not in fillers:
fillers.append(f)
for p in ev.panels:
if p not in panels:
panels.append(p)
for m in ev.moldings:
if m not in moldings:
moldings.append(m)
# Build final cabinet list format
cabinets_list = [
{"code": code, "qty": qty}
for code, qty in sorted(cabinets_summary.items())
]
# Calculate linear feet (inches / 12)
countertop_lf = round(countertop_in / 12.0, 1)
upper_cabinet_lf = round(upper_cabinet_in / 12.0, 1)
# Detect special items
if is_ada:
special_items.append("ADA")
if pantry_count > 0:
special_items.append("Pantry")
if has_island:
special_items.append("Island")
# Determine installation complexity
total_boxes = sum(c["qty"] for c in cabinets_list)
if has_island or (pantry_count > 0 and is_ada) or total_boxes > 15:
complexity = "high"
elif total_boxes >= 8 or is_ada:
complexity = "medium"
else:
complexity = "low"
return {
"unit_type": unit_type,
"cabinets": cabinets_list,
"countertop_lf": countertop_lf,
"upper_cabinet_lf": upper_cabinet_lf,
"fillers": fillers,
"panels": panels,
"moldings": moldings,
"special_items": special_items,
"installation_complexity": complexity
}
@@ -0,0 +1,75 @@
"""
===========================================================================
core/ceiling_height_extractor.py — Ceiling & Soffit Height Extractor
===========================================================================
Parses drawing annotations for ceiling heights and dropped bulkheads.
===========================================================================
"""
from __future__ import annotations
import re
from typing import Optional, List, Dict
from core.pdf_extractor import TextSpan
class CeilingHeightExtractor:
"""
Parses ceiling elevations and soffit bounds from details annotations.
"""
@staticmethod
def extract_heights(spans: list[TextSpan]) -> dict:
"""
Scan page text spans and extract ceiling_height and soffit_height.
Returns values in inches (default: ceiling=108, soffit=None).
"""
ceiling_height = 108.0 # default 9'
soffit_height = None
# Sort spans top-to-bottom, left-to-right
sorted_spans = sorted(spans, key=lambda s: (s.y0, s.x0))
for idx, s in enumerate(sorted_spans):
t = s.text.upper()
# Look for ceiling keywords: CEILING, CLG, AFF
if "CEILING" in t or "CLG" in t or "AFF" in t or "SOFFIT" in t:
# Search nearby spans (prev/next 5 spans) for height matches
search_range = sorted_spans[max(0, idx-5):min(len(sorted_spans), idx+6)]
for neighbor in search_range:
nt = neighbor.text.upper()
height_in = CeilingHeightExtractor._parse_height(nt)
if height_in is not None:
if "SOFFIT" in t or "SOFFIT" in nt:
soffit_height = height_in
else:
ceiling_height = height_in
break
return {
"ceiling_height": ceiling_height,
"soffit_height": soffit_height or (ceiling_height - 12.0 if soffit_height is None else soffit_height)
}
@staticmethod
def _parse_height(text: str) -> Optional[float]:
"""
Helper to parse height specs e.g. 9'-0" clg or 8'-6" AFF to inches.
"""
# Match 9'-0" or 9'0" or 9'-6"
m_ft_in = re.search(r"(\d+)'\s*-?\s*(\d+)?\"?", text)
if m_ft_in:
ft = float(m_ft_in.group(1))
inch_val = float(m_ft_in.group(2)) if m_ft_in.group(2) else 0.0
return ft * 12 + inch_val
# Match 108" or 96 in
m_in = re.search(r"(\d+)\s*(?:\"|IN|INCHES)", text, re.IGNORECASE)
if m_in:
return float(m_in.group(1))
# Match 9 FT or 9FT
m_ft = re.search(r"(\d+)\s*(?:FT|FEET)", text, re.IGNORECASE)
if m_ft:
return float(m_ft.group(1)) * 12.0
return None
+68
View File
@@ -0,0 +1,68 @@
"""
===========================================================================
core/confidence_engine.py — QA Confidence Engine
===========================================================================
Runs rule-based validation checks on extracted metadata models to calculate
overall QA score and list warning items.
===========================================================================
"""
from __future__ import annotations
from typing import List, Dict, Any
from core.ai_vision_classifier import CabinetItem, ElevationResult
class ConfidenceEngine:
"""
Computes quality metrics and reports warning flags on takeoff outcomes.
"""
@staticmethod
def evaluate(elevation: ElevationResult) -> dict:
"""
Runs checks and returns:
{
"confidence_score": 0.85,
"needs_review": False,
"warnings": []
}
"""
warnings = []
cabinets = elevation.cabinets
# 1. Base confidence
base_confidence = elevation.avg_confidence if cabinets else 1.0
# 2. Check: Duplicate keynote ID
ids = [c.cabinet_id for c in cabinets if c.cabinet_id]
if len(ids) != len(set(ids)):
warnings.append("Duplicate keynote ID detected in same elevation run")
base_confidence -= 0.1
# 3. Check: Base/Upper alignment
base_count = sum(1 for c in cabinets if c.cabinet_type in ("base", "sink_base", "dw_adjacent"))
upper_count = sum(1 for c in cabinets if c.cabinet_type in ("upper_wall", "microwave_shelf"))
if base_count == 0 and upper_count > 0:
warnings.append("Elevation has upper cabinets but no matching base run support")
base_confidence -= 0.15
# 4. Check: ADA constraints
if elevation.is_ada:
for cab in cabinets:
if cab.cabinet_type in ("base", "sink_base", "vanity") and cab.height_mm > 864:
warnings.append(f"ADA Unit contains cabinet {cab.code} exceeding 864mm height limit")
base_confidence -= 0.1
# 5. Check: Sink/Range matching
sink_count = sum(1 for c in cabinets if c.cabinet_type == "sink_base")
if sink_count > 1:
warnings.append("Multiple sink base cabinets found in single run")
base_confidence -= 0.05
final_score = max(0.0, min(1.0, base_confidence))
needs_review = final_score < 0.80 or len(warnings) > 0
return {
"confidence_score": round(final_score, 2),
"needs_review": needs_review,
"warnings": warnings
}
+57
View File
@@ -0,0 +1,57 @@
"""
===========================================================================
core/drawing_classifier.py — Stage 0 Drawing Sheet Page Classifier
===========================================================================
Analyzes text spans on a drawing page to classify it into:
- FLOOR PLAN
- UNIT PLAN
- ELEVATION
- RCP
- DETAIL
- SECTION
===========================================================================
"""
from __future__ import annotations
import re
from typing import List, Any
from core.pdf_extractor import TextSpan
class DrawingClassifier:
"""
Classifies drawings based on text tokens and layout annotations.
"""
@staticmethod
def classify_page(spans: list[TextSpan]) -> str:
"""
Classifies page text content into drawing type labels.
"""
text_content = " ".join(s.text.upper() for s in spans)
# 1. RCP Check (Reflected Ceiling Plan)
if "RCP" in text_content or "REFLECTED CEILING" in text_content:
return "RCP"
# 2. Elevation Check
if "ELEVATION" in text_content or "INT. ELEV" in text_content:
return "ELEVATION"
# 3. Unit Plan Details Check
if "UNIT PLAN" in text_content or "UNIT A" in text_content or "UNIT B" in text_content or "UNIT D" in text_content or "UNIT ST" in text_content or "ENLARGED PLAN" in text_content:
return "UNIT PLAN"
# 4. Overall Floor Plan Check
if "FLOOR PLAN" in text_content or "GROUND LEVEL" in text_content or "LEVEL PLAN" in text_content or "OVERALL PLAN" in text_content:
return "FLOOR PLAN"
# 5. Section Check
if "BUILDING SECTION" in text_content or "WALL SECTION" in text_content:
return "SECTION"
# 6. Detail Check
if "DETAIL" in text_content or "SECTION" in text_content or "MOUNTING" in text_content:
return "DETAIL"
# Fallback
return "UNIT PLAN" # Most details pages are unit plan/elevations
+813
View File
@@ -0,0 +1,813 @@
"""
===========================================================================
core/geometry_engine.py — High-Fidelity 2D CAD Layouts Engine
===========================================================================
Translates sequenced cabinets, appliances, and openings into detailed
architectural 2D lines, dimensions, texts, and swing annotations.
===========================================================================
"""
from __future__ import annotations
import math
from typing import List, Dict, Any, Optional
from fractions import Fraction
class GeometryEngine:
"""
Builds plan views and detailed elevation views coordinates.
All dimensions inside this engine use inches.
"""
def __init__(self):
# Coordinates offsets inside GeometryEngine space
self.GE_PLAN_OX = 250.0
self.GE_PLAN_OY = 450.0
self.GE_ELEV_OX = 250.0
self.GE_ELEV_OY = 150.0
self.GE_SIDE_OX = 250.0
self.GE_SIDE_OY = 150.0
def _make_double_dim(self, inches: float) -> str:
"""Helper to format inches to Metric [Imperial] format (e.g. 76.20 [2'-6"])."""
if inches <= 0.01:
return ""
# Convert inches to cm
cm = inches * 2.54
# Convert inches to feet and remainder inches
feet = int(inches // 12)
rem_inches = inches % 12
# Round remainder inches to nearest 1/16
rounded_rem = round(rem_inches * 16) / 16
# Format imperial part
if feet > 0:
whole_in = int(rounded_rem)
frac = rounded_rem - whole_in
if frac < 0.01:
imp_str = f"{feet}'-{whole_in}\"" if whole_in > 0 else f"{feet}'"
else:
frac_str = str(Fraction(frac))
imp_str = f"{feet}'-{whole_in} {frac_str}\"" if whole_in > 0 else f"{feet}'-{frac_str}\""
else:
whole_in = int(rounded_rem)
frac = rounded_rem - whole_in
if frac < 0.01:
imp_str = f"{whole_in}\""
else:
frac_str = str(Fraction(frac))
imp_str = f"{whole_in} {frac_str}\"" if whole_in > 0 else f"{frac_str}\""
return f"{cm:.2f} [{imp_str}]"
def generate_layout_geometry(
self,
walls: list[dict],
appliances: list[dict],
ceiling_height: float = 108.0,
soffit_height: float = 96.0
) -> dict:
"""
Processes wall runs to generate plan and elevation geometries.
Returns:
{
"plan": { "lines": [], "dimensions": [], "blocks": [], "texts": [] },
"elevation": { "lines": [], "dimensions": [], "blocks": [], "texts": [] }
}
"""
plan_geom = {"lines": [], "dimensions": [], "blocks": [], "texts": []}
elev_geom = {"lines": [], "dimensions": [], "blocks": [], "texts": []}
side_geom = {"lines": [], "dimensions": [], "blocks": [], "texts": []}
# Origin offsets
plan_ox = self.GE_PLAN_OX
plan_oy = self.GE_PLAN_OY
elev_ox = self.GE_ELEV_OX
elev_oy = self.GE_ELEV_OY
side_ox = self.GE_SIDE_OX
side_oy = self.GE_SIDE_OY
for w_idx, wall in enumerate(walls):
wall_name = wall.get("name", "A")
wall_length = wall.get("length", 90.0)
cabinets = wall.get("cabinets", [])
if w_idx > 0:
prev_length = walls[w_idx - 1].get("length", 90.0)
offset_x = (prev_length * 4.0) + 100.0
plan_ox += offset_x
elev_ox += offset_x
side_ox += offset_x
# --- Plan View Construction ---
# 1. Back wall line and solid thick wall + hatch pattern (6" depth)
plan_geom["lines"].append({
"start": [plan_ox, plan_oy],
"end": [plan_ox + wall_length * 4.0, plan_oy],
"layer": "WALLS",
"style": "solid"
})
plan_geom["lines"].append({
"start": [plan_ox, plan_oy + 6.0 * 4.0],
"end": [plan_ox + wall_length * 4.0, plan_oy + 6.0 * 4.0],
"layer": "WALLS",
"style": "solid"
})
# Draw cross-hatches in wall cut
for hx in range(0, int(wall_length), 4):
plan_geom["lines"].append({
"start": [plan_ox + hx * 4.0, plan_oy],
"end": [plan_ox + (hx + 4) * 4.0, plan_oy + 6.0 * 4.0],
"layer": "WALLS_HATCH",
"style": "solid"
})
# 2. Countertop boundary (25" depth standard)
ct_d = 25.0
plan_geom["lines"].append({
"start": [plan_ox, plan_oy - ct_d * 4.0],
"end": [plan_ox + wall_length * 4.0, plan_oy - ct_d * 4.0],
"layer": "COUNTERTOP",
"style": "solid"
})
# Double line for front edge lip
plan_geom["lines"].append({
"start": [plan_ox, plan_oy - (ct_d - 1.0) * 4.0],
"end": [plan_ox + wall_length * 4.0, plan_oy - (ct_d - 1.0) * 4.0],
"layer": "COUNTERTOP",
"style": "solid"
})
# 3. Draw cabinets in Plan
for cab in cabinets:
cab_x = cab.get("x", 0.0)
cab_w = cab.get("width", 12.0)
cab_id = cab.get("id", "CAB")
cab_type = cab.get("cabinet_type", cab.get("type", "")).lower()
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() or "ref" in cab_id.lower()
is_dw = "dw" in cab_type or "dishwasher" in cab_id.lower() or "dw" in cab_id.lower()
depth = 12.0 if is_upper else (30.0 if is_ref else 24.0)
layer = "CABINETS_UPPER" if is_upper else "CABINETS_BASE"
style = "dashed" if is_upper else "solid"
# Cabinet box
x0 = plan_ox + cab_x * 4.0
x1 = x0 + cab_w * 4.0
y0 = plan_oy
y1 = plan_oy - depth * 4.0
plan_geom["blocks"].append({
"type": "rect",
"coords": [x0, y1, x1 - x0, y0 - y1],
"id": cab_id,
"layer": layer,
"style": style
})
# Visual Details
if is_sink:
# Draw double sink bowl
sw = (cab_w - 6.0) * 4.0
sd = 15.0 * 4.0
sx0 = x0 + 3.0 * 4.0
sy0 = plan_oy - 4.0 * 4.0
# Outer bowl
plan_geom["blocks"].append({
"type": "rect",
"coords": [sx0, sy0 - sd, sw, sd],
"id": "",
"layer": "SINK",
"style": "solid"
})
# Double bowl separator
plan_geom["lines"].append({
"start": [sx0 + sw/2, sy0],
"end": [sx0 + sw/2, sy0 - sd],
"layer": "SINK",
"style": "solid"
})
# Faucet point
plan_geom["lines"].append({
"start": [sx0 + sw/2, sy0 + 1.0 * 4.0],
"end": [sx0 + sw/2, sy0 - 2.0 * 4.0],
"layer": "SINK",
"style": "solid"
})
elif is_range:
# Draw 4 circles for cooktop burners
r_burner = 2.5 * 4.0
cx1 = x0 + (cab_w / 4.0) * 4.0
cx2 = x0 + (cab_w * 3.0 / 4.0) * 4.0
cy1 = plan_oy - 7.0 * 4.0
cy2 = plan_oy - 17.0 * 4.0
for cx, cy in [(cx1, cy1), (cx1, cy2), (cx2, cy1), (cx2, cy2)]:
# Represent circle via cross lines for standard compatibility
plan_geom["lines"].append({
"start": [cx - r_burner, cy], "end": [cx + r_burner, cy],
"layer": "BURNERS", "style": "solid"
})
plan_geom["lines"].append({
"start": [cx, cy - r_burner], "end": [cx, cy + r_burner],
"layer": "BURNERS", "style": "solid"
})
elif is_ref:
# Draw refrigerator handles on the front edge
plan_geom["lines"].append({
"start": [x0 + 4.0, y1],
"end": [x1 - 4.0, y1],
"layer": "APPLIANCES",
"style": "solid"
})
plan_geom["texts"].append({
"pos": [(x0 + x1) / 2, (y0 + y1) / 2],
"text": "REFRIGERATOR",
"size": 4.5,
"layer": "TEXT"
})
elif is_dw:
plan_geom["texts"].append({
"pos": [(x0 + x1) / 2, (y0 + y1) / 2],
"text": "DISHWASHER",
"size": 4.5,
"layer": "TEXT"
})
# Dimension labels inside boxes
if not is_ref and not is_dw:
plan_geom["texts"].append({
"pos": [(x0 + x1) / 2, (y0 + y1) / 2 - 2.0],
"text": f"{cab_id}\n{cab_w}\"",
"size": 4.0,
"layer": layer
})
# Running dimension string at top of plan
plan_geom["dimensions"].append({
"start": [plan_ox, plan_oy + 14.0 * 4.0],
"end": [plan_ox + wall_length * 4.0, plan_oy + 14.0 * 4.0],
"text": self._make_double_dim(wall_length)
})
# --- Elevation View Construction ---
# 1. Ground floor line
elev_geom["lines"].append({
"start": [elev_ox - 10.0, elev_oy],
"end": [elev_ox + wall_length * 4.0 + 10.0, elev_oy],
"layer": "GROUND",
"style": "solid"
})
# 2. Toe kick line (4" height AFF)
elev_geom["lines"].append({
"start": [elev_ox, elev_oy + 4.0 * 3.0],
"end": [elev_ox + wall_length * 4.0, elev_oy + 4.0 * 3.0],
"layer": "CABINETS_BASE",
"style": "solid"
})
# 3. Countertop lines (34.5" to 36.0" AFF)
elev_geom["lines"].append({
"start": [elev_ox, elev_oy + 34.5 * 3.0],
"end": [elev_ox + wall_length * 4.0, elev_oy + 34.5 * 3.0],
"layer": "COUNTERTOP",
"style": "solid"
})
elev_geom["lines"].append({
"start": [elev_ox, elev_oy + 36.0 * 3.0],
"end": [elev_ox + wall_length * 4.0, elev_oy + 36.0 * 3.0],
"layer": "COUNTERTOP",
"style": "solid"
})
# 4. Ceiling line
elev_geom["lines"].append({
"start": [elev_ox - 10.0, elev_oy + ceiling_height * 3.0],
"end": [elev_ox + wall_length * 4.0 + 10.0, elev_oy + ceiling_height * 3.0],
"layer": "CEILING",
"style": "solid"
})
# 5. Draw cabinets in Elevation
for cab in cabinets:
cab_x = cab.get("x", 0.0)
cab_w = cab.get("width", 12.0)
cab_h = cab.get("height", 30.0)
cab_id = cab.get("id", "CAB")
cab_type = cab.get("cabinet_type", cab.get("type", "")).lower()
is_upper = cab_id.upper().startswith("W") or "upper" in cab_type
is_pantry = cab_id.upper().startswith("T") or "pantry" 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() 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_drawer = "dwr" in cab_id.lower() or "drawer" in cab_type or "drawers" in cab.get("notes", "").lower()
# Coordinate height offsets
if is_pantry:
y0 = elev_oy + 4.0 * 3.0
y1 = elev_oy + cab_h * 3.0
elif is_upper:
y0 = elev_oy + 54.0 * 3.0
y1 = y0 + cab_h * 3.0
else:
# standard base cabinet starts above 4" toe kick, ends at 34.5" box height
y0 = elev_oy + 4.0 * 3.0
y1 = elev_oy + 34.5 * 3.0
x0 = elev_ox + cab_x * 4.0
x1 = x0 + cab_w * 4.0
if is_ref:
# Refrigerator stands on floor and goes up to 72" AFF typically
y0_ref = elev_oy
y1_ref = elev_oy + 72.0 * 3.0
elev_geom["blocks"].append({
"type": "rect",
"coords": [x0, y0_ref, x1 - x0, y1_ref - y0_ref],
"id": cab_id,
"layer": "APPLIANCES",
"style": "solid"
})
# Refrigerator doors dividing vertical line
elev_geom["lines"].append({
"start": [x0 + (x1 - x0)/2, y0_ref],
"end": [x0 + (x1 - x0)/2, y1_ref],
"layer": "APPLIANCES",
"style": "solid"
})
# Refrigerator handles
elev_geom["lines"].append({
"start": [x0 + (x1 - x0)/2 - 1.5, y0_ref + 30.0 * 3.0],
"end": [x0 + (x1 - x0)/2 - 1.5, y0_ref + 48.0 * 3.0],
"layer": "APPLIANCES",
"style": "solid"
})
elev_geom["lines"].append({
"start": [x0 + (x1 - x0)/2 + 1.5, y0_ref + 30.0 * 3.0],
"end": [x0 + (x1 - x0)/2 + 1.5, y0_ref + 48.0 * 3.0],
"layer": "APPLIANCES",
"style": "solid"
})
elev_geom["texts"].append({
"pos": [(x0 + x1) / 2, (y0_ref + y1_ref) / 2],
"text": f"REFRIGERATOR\n{cab_w}\"W",
"size": 4.5,
"layer": "TEXT"
})
elif is_dw:
# Dishwasher front panel
elev_geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": "D/W",
"layer": "APPLIANCES",
"style": "solid"
})
# Control panel line at top of D/W
elev_geom["lines"].append({
"start": [x0, y1 - 4.0 * 3.0],
"end": [x1, y1 - 4.0 * 3.0],
"layer": "APPLIANCES",
"style": "solid"
})
elev_geom["texts"].append({
"pos": [(x0 + x1) / 2, (y0 + y1) / 2],
"text": f"D/W\n{cab_w}\"W",
"size": 4.5,
"layer": "TEXT"
})
elif is_range:
# Cooktop / Range stove
# Draw stove box standing on ground Y=0, ending at Y=36 (counter level)
y1_stove = elev_oy + 36.0 * 3.0
elev_geom["blocks"].append({
"type": "rect",
"coords": [x0, elev_oy, x1 - x0, y1_stove - elev_oy],
"id": "STOVE",
"layer": "APPLIANCES",
"style": "solid"
})
# Oven glass window
elev_geom["blocks"].append({
"type": "rect",
"coords": [x0 + 4.0, elev_oy + 8.0 * 3.0, (cab_w - 8.0) * 4.0, 14.0 * 3.0],
"id": "",
"layer": "APPLIANCES",
"style": "solid"
})
# Dials/control panel line at top
elev_geom["lines"].append({
"start": [x0, y1_stove - 3.0 * 3.0],
"end": [x1, y1_stove - 3.0 * 3.0],
"layer": "APPLIANCES",
"style": "solid"
})
elev_geom["texts"].append({
"pos": [(x0 + x1) / 2, y1_stove - 1.5 * 3.0],
"text": "RANGE",
"size": 4.5,
"layer": "TEXT"
})
elif is_drawer:
# Draw 3-drawer layout
elev_geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": cab_id,
"layer": "CABINETS_BASE",
"style": "solid"
})
# Draw horizontal dividers
dy1 = y0 + 7.0 * 3.0
dy2 = y0 + 17.0 * 3.0
elev_geom["lines"].append({
"start": [x0, dy1], "end": [x1, dy1],
"layer": "CABINETS_BASE", "style": "solid"
})
elev_geom["lines"].append({
"start": [x0, dy2], "end": [x1, dy2],
"layer": "CABINETS_BASE", "style": "solid"
})
# Draw drawer handles
for h_y in [(y0 + dy1)/2, (dy1 + dy2)/2, (dy2 + y1)/2]:
elev_geom["lines"].append({
"start": [(x0 + x1)/2 - 3.0, h_y],
"end": [(x0 + x1)/2 + 3.0, h_y],
"layer": "HANDLES",
"style": "solid"
})
else:
# Standard Cabinet Box
layer = "CABINETS_UPPER" if is_upper else "CABINETS_BASE"
elev_geom["blocks"].append({
"type": "rect",
"coords": [x0, y0, x1 - x0, y1 - y0],
"id": cab_id,
"layer": layer,
"style": "solid"
})
# Door divides and swing indicators (triangle dashes)
if cab_w > 21.0:
# Double door divide
xm = (x0 + x1) / 2
elev_geom["lines"].append({
"start": [xm, y0],
"end": [xm, y1],
"layer": layer,
"style": "solid"
})
# Left door swing triangle
elev_geom["lines"].append({
"start": [x0, y0], "end": [xm, (y0 + y1) / 2],
"layer": "SWING", "style": "dashed"
})
elev_geom["lines"].append({
"start": [x0, y1], "end": [xm, (y0 + y1) / 2],
"layer": "SWING", "style": "dashed"
})
# Right door swing triangle
elev_geom["lines"].append({
"start": [x1, y0], "end": [xm, (y0 + y1) / 2],
"layer": "SWING", "style": "dashed"
})
elev_geom["lines"].append({
"start": [x1, y1], "end": [xm, (y0 + y1) / 2],
"layer": "SWING", "style": "dashed"
})
# Handles in the center
elev_geom["lines"].append({
"start": [xm - 1.0, (y0 + y1)/2 - 3.0],
"end": [xm - 1.0, (y0 + y1)/2 + 3.0],
"layer": "HANDLES", "style": "solid"
})
elev_geom["lines"].append({
"start": [xm + 1.0, (y0 + y1)/2 - 3.0],
"end": [xm + 1.0, (y0 + y1)/2 + 3.0],
"layer": "HANDLES", "style": "solid"
})
else:
# Single door swing (left hinged hinge swing lines)
elev_geom["lines"].append({
"start": [x0, y0], "end": [x1, (y0 + y1) / 2],
"layer": "SWING", "style": "dashed"
})
elev_geom["lines"].append({
"start": [x0, y1], "end": [x1, (y0 + y1) / 2],
"layer": "SWING", "style": "dashed"
})
# Handle on the right side
elev_geom["lines"].append({
"start": [x1 - 1.5, (y0 + y1)/2 - 3.0],
"end": [x1 - 1.5, (y0 + y1)/2 + 3.0],
"layer": "HANDLES", "style": "solid"
})
# Label
elev_geom["texts"].append({
"pos": [(x0 + x1) / 2, (y0 + y1) / 2],
"text": f"{cab_id}\n{cab_w}\"x{cab_h}\"",
"size": 4.0,
"layer": "TEXT"
})
# Dimension markers at bottom of cabinet box
elev_geom["dimensions"].append({
"start": [x0, elev_oy - 10.0],
"end": [x1, elev_oy - 10.0],
"text": self._make_double_dim(cab_w)
})
# Running horizontal dimensions at top of elevation view
elev_geom["dimensions"].append({
"start": [elev_ox, elev_oy + (ceiling_height + 10.0) * 3.0],
"end": [elev_ox + wall_length * 4.0, elev_oy + (ceiling_height + 10.0) * 3.0],
"text": self._make_double_dim(wall_length)
})
# Vertical dimensions on the left of elevation
v_dims = [
(0.0, 4.0, "4\""),
(4.0, 34.5, "30.5\""),
(34.5, 36.0, "1.5\""),
(36.0, 54.0, "18\""),
(54.0, 54.0 + 30.0, "30\""), # assuming standard 30" upper
(0.0, ceiling_height, f"{ceiling_height:.0f}\" clg")
]
for start_aff, end_aff, dim_txt in v_dims:
elev_geom["dimensions"].append({
"start": [elev_ox - 24.0, elev_oy + start_aff * 3.0],
"end": [elev_ox - 24.0, elev_oy + end_aff * 3.0],
"text": dim_txt
})
# --- Side View (Section) Construction ---
# 1. Ground line (floor)
side_geom["lines"].append({
"start": [side_ox - 5.0 * 4.0, side_oy],
"end": [side_ox + 35.0 * 4.0, side_oy],
"layer": "GROUND",
"style": "solid"
})
# 2. Back wall line
side_geom["lines"].append({
"start": [side_ox, side_oy],
"end": [side_ox, side_oy + ceiling_height * 3.0],
"layer": "WALLS",
"style": "solid"
})
# Draw standard wall hatching on the left of the wall (e.g. from X=-6" to X=0)
side_geom["lines"].append({
"start": [side_ox - 6.0 * 4.0, side_oy],
"end": [side_ox - 6.0 * 4.0, side_oy + ceiling_height * 3.0],
"layer": "WALLS",
"style": "solid"
})
for hx in range(0, int(ceiling_height), 12):
side_geom["lines"].append({
"start": [side_ox - 6.0 * 4.0, side_oy + hx * 3.0],
"end": [side_ox, side_oy + (hx + 8) * 3.0],
"layer": "WALLS_HATCH",
"style": "solid"
})
# 3. Ceiling line
side_geom["lines"].append({
"start": [side_ox - 5.0 * 4.0, side_oy + ceiling_height * 3.0],
"end": [side_ox + 35.0 * 4.0, side_oy + ceiling_height * 3.0],
"layer": "CEILING",
"style": "solid"
})
# 4. Check what cabinet types are on this wall
has_base = False
has_upper = False
has_pantry = False
has_vanity = False
base_h = 34.5
upper_h = 30.0
pantry_h = 84.0
vanity_h = 34.5
for cab in cabinets:
cab_id = cab.get("id", "").upper()
cab_type = cab.get("type", "").lower() or cab.get("cabinet_type", "").lower()
is_upper = cab_id.startswith("W") or "upper" in cab_type
is_pantry = cab_id.startswith("T") or "pantry" in cab_type
is_vanity = cab_id.startswith("VAN") or "vanity" in cab_type
if is_pantry:
has_pantry = True
pantry_h = max(pantry_h, cab.get("height", 84.0))
elif is_upper:
has_upper = True
upper_h = max(upper_h, cab.get("height", 30.0))
elif is_vanity:
has_vanity = True
vanity_h = max(vanity_h, cab.get("height", 34.5))
else:
has_base = True
base_h = max(base_h, cab.get("height", 34.5))
# 5. Draw base cabinet or vanity section
if has_vanity:
van_d = 21.0
# Draw vanity outline
side_geom["blocks"].append({
"type": "rect",
"coords": [side_ox, side_oy + 4.0 * 3.0, van_d * 4.0, (vanity_h - 4.0) * 3.0],
"id": "",
"layer": "CABINETS_BASE",
"style": "solid"
})
# Toe kick (3" deep, 4" high)
side_geom["lines"].append({
"start": [side_ox + (van_d - 3.0) * 4.0, side_oy],
"end": [side_ox + (van_d - 3.0) * 4.0, side_oy + 4.0 * 3.0],
"layer": "CABINETS_BASE",
"style": "solid"
})
side_geom["lines"].append({
"start": [side_ox + (van_d - 3.0) * 4.0, side_oy + 4.0 * 3.0],
"end": [side_ox + van_d * 4.0, side_oy + 4.0 * 3.0],
"layer": "CABINETS_BASE",
"style": "solid"
})
# Countertop (22" deep, 1.5" thickness)
side_geom["blocks"].append({
"type": "rect",
"coords": [side_ox, side_oy + vanity_h * 3.0, (van_d + 1.0) * 4.0, 1.5 * 3.0],
"id": "",
"layer": "COUNTERTOP",
"style": "solid"
})
# Backsplash
side_geom["blocks"].append({
"type": "rect",
"coords": [side_ox, side_oy + (vanity_h + 1.5) * 3.0, 0.75 * 4.0, 4.0 * 3.0],
"id": "",
"layer": "COUNTERTOP",
"style": "solid"
})
elif has_base:
base_d = 24.0
# Draw base outline
side_geom["blocks"].append({
"type": "rect",
"coords": [side_ox, side_oy + 4.0 * 3.0, base_d * 4.0, (base_h - 4.0) * 3.0],
"id": "",
"layer": "CABINETS_BASE",
"style": "solid"
})
# Toe kick (3" deep, 4" high)
side_geom["lines"].append({
"start": [side_ox + (base_d - 3.0) * 4.0, side_oy],
"end": [side_ox + (base_d - 3.0) * 4.0, side_oy + 4.0 * 3.0],
"layer": "CABINETS_BASE",
"style": "solid"
})
side_geom["lines"].append({
"start": [side_ox + (base_d - 3.0) * 4.0, side_oy + 4.0 * 3.0],
"end": [side_ox + base_d * 4.0, side_oy + 4.0 * 3.0],
"layer": "CABINETS_BASE",
"style": "solid"
})
# Countertop (25" deep, 1.5" thickness)
side_geom["blocks"].append({
"type": "rect",
"coords": [side_ox, side_oy + base_h * 3.0, (base_d + 1.0) * 4.0, 1.5 * 3.0],
"id": "",
"layer": "COUNTERTOP",
"style": "solid"
})
# Backsplash
side_geom["blocks"].append({
"type": "rect",
"coords": [side_ox, side_oy + (base_h + 1.5) * 3.0, 0.75 * 4.0, 18.0 * 3.0],
"id": "",
"layer": "COUNTERTOP",
"style": "solid"
})
# 6. Draw pantry/tall cabinet section
if has_pantry:
pantry_d = 24.0
# Outline
side_geom["blocks"].append({
"type": "rect",
"coords": [side_ox, side_oy + 4.0 * 3.0, pantry_d * 4.0, (pantry_h - 4.0) * 3.0],
"id": "",
"layer": "CABINETS_BASE",
"style": "solid"
})
# Toe kick (3" deep, 4" high)
side_geom["lines"].append({
"start": [side_ox + (pantry_d - 3.0) * 4.0, side_oy],
"end": [side_ox + (pantry_d - 3.0) * 4.0, side_oy + 4.0 * 3.0],
"layer": "CABINETS_BASE",
"style": "solid"
})
side_geom["lines"].append({
"start": [side_ox + (pantry_d - 3.0) * 4.0, side_oy + 4.0 * 3.0],
"end": [side_ox + pantry_d * 4.0, side_oy + 4.0 * 3.0],
"layer": "CABINETS_BASE",
"style": "solid"
})
# 7. Draw upper cabinet section
if has_upper:
upper_d = 12.0
# Outline
side_geom["blocks"].append({
"type": "rect",
"coords": [side_ox, side_oy + 54.0 * 3.0, upper_d * 4.0, upper_h * 3.0],
"id": "",
"layer": "CABINETS_UPPER",
"style": "solid"
})
# 8. Add side view text labels
side_geom["texts"].append({
"pos": [side_ox + 15.0 * 4.0, side_oy - 15.0],
"text": "SIDE SECTION",
"size": 5.0,
"layer": "TEXT"
})
# 9. Add dimension strings
# Vertical dimension strings (left side of wall)
# Toe kick: 4"
side_geom["dimensions"].append({
"start": [side_ox - 10.0, side_oy],
"end": [side_ox - 10.0, side_oy + 4.0 * 3.0],
"text": "4\""
})
# Base/Vanity cabinet box
box_h = vanity_h if has_vanity else base_h
side_geom["dimensions"].append({
"start": [side_ox - 10.0, side_oy + 4.0 * 3.0],
"end": [side_ox - 10.0, side_oy + box_h * 3.0],
"text": f"{(box_h - 4.0):.1f}\""
})
# Countertop: 1.5"
side_geom["dimensions"].append({
"start": [side_ox - 10.0, side_oy + box_h * 3.0],
"end": [side_ox - 10.0, side_oy + (box_h + 1.5) * 3.0],
"text": "1 1/2\""
})
# Splash space: 18" (or 4" for vanity)
splash_h = 4.0 if has_vanity else 18.0
side_geom["dimensions"].append({
"start": [side_ox - 10.0, side_oy + (box_h + 1.5) * 3.0],
"end": [side_ox - 10.0, side_oy + (box_h + 1.5 + splash_h) * 3.0],
"text": f"{splash_h:.0f}\""
})
# Upper box
if has_upper:
side_geom["dimensions"].append({
"start": [side_ox - 10.0, side_oy + 54.0 * 3.0],
"end": [side_ox - 10.0, side_oy + (54.0 + upper_h) * 3.0],
"text": f"{upper_h:.0f}\""
})
# Ceiling height total
side_geom["dimensions"].append({
"start": [side_ox - 22.0, side_oy],
"end": [side_ox - 22.0, side_oy + ceiling_height * 3.0],
"text": f"{ceiling_height:.0f}\" CLG"
})
# Horizontal depth dimensions
if has_base:
side_geom["dimensions"].append({
"start": [side_ox, side_oy + (base_h + 1.5) * 3.0 + 8.0],
"end": [side_ox + 25.0 * 4.0, side_oy + (base_h + 1.5) * 3.0 + 8.0],
"text": "25\""
})
if has_vanity:
side_geom["dimensions"].append({
"start": [side_ox, side_oy + (vanity_h + 1.5) * 3.0 + 8.0],
"end": [side_ox + 22.0 * 4.0, side_oy + (vanity_h + 1.5) * 3.0 + 8.0],
"text": "22\""
})
if has_upper:
side_geom["dimensions"].append({
"start": [side_ox, side_oy + (54.0 + upper_h) * 3.0 + 8.0],
"end": [side_ox + 12.0 * 4.0, side_oy + (54.0 + upper_h) * 3.0 + 8.0],
"text": "12\""
})
return {
"plan": plan_geom,
"elevation": elev_geom,
"side": side_geom
}
@@ -0,0 +1,74 @@
"""
===========================================================================
core/kitchen_layout_classifier.py — Kitchen Type Classifier
===========================================================================
Generates a layout signature for a kitchen and maps it to a canonical
kitchen type (e.g., K1, K2).
===========================================================================
"""
from __future__ import annotations
from typing import Any
class KitchenLayoutClassifier:
"""
Classifies kitchen layouts and maps them to K-types.
"""
def __init__(self):
# Maps signature -> type name (e.g., "K1")
self.signature_to_type: dict[str, str] = {}
self.type_counter = 0
def get_kitchen_type(self, walls: list[dict], appliances: list[dict], layout_shape: str) -> str:
"""
Generate a unique signature and return the K-type (e.g. "K1").
"""
# 1. Build appliance sequence
# Group appliances and sink cabinets by wall and sort horizontally
appliance_seqs = []
for wall in walls:
wall_name = wall["name"]
wall_items = []
# Find appliances on this wall
for app in appliances:
if app["wall"] == wall_name:
wall_items.append((app["x"], app["type"]))
# Find sink base or range cabinets on this wall from cabinets
for cab in wall.get("cabinets", []):
# Check if it has a sink/range keyword or ID mapping
cid = cab.get("id", "").upper()
c_type = cab.get("type", "").lower()
# Some cabinets are mapped to keynotes representing sinks/ranges
if "SINK" in c_type or cid in ("U9", "U2"): # U9/U2 are often sink/range in keynotes
wall_items.append((cab["x"], "SINK"))
# Sort by x coordinate
wall_items.sort(key=lambda item: item[0])
seq = "-".join(item[1] for item in wall_items)
if seq:
appliance_seqs.append(f"Wall_{wall_name}:{seq}")
appliance_seq_str = "; ".join(appliance_seqs) if appliance_seqs else "NONE"
# 2. Wall lengths string
lengths = []
for wall in sorted(walls, key=lambda w: w["name"]):
length_in = wall.get("length", 0)
lengths.append(f"{wall['name']}:{length_in:.0f}\"")
lengths_str = ", ".join(lengths)
# 3. Form final signature
signature = f"{appliance_seq_str} | {layout_shape} | {lengths_str}"
# 4. Check/register signature
if signature in self.signature_to_type:
return self.signature_to_type[signature]
else:
self.type_counter += 1
type_name = f"K{self.type_counter}"
self.signature_to_type[signature] = type_name
return type_name
+204
View File
@@ -0,0 +1,204 @@
"""
===========================================================================
core/legend_extractor.py — Keynote Legend Extractor
===========================================================================
Dynamically extracts the U-code keynotes legend (e.g., U1-U50) and their
descriptions from architectural drawing sheets. Works for both single-page
and multi-page PDFs, and handles multi-column legend layouts.
===========================================================================
"""
from __future__ import annotations
import re
from pathlib import Path
from typing import Optional, Dict
import fitz # PyMuPDF
from core.pdf_extractor import PDFExtractor, TextSpan
class LegendExtractor:
"""
Extracts U-code legends from architectural drawing pages.
"""
def __init__(self, spans: list[TextSpan], page_w: float, page_h: float):
self.spans = spans
self.page_w = page_w
self.page_h = page_h
def extract(self) -> dict[str, str]:
"""
Scan page text, find the legend area, and reconstruct keynote dictionary.
Returns a dictionary of { "U1": "Description...", "U2": "Description..." }
"""
# 1. Locate the legend header (e.g., "KEYNOTE LEGEND" or "SYMBOL LEGEND")
header_span = None
for s in self.spans:
t = s.upper
if "KEYNOTE" in t and "LEGEND" in t:
header_span = s
break
if not header_span:
# Fallback: search for first span containing "LEGEND" or "KEYNOTE"
for s in self.spans:
t = s.upper
if "LEGEND" in t:
header_span = s
break
# Define boundary of legend area
if header_span:
# Legend starts below the header and occupies the right portion of the sheet
lx0 = header_span.x0 - 200
ly0 = header_span.y1
# Extend to right edge of page
lx1 = self.page_w
ly1 = self.page_h
else:
# Fallback to rightmost 30% of the page
lx0 = self.page_w * 0.70
ly0 = 0
lx1 = self.page_w
ly1 = self.page_h
# 2. Filter spans within the legend area
legend_spans = [
s for s in self.spans
if lx0 <= s.x0 <= lx1 and ly0 <= s.y0 <= ly1 and len(s.text.strip()) > 0
]
if not legend_spans:
return {}
# 3. Detect column X coordinates for U-codes dynamically
# Look for spans matching U\d+ to identify U-code columns
u_pattern = re.compile(r'^U(\d+)$', re.IGNORECASE)
u_x_coords = []
for s in legend_spans:
if u_pattern.match(s.text.strip()):
u_x_coords.append(s.x0)
# Cluster U-code X coordinates to identify column starting points
columns = []
for x in sorted(u_x_coords):
# Group into existing column if close (within 40 pts)
matched = False
for col in columns:
if abs(col["start"] - x) < 40:
col["coords"].append(x)
col["start"] = sum(col["coords"]) / len(col["coords"])
matched = True
break
if not matched:
columns.append({"start": x, "coords": [x]})
columns.sort(key=lambda c: c["start"])
# Determine boundaries between columns
boundaries = []
for i in range(len(columns) - 1):
mid = (columns[i]["start"] + columns[i+1]["start"]) / 2
boundaries.append(mid)
# 4. Group legend spans by Y coordinate
lines_by_y: dict[float, list[TextSpan]] = {}
for s in legend_spans:
y = round(s.bbox[1], 1)
matched_y = None
for existing_y in lines_by_y:
if abs(existing_y - y) <= 3.0:
matched_y = existing_y
break
if matched_y is None:
lines_by_y[y] = [s]
else:
lines_by_y[matched_y].append(s)
# Sort lines top-to-bottom
sorted_ys = sorted(lines_by_y.keys())
# 5. Process each line and assign to columns
# We will track the current active U-code description for each column
col_active_key: dict[int, Optional[str]] = {i: None for i in range(len(columns) + 1)}
legend_dict: dict[str, list[str]] = {}
for y in sorted_ys:
line_spans = sorted(lines_by_y[y], key=lambda s: s.x0)
# Distribute spans on this line to columns based on boundaries
col_spans: dict[int, list[TextSpan]] = {i: [] for i in range(len(columns) + 1)}
for s in line_spans:
col_idx = 0
for b in boundaries:
if s.x0 > b:
col_idx += 1
else:
break
col_spans[col_idx].append(s)
# Process each column on this line
for col_idx in range(len(columns) + 1):
spans_in_col = col_spans[col_idx]
if not spans_in_col:
continue
# Check if first span is a U-code (starts a new description)
first_text = spans_in_col[0].text.strip()
m = u_pattern.match(first_text)
if m:
u_code = first_text.upper()
col_active_key[col_idx] = u_code
legend_dict[u_code] = []
# The rest of the spans in this column are part of the description
desc_parts = [s.text.strip() for s in spans_in_col[1:] if s.text.strip()]
if desc_parts:
legend_dict[u_code].append(" ".join(desc_parts))
else:
# Append to active keynote in this column if we have one
u_code = col_active_key[col_idx]
if u_code:
desc_parts = [s.text.strip() for s in spans_in_col if s.text.strip()]
if desc_parts:
legend_dict[u_code].append(" ".join(desc_parts))
# Join the list of text lines for each U-code into a single string
final_legend: dict[str, str] = {}
for u_code, lines in legend_dict.items():
full_desc = " ".join(lines).strip()
# Clean up double spaces or trailing periods/commas
full_desc = re.sub(r'\s+', ' ', full_desc)
final_legend[u_code] = full_desc
return final_legend
def extract_legend_from_pdf(pdf_path: str | Path) -> dict[str, str]:
"""Convenience wrapper to load PDF and extract keynote legend."""
pdf_path = Path(pdf_path)
if not pdf_path.exists():
return {}
with PDFExtractor(pdf_path) as ex:
# Keynotes are always on sheet 0 (first page of details)
page = ex.extract_page(0)
extractor = LegendExtractor(page.spans, page.page_w, page.page_h)
return extractor.extract()
# ══════════════════════════════════════════════════════════════════════════
# QUICK TEST
# ══════════════════════════════════════════════════════════════════════════
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python -m core.legend_extractor <path_to_pdf>")
sys.exit(1)
pdf = sys.argv[1]
legend = extract_legend_from_pdf(pdf)
print(f"\nExtracted {len(legend)} U-code legend keys:")
for k in sorted(legend.keys(), key=lambda x: int(x[1:]) if x[1:].isdigit() else 999):
print(f" {k:5s} -> {legend[k][:80]}...")
+56
View File
@@ -0,0 +1,56 @@
"""
===========================================================================
core/opening_extractor.py — Doors & Windows Extractor
===========================================================================
Locates structural openings like door passages and window sills.
===========================================================================
"""
from __future__ import annotations
import re
from typing import Optional, List, Dict, Any
from core.pdf_extractor import TextSpan, VectorRect
class OpeningExtractor:
"""
Identifies door/window dimensions, wall positions, and alignment interruptions.
"""
@staticmethod
def extract_openings(spans: list[TextSpan], rects: list[VectorRect]) -> dict:
"""
Parses text and geometry bounding boxes to identify doors and windows.
"""
doors = []
windows = []
# Parse text spans looking for window/door callouts (e.g. Window W1, W7, Door D1)
text_content = " ".join(s.text.upper() for s in spans)
# Check window coordinates/dimensions if indicated
# e.g., "WINDOW ABOVE SINK", "W7"
w_matches = re.findall(r'\bW(\d+)\b', text_content)
d_matches = re.findall(r'\bD(\d+)\b', text_content)
# Standard window width is typically 36" wide, 48" high, 36" sill
if "WINDOW" in text_content or w_matches:
windows.append({
"width_in": 36.0,
"height_in": 48.0,
"x_in": 60.0,
"sill_height_in": 36.0,
"notes": "Window found on wall"
})
if "DOOR" in text_content or d_matches:
doors.append({
"width_in": 36.0,
"height_in": 80.0,
"x_in": 120.0,
"notes": "Door opening"
})
return {
"doors": doors,
"windows": windows
}
-290
View File
@@ -1,290 +0,0 @@
"""
===========================================================================
core/unit_counter.py — Floor Plan Unit Type Counter
===========================================================================
Reads building floor plan PDFs and counts how many of each unit type
exist per floor, then aggregates for the whole building.
Strategy:
1. Extract all text from floor plan PDFs
2. Find unit labels matching known patterns:
"UNIT A1", "UNIT A-1", "A1 TYP.", "A-1", "TYPE A1", etc.
3. Count unique occurrences (not label repetitions like "TYP.")
4. Aggregate across all floor plan PDFs
5. If auto-count confidence < 80%, save to JSON and let user confirm
Architecture notes:
- Casa Familia: 3 floor plan PDFs (Ground, 2nd, 3rd)
- Heritage Village: 3 floor plan PDFs (Partial C, Ground, 2nd, 3rd)
- Multiple units of same type appear on each floor
===========================================================================
"""
from __future__ import annotations
import json
import re
from collections import Counter, defaultdict
from dataclasses import dataclass, field
from pathlib import Path
from typing import Optional
from core.pdf_extractor import PDFExtractor, TextSpan
# ══════════════════════════════════════════════════════════════════════════
# DATA CLASSES
# ══════════════════════════════════════════════════════════════════════════
@dataclass
class FloorCount:
"""Unit counts for one floor."""
floor_name: str
pdf_path: str
unit_counts: dict[str, int] = field(default_factory=dict)
confidence: float = 0.0
raw_hits: list[str] = field(default_factory=list)
@dataclass
class ProjectUnitMatrix:
"""Complete unit count matrix for a project."""
project_name: str
floor_counts: list[FloorCount] = field(default_factory=list)
totals: dict[str, int] = field(default_factory=dict)
confidence: float = 0.0
needs_review: bool = False
review_note: str = ""
def to_dict(self) -> dict:
return {
"project_name": self.project_name,
"totals": self.totals,
"by_floor": [
{
"floor": fc.floor_name,
"pdf": fc.pdf_path,
"counts": fc.unit_counts,
"confidence": fc.confidence,
}
for fc in self.floor_counts
],
"confidence": self.confidence,
"needs_review": self.needs_review,
"review_note": self.review_note,
}
def print_summary(self):
print(f"\n Project Unit Matrix: {self.project_name}")
print(f" {'Unit Type':15s} {'Count':8s}")
print(" " + "-" * 30)
total = 0
for unit_type, count in sorted(self.totals.items()):
print(f" {unit_type:15s} {count:8d}")
total += count
print(" " + "-" * 30)
print(f" {'TOTAL':15s} {total:8d}")
print(f" Confidence: {self.confidence:.1%}")
if self.needs_review:
print(f" ⚠️ Needs review: {self.review_note}")
# ══════════════════════════════════════════════════════════════════════════
# UNIT TYPE PATTERNS
# ══════════════════════════════════════════════════════════════════════════
# Patterns that identify a unit type label in floor plan text
# Captures: "UNIT A1", "UNIT A-1", "A1 TYP.", "TYPE A1", "UNIT A1 TYP."
_UNIT_PATTERNS = [
# "UNIT A1" or "UNIT A-1"
re.compile(r'\bUNIT\s+(A|B|C|D|ST)-?\d+[A-Za-z]?\s*(?:TYP\.?|N|ACC|ADA|FHA)?\b', re.IGNORECASE),
# "A1 TYP." or "A-1A TYP."
re.compile(r'\b(A|B|C|D|ST)-?\d+[A-Za-z]?\s*TYP\.?\b', re.IGNORECASE),
# "TYPE K1" or "TYPE A"
re.compile(r'\bTYPE\s+(A|B|C|D|ST|K)\d*[A-Za-z]?\b', re.IGNORECASE),
]
# Normalization: map raw label to canonical unit type
def _normalize_unit_label(raw: str) -> str:
"""Normalize a unit label to canonical form e.g. 'UNIT A1 TYP.' → 'A1'."""
raw = raw.upper().strip()
# Remove "UNIT " prefix
raw = re.sub(r'^UNIT\s+', '', raw)
# Remove trailing qualifiers (TYP., N, etc.) — keep ACC/ADA
raw = re.sub(r'\s+TYP\.?$', '', raw)
raw = re.sub(r'\s+TYPE\s+', '', raw)
# Normalize dash: "A-1" → "A1"
raw = re.sub(r'([A-Z])-(\d)', r'\1\2', raw)
# Normalize spaces
raw = raw.strip()
return raw
# ══════════════════════════════════════════════════════════════════════════
# UNIT COUNTER
# ══════════════════════════════════════════════════════════════════════════
class UnitCounter:
"""
Count unit types from architectural floor plan PDFs.
Usage:
counter = UnitCounter()
matrix = counter.count_from_pdfs(
pdf_paths=["Floor_Plans/Ground.pdf", "Floor_Plans/2nd.pdf"],
project_name="Casa Familia",
)
matrix.print_summary()
"""
def count_from_pdfs(
self,
pdf_paths: list[str | Path],
project_name: str,
manual_override: Optional[dict[str, int]] = None,
) -> ProjectUnitMatrix:
"""
Extract unit counts from multiple floor plan PDFs.
Args:
pdf_paths: List of floor plan PDF paths
project_name: Project name for display
manual_override: If provided, use these counts instead of auto-detection
"""
if manual_override:
print(f" Using manual unit counts for {project_name}")
return ProjectUnitMatrix(
project_name = project_name,
totals = manual_override,
confidence = 1.0,
needs_review = False,
)
floor_counts: list[FloorCount] = []
all_unit_counts: Counter = Counter()
for pdf_path in pdf_paths:
pdf_path = Path(pdf_path)
if not pdf_path.exists():
print(f" ⚠️ Floor plan PDF not found: {pdf_path}")
continue
floor_count = self._count_from_pdf(pdf_path)
floor_counts.append(floor_count)
for unit_type, count in floor_count.unit_counts.items():
all_unit_counts[unit_type] += count
# Compute overall confidence
if floor_counts:
avg_conf = sum(fc.confidence for fc in floor_counts) / len(floor_counts)
else:
avg_conf = 0.0
totals = dict(all_unit_counts)
needs_review = avg_conf < 0.80 or not totals
matrix = ProjectUnitMatrix(
project_name = project_name,
floor_counts = floor_counts,
totals = totals,
confidence = avg_conf,
needs_review = needs_review,
review_note = (
"Auto-detection confidence too low — please verify unit counts in project_config.json"
if needs_review else ""
),
)
return matrix
def _count_from_pdf(self, pdf_path: Path) -> FloorCount:
"""Extract unit type counts from one floor plan PDF."""
floor_name = pdf_path.stem
print(f" Counting units from: {floor_name}")
with PDFExtractor(pdf_path) as ex:
all_spans: list[TextSpan] = []
for i in range(ex.page_count):
all_spans.extend(ex.extract_spans(i))
hits: list[str] = []
for span in all_spans:
text = span.text.strip()
if len(text) < 2 or len(text) > 40:
continue
for pattern in _UNIT_PATTERNS:
m = pattern.search(text)
if m:
normalized = _normalize_unit_label(m.group(0))
if normalized and len(normalized) <= 10:
hits.append(normalized)
break
# Count occurrences
raw_counter = Counter(hits)
print(f" Raw hits: {dict(raw_counter)}")
# Filter: a label appearing < 2 times is likely a legend/title, not an instance
unit_counts = {k: v for k, v in raw_counter.items() if v >= 2}
# Confidence: higher if counts are consistent across floors
confidence = 0.85 if unit_counts else 0.30
return FloorCount(
floor_name = floor_name,
pdf_path = str(pdf_path),
unit_counts = unit_counts,
confidence = confidence,
raw_hits = hits,
)
# ══════════════════════════════════════════════════════════════════════════
# JSON SAVE/LOAD
# ══════════════════════════════════════════════════════════════════════════
def save_matrix(matrix: ProjectUnitMatrix, out_path: str | Path) -> Path:
"""Save ProjectUnitMatrix to JSON file."""
out_path = Path(out_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(
json.dumps(matrix.to_dict(), indent=2, ensure_ascii=False),
encoding="utf-8"
)
print(f" Unit matrix saved: {out_path}")
return out_path
def load_matrix_from_config(unit_counts: dict[str, int], project_name: str) -> ProjectUnitMatrix:
"""Create a ProjectUnitMatrix directly from project_config.json counts."""
return ProjectUnitMatrix(
project_name = project_name,
totals = unit_counts,
confidence = 1.0,
needs_review = False,
)
# ══════════════════════════════════════════════════════════════════════════
# QUICK TEST
# ══════════════════════════════════════════════════════════════════════════
if __name__ == "__main__":
import sys
if len(sys.argv) < 2:
print("Usage: python -m core.unit_counter <floor_plan_pdf1> [<floor_plan_pdf2> ...]")
print("\nRunning with manual counts test...")
matrix = load_matrix_from_config(
unit_counts = {
"A1": 14, "A2-ADA": 3, "A3": 2,
"B1": 3, "B2-ADA": 3,
},
project_name = "Casa Familia (manual)",
)
matrix.print_summary()
sys.exit(0)
pdf_paths = sys.argv[1:]
counter = UnitCounter()
matrix = counter.count_from_pdfs(pdf_paths, project_name="Test Project")
matrix.print_summary()
@@ -0,0 +1,151 @@
"""
===========================================================================
core/unit_matrix_extractor.py — Unit Matrix Extractor
===========================================================================
Counts and compiles floor-by-floor and building-wide unit takeoff matrices.
===========================================================================
"""
from __future__ import annotations
import json
import re
from pathlib import Path
from collections import Counter, defaultdict
from typing import Optional, List, Dict
from dataclasses import dataclass
from core.pdf_extractor import PDFExtractor, TextSpan
@dataclass
class FloorCount:
floor_name: str
pdf_path: str
unit_counts: dict[str, int]
confidence: float
@dataclass
class UnitMatrixResult:
project_name: str
totals: dict[str, int]
floor_counts: list[FloorCount]
confidence: float = 1.0
needs_review: bool = False
def print_summary(self):
print(f"\n--- Takeoff Matrix Summary: {self.project_name} ---")
for ut, count in self.totals.items():
print(f" Unit {ut}: {count}")
print(f"Confidence: {self.confidence:.2f} | Needs Review: {self.needs_review}")
def load_matrix_from_config(config_dict: dict, project_name: str) -> UnitMatrixResult:
"""Loads a unit takeoff matrix directly from configuration dictionary."""
return UnitMatrixResult(
project_name = project_name,
totals = config_dict,
floor_counts = [],
confidence = 1.0,
needs_review = False
)
class UnitMatrixExtractor:
"""
Handles unit occurrence count taking and output mapping.
"""
def __init__(self):
# Patterns for unit occurrences
self._patterns = [
re.compile(r'\bUNIT\s+(A|B|C|D|ST)-?\d+[A-Za-z]?\s*(?:TYP\.?|N|ACC|ADA|FHA)?\b', re.IGNORECASE),
re.compile(r'\b(A|B|C|D|ST)-?\d+[A-Za-z]?\s*TYP\.?\b', re.IGNORECASE),
re.compile(r'\bTYPE\s+(A|B|C|D|ST|K)\d*[A-Za-z]?\b', re.IGNORECASE),
]
def count_from_pdfs(
self,
pdf_paths: list[str | Path],
project_name: str
) -> UnitMatrixResult:
"""
Count occurrences across PDFs and return structured results as a UnitMatrixResult.
"""
totals = {}
floor_counts = []
for p in pdf_paths:
path = Path(p)
if not path.exists():
continue
# Count from individual floor plan sheet
counts = self._count_units_on_sheet(path)
floor_counts.append(counts)
for ut, cnt in counts.unit_counts.items():
totals[ut] = totals.get(ut, 0) + cnt
conf = 1.0
if floor_counts:
conf = sum(fc.confidence for fc in floor_counts) / len(floor_counts)
needs_review = conf < 0.8 or not totals
return UnitMatrixResult(
project_name = project_name,
totals = totals,
floor_counts = floor_counts,
confidence = conf,
needs_review = needs_review
)
def extract_matrix(
self,
pdf_paths: list[str | Path],
project_name: str,
manual_override: Optional[dict[str, int]] = None
) -> dict:
"""
Backward compatible dict output.
"""
res = self.count_from_pdfs(pdf_paths, project_name)
if manual_override:
res.totals = manual_override
return {
"project_name": res.project_name,
"totals": res.totals,
"floor_counts": res.floor_counts
}
def _count_units_on_sheet(self, pdf_path: Path) -> FloorCount:
floor_name = pdf_path.stem
hits = []
with PDFExtractor(pdf_path) as ex:
for i in range(ex.page_count):
spans = ex.extract_spans(i)
for s in spans:
text = s.text.strip()
if len(text) < 2 or len(text) > 45:
continue
for pat in self._patterns:
m = pat.search(text)
if m:
raw = m.group(0).upper().strip()
raw = re.sub(r'^UNIT\s+', '', raw)
raw = re.sub(r'\s+TYP\.?$', '', raw)
raw = re.sub(r'\s+TYPE\s+', '', raw)
raw = re.sub(r'([A-Z])-(\d)', r'\1\2', raw)
normalized = raw.strip()
if normalized and len(normalized) <= 12:
hits.append(normalized)
break
raw_counter = Counter(hits)
unit_counts = {k: v for k, v in raw_counter.items() if v >= 2}
confidence = 0.85 if unit_counts else 0.30
return FloorCount(
floor_name = floor_name,
pdf_path = str(pdf_path),
unit_counts = unit_counts,
confidence = confidence
)
@@ -0,0 +1,60 @@
"""
===========================================================================
core/vanity_layout_classifier.py — Vanity Type Classifier
===========================================================================
Generates a layout signature for a bathroom vanity and maps it to a
canonical bathroom type (e.g., V1, V2).
===========================================================================
"""
from __future__ import annotations
class VanityLayoutClassifier:
"""
Classifies vanity layouts and maps them to V-types.
"""
def __init__(self):
# Maps signature -> type name (e.g., "V1")
self.signature_to_type: dict[str, str] = {}
self.type_counter = 0
def get_vanity_type(self, cabinets: list[dict], room_width_mm: float = 0.0) -> str:
"""
Generate a unique signature and return the V-type (e.g. "V1").
"""
# Find vanity cabinets and sum their widths
vanity_cabs = [
c for c in cabinets
if c.get("type") == "vanity" or "vanity" in c.get("type", "").lower()
]
vanity_width_in = 0.0
num_sinks = 0
is_ada = False
for vc in vanity_cabs:
w_in = vc.get("width_mm", vc.get("width", 0) * 25.4) / 25.4
vanity_width_in += w_in
if vc.get("is_ada"):
is_ada = True
# Double vanity check from keynote or notes
if "double" in vc.get("notes", "").lower() or "double" in vc.get("location", "").lower():
num_sinks = 2
if not vanity_cabs:
# Fallback if no explicit vanity cabinets are detected
signature = "NO_VANITY"
else:
if num_sinks == 0:
num_sinks = 2 if vanity_width_in >= 48 else 1
ada_str = "ADA" if is_ada else "STD"
signature = f"VANITY | {vanity_width_in:.0f}\" | {num_sinks}SINK | {ada_str}"
if signature in self.signature_to_type:
return self.signature_to_type[signature]
else:
self.type_counter += 1
type_name = f"V{self.type_counter}"
self.signature_to_type[signature] = type_name
return type_name
@@ -0,0 +1,161 @@
"""
===========================================================================
generators/shop_drawing_dxf.py — AutoCAD DXF Generator
===========================================================================
Translates coordinate lines, annotations, and boxes into AutoCAD-compatible
dxf files using ezdxf.
===========================================================================
"""
from __future__ import annotations
import os
from pathlib import Path
import ezdxf
class DXFDrawingGenerator:
"""
Generates dxf CAD vector files for units and elevations.
"""
def __init__(self):
pass
def generate(self, geometry: dict, output_path: str | Path):
"""
Generates plan and elevation views and saves to a dxf file.
"""
output_path = Path(output_path)
output_path.parent.mkdir(parents=True, exist_ok=True)
# Create drawing
doc = ezdxf.new('R2010')
msp = doc.modelspace()
# Add typical layers
doc.layers.add('WALLS', color=7)
doc.layers.add('CABINETS_BASE', color=7) # Black/White
doc.layers.add('CABINETS_UPPER', color=7) # Black/White
doc.layers.add('GROUND', color=8)
doc.layers.add('CEILING', color=8)
doc.layers.add('DIMENSIONS', color=8) # Gray/Pencil like
doc.layers.add('TEXT', color=7) # Calculate wall length in inches dynamically to position views correctly
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 - 250.0) / 4.0
ELEV_Y_OFFSET = 60.0
SIDE_X_OFFSET = max(90.0, wall_length_in) + 30.0
# Helper coordinate mapping functions (converting raw visual coordinates back to actual inches)
def to_plan_inch(pt):
return ((pt[0] - 250.0) / 4.0, (pt[1] - 450.0) / 4.0)
def to_elev_inch(pt):
return ((pt[0] - 250.0) / 4.0, (pt[1] - 150.0) / 3.0 + ELEV_Y_OFFSET)
def to_side_inch(pt):
return ((pt[0] - 250.0) / 4.0 + SIDE_X_OFFSET, (pt[1] - 150.0) / 3.0 + ELEV_Y_OFFSET)
# 1. Write Plan Geometry to model space
for line in geometry["plan"]["lines"]:
layer = line.get("layer", "WALLS")
msp.add_line(to_plan_inch(line["start"]), to_plan_inch(line["end"]), dxfattribs={'layer': layer})
for block in geometry["plan"]["blocks"]:
layer = block.get("layer", "CABINETS_BASE")
x, y, w, h = block["coords"]
x_in = (x - 250.0) / 4.0
y_in = (y - 450.0) / 4.0
w_in = w / 4.0
h_in = h / 4.0
msp.add_line((x_in, y_in), (x_in + w_in, y_in), dxfattribs={'layer': layer})
msp.add_line((x_in + w_in, y_in), (x_in + w_in, y_in + h_in), dxfattribs={'layer': layer})
msp.add_line((x_in + w_in, y_in + h_in), (x_in, y_in + h_in), dxfattribs={'layer': layer})
msp.add_line((x_in, y_in + h_in), (x_in, y_in), dxfattribs={'layer': layer})
for txt in geometry["plan"]["texts"]:
layer = txt.get("layer", "TEXT")
pos_in = to_plan_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["plan"]["dimensions"]:
layer = "DIMENSIONS"
s_in = to_plan_inch(dim["start"])
e_in = to_plan_inch(dim["end"])
msp.add_line(s_in, e_in, dxfattribs={'layer': layer})
text_pos = [(s_in[0] + e_in[0])/2, (s_in[1] + e_in[1])/2 + 2.0]
msp.add_text(dim["text"], dxfattribs={'layer': layer, 'height': 2.0}).set_placement(text_pos)
# 2. Write Elevation Geometry
for line in geometry["elevation"]["lines"]:
layer = line.get("layer", "WALLS")
msp.add_line(to_elev_inch(line["start"]), to_elev_inch(line["end"]), dxfattribs={'layer': layer})
for block in geometry["elevation"]["blocks"]:
layer = block.get("layer", "CABINETS_BASE")
x, y, w, h = block["coords"]
x_in = (x - 250.0) / 4.0
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})
msp.add_line((x_in + w_in, y_in), (x_in + w_in, y_in + h_in), dxfattribs={'layer': layer})
msp.add_line((x_in + w_in, y_in + h_in), (x_in, y_in + h_in), dxfattribs={'layer': layer})
msp.add_line((x_in, y_in + h_in), (x_in, y_in), dxfattribs={'layer': layer})
for txt in geometry["elevation"]["texts"]:
layer = txt.get("layer", "TEXT")
pos_in = to_elev_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["elevation"]["dimensions"]:
layer = "DIMENSIONS"
s_in = to_elev_inch(dim["start"])
e_in = to_elev_inch(dim["end"])
msp.add_line(s_in, e_in, dxfattribs={'layer': layer})
text_pos = [(s_in[0] + e_in[0])/2, (s_in[1] + e_in[1])/2 + 2.0]
msp.add_text(dim["text"], dxfattribs={'layer': layer, 'height': 2.0}).set_placement(text_pos)
# 3. Write Side Section Geometry
for line in geometry.get("side", {}).get("lines", []):
layer = line.get("layer", "WALLS")
msp.add_line(to_side_inch(line["start"]), to_side_inch(line["end"]), dxfattribs={'layer': layer})
for block in geometry.get("side", {}).get("blocks", []):
layer = block.get("layer", "CABINETS_BASE")
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})
msp.add_line((x_in + w_in, y_in), (x_in + w_in, y_in + h_in), dxfattribs={'layer': layer})
msp.add_line((x_in + w_in, y_in + h_in), (x_in, y_in + h_in), dxfattribs={'layer': layer})
msp.add_line((x_in, y_in + h_in), (x_in, y_in), dxfattribs={'layer': layer})
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"])
msp.add_line(s_in, e_in, dxfattribs={'layer': layer})
text_pos = [(s_in[0] + e_in[0])/2, (s_in[1] + e_in[1])/2 + 2.0]
msp.add_text(dim["text"], dxfattribs={'layer': layer, 'height': 2.0}).set_placement(text_pos)
# 4. Add view labels to DXF model space
msp.add_text("COUNTERTOP PLAN VIEW", dxfattribs={'layer': 'TEXT', 'height': 3.5}).set_placement((wall_length_in / 2, -40.0))
msp.add_text("FRONT ELEVATION VIEW", dxfattribs={'layer': 'TEXT', 'height': 3.5}).set_placement((wall_length_in / 2, ELEV_Y_OFFSET - 15.0))
msp.add_text("SIDE SECTION VIEW", dxfattribs={'layer': 'TEXT', 'height': 3.5}).set_placement((SIDE_X_OFFSET + 15.0, ELEV_Y_OFFSET - 15.0))
# Save file
doc.saveas(str(output_path))
print(f" [SUCCESS] DXF drawing saved: {output_path}")
return output_path
+657 -22
View File
@@ -50,10 +50,11 @@ DA_T = PAGE_H - 10.0
DA_B = 10.0
# Colors
NAVY = colors.Color(0.106, 0.212, 0.365) # #1B365D
NAVY = colors.Color(0.15, 0.15, 0.15) # Charcoal/Pencil Black
WHITE = colors.white
LTGRAY = colors.Color(0.95, 0.95, 0.95)
LTBLUE = colors.Color(0.85, 0.89, 0.95)
PENCIL_MEDIUM = colors.Color(0.35, 0.35, 0.35) # Pencil gray for dimensions/subtle details
# ══════════════════════════════════════════════════════════════════════════
@@ -110,8 +111,8 @@ def _draw_title_block(c: canvas.Canvas, config: dict, page_num: int, total_pages
"""Draw the right-side vertical title block."""
c.saveState()
# Title block background
c.setFillColor(NAVY)
# Title block background - white background
c.setFillColor(WHITE)
c.rect(TB_X, 0, TB_W, PAGE_H, fill=1, stroke=0)
# Rotate to draw vertical text
@@ -120,7 +121,7 @@ def _draw_title_block(c: canvas.Canvas, config: dict, page_num: int, total_pages
# Company name
company = config.get("company", {})
c.setFillColor(WHITE)
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 8)
c.drawCentredString(0, 28, company.get("name", "ITALIAN KITCHEN AND BATH"))
@@ -128,7 +129,7 @@ def _draw_title_block(c: canvas.Canvas, config: dict, page_num: int, total_pages
c.drawCentredString(0, 20, company.get("tagline", "kitchen | bath | tile | closet"))
# Divider
c.setStrokeColor(WHITE)
c.setStrokeColor(NAVY)
c.setLineWidth(0.5)
c.line(-28, 14, 28, 14)
@@ -140,6 +141,7 @@ def _draw_title_block(c: canvas.Canvas, config: dict, page_num: int, total_pages
f"DATE: {config.get('date', '')}",
f"REV: {config.get('revision', '1.0')}",
f"DRAWN: {config.get('drawn_by', 'A.C')}",
f"SCALE: 1/2\" = 1'-0\"",
drawing_title[:28],
f"SHEET: {page_num} / {total_pages}",
]
@@ -166,10 +168,10 @@ def _draw_page_border(c: canvas.Canvas):
def _draw_section_header(c: canvas.Canvas, y: float, text: str):
"""Draw a navy-background section header bar."""
c.setFillColor(NAVY)
"""Draw a light-gray-background section header bar with dark pencil text."""
c.setFillColor(LTGRAY)
c.rect(DA_L, y - 12, DA_R - DA_L, 14, fill=1, stroke=0)
c.setFillColor(WHITE)
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 8)
c.drawString(DA_L + 4, y - 8, text)
return y - 14
@@ -184,11 +186,11 @@ def _draw_cover(c: canvas.Canvas, config: dict, unit_totals: dict, total_pages:
company = config.get("company", {})
# Background
c.setFillColor(NAVY)
c.setFillColor(WHITE)
c.rect(0, PAGE_H * 0.55, TB_X, PAGE_H * 0.45, fill=1, stroke=0)
# Company logo / name area
c.setFillColor(WHITE)
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 28)
c.drawCentredString((DA_L + DA_R) / 2, PAGE_H * 0.80,
company.get("name", "ITALIAN KITCHEN AND BATH"))
@@ -246,6 +248,372 @@ 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)
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):
_draw_page_border(c)
_draw_title_block(c, config, 2, total_pages, "PROJECT MATRIX")
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 14)
c.drawString(DA_L + 10, DA_T - 20, "PROJECT CABINET MATRIX")
c.setFont(_FONT_REG, 8)
c.setFillColor(colors.black)
c.drawString(DA_L + 10, DA_T - 32, config.get("project_name", "CASA FAMILIA"))
# Table dimensions
cols = [120, 48, 38, 38, 38, 38, 95, 62.5, 62.5]
tw = sum(cols)
tx = DA_L + (1139.6 - tw) / 2
ty = DA_T - 50
# Draw Header (48 pt height)
c.saveState()
c.setFillColor(LTGRAY)
c.rect(tx, ty - 48, tw, 48, fill=1, stroke=1)
col_x = [tx]
for w in cols:
col_x.append(col_x[-1] + w)
c.setStrokeColor(NAVY)
c.setLineWidth(0.5)
# Draw vertical lines in header
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
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)
c.setFont(_FONT_BOLD, 8)
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[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")
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"}
]
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"}
]
v1_tot = 0
v2_tot = 0
v3_tot = 0
v4_tot = 0
kt_totals = {"K1": 0, "K2": 0, "K3": 0, "K4": 0}
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
# 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"])
]
ry = ty - 48
rh = 16
def draw_row(ry, cells, bold=False, is_building_header=False):
c.saveState()
c.setStrokeColor(NAVY)
c.setLineWidth(0.5)
c.rect(tx, ry, tw, rh, stroke=1, fill=0)
# Draw vertical lines
cx = tx
for w in cols[:-1]:
cx += w
c.line(cx, ry, cx, ry + rh)
# Draw cell contents
c.setFont(_FONT_BOLD if bold else _FONT_REG, 7.5)
c.setFillColor(colors.black)
cx = tx
for i, val in enumerate(cells):
w = cols[i]
if val not in (0, "", None, "-"):
if i == 0: # Left aligned for Unit Name
c.drawString(cx + 4, ry + 4, str(val))
else: # Centered for others
c.drawCentredString(cx + w / 2, ry + 4, str(val))
elif val == "-" or (is_building_header and i == 1):
c.drawCentredString(cx + w / 2, ry + 4, "-")
cx += w
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
# 2. Building A units
for idx, item in enumerate(building_a_units):
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"],
"",
""
])
# 5. Table outer border
c.saveState()
c.setStrokeColor(NAVY)
c.setLineWidth(0.75)
c.rect(tx, ry, tw, (ty - 48) - ry, fill=0, stroke=1)
c.restoreState()
# 6. Summary Totals below table (just like in the image)
sum_y = ry - 20
c.setFont(_FONT_BOLD, 8)
c.setFillColor(colors.black)
# Totals numbers centered under respective columns
c.drawCentredString(tx + cols[0] + cols[1] / 2, sum_y, str(tot_kitchens)) # total qty (50)
c.drawCentredString(tx + sum(cols[:2]) + cols[2] / 2, sum_y, str(v1_tot)) # V1 (34)
c.drawCentredString(tx + sum(cols[:3]) + cols[3] / 2, sum_y, str(v2_tot)) # V2 (12)
c.drawCentredString(tx + sum(cols[:4]) + cols[4] / 2, sum_y, str(v3_tot)) # V3 (4)
c.drawCentredString(tx + sum(cols[:5]) + cols[5] / 2, sum_y, str(v4_tot)) # V4 (12)
c.drawCentredString(tx + sum(cols[:8]) + cols[8] / 2, sum_y, str(tot_kitchens)) # total kitchens (50)
# Vanity labels below totals numbers
lbl_y = sum_y - 12
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")
c.drawCentredString(tx + sum(cols[:5]) + cols[5] / 2, lbl_y, "V4")
# Left side block text
txt_y = lbl_y - 25
c.drawString(tx + 40, txt_y, f"KITCHEN TOTAL QTY = {tot_kitchens}")
c.drawString(tx + 40, txt_y - 12, f"VANITY TOTAL QTY = {v1_tot + v2_tot + v3_tot + v4_tot}")
def _draw_heritage_matrix(c: canvas.Canvas, config: dict, unit_totals: dict, total_pages: int):
_draw_page_border(c)
_draw_title_block(c, config, 2, total_pages, "PROJECT MATRIX")
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 14)
c.drawString(DA_L + 10, DA_T - 20, "PROJECT CABINET MATRIX")
c.setFont(_FONT_REG, 8)
c.setFillColor(colors.black)
c.drawString(DA_L + 10, DA_T - 32, config.get("project_name", "HERITAGE VILLAGE"))
# Table columns centered
cols = [90, 160, 30, 45, 45, 45, 45, 45, 45, 60, 60]
heads = ["UNIT TYPE", "DESCRIPTION", "QTY", "KIT. UPPER", "KIT. LOWER", "KIT. TALL", "KIT. TOTAL", "BATH CABS", "UNIT TOTAL", "PROJ. KIT.", "PROJ. BATH"]
tw = sum(cols)
tx = DA_L + (1139.6 - tw) / 2
ty = DA_T - 50
# Table header row
c.setLineWidth(0.5)
c.rect(tx, ty-32, tw, 32, stroke=1, fill=0)
cx = tx
c.setFont(_FONT_BOLD, 7.5)
for h, cw in zip(heads, cols):
ls = h.split("\n")
for li, l in enumerate(ls):
c.drawCentredString(cx+cw/2, ty-14+li*(-10), l)
if cx > tx: c.line(cx, ty-32, cx, ty)
cx += cw
heritage_matrix_data = [
{"unit": "A-1", "desc": "1BR/1Bath FHA", "qty_key": "A-1", "u": 4, "l": 4, "t": 0, "b": 3},
{"unit": "A-1a ACC", "desc": "1BR/1Bath Accessible", "qty_key": "A-1a ACC", "u": 4, "l": 4, "t": 0, "b": 3},
{"unit": "B-1", "desc": "2BR/2Bath FHA", "qty_key": "B-1", "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "B-1a ACC", "desc": "2BR/2Bath Accessible", "qty_key": "B-1a ACC", "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "C-1", "desc": "3BR/2Bath FHA", "qty_key": "C-1", "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "C-2", "desc": "3BR/2Bath FHA", "qty_key": "C-2", "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "C-2a ACC", "desc": "3BR/2Bath Accessible", "qty_key": "C-2a ACC", "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "C-3", "desc": "3BR/2Bath FHA", "qty_key": "C-3", "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "D-1N", "desc": "4BR/2Bath FHA (North)", "qty_key": "D-1N", "u": 6, "l": 6, "t": 0, "b": 5},
{"unit": "D-1", "desc": "4BR/2Bath FHA", "qty_key": "D-1", "u": 6, "l": 6, "t": 0, "b": 5},
{"unit": "D-1a ACC", "desc": "4BR/2Bath Accessible", "qty_key": "D-1a ACC", "u": 6, "l": 6, "t": 0, "b": 5},
{"unit": "D-1A ACC", "desc": "4BR/2Bath Accessible", "qty_key": "D-1A ACC", "u": 6, "l": 6, "t": 0, "b": 5},
{"unit": "ST-1a ACC", "desc": "Studio Accessible", "qty_key": "ST-1a ACC", "u": 3, "l": 3, "t": 0, "b": 2},
{"unit": "ST-1", "desc": "Studio FHA", "qty_key": "ST-1", "u": 3, "l": 3, "t": 0, "b": 2},
]
def draw_row(ry, label, desc, data, bold=False):
c.setLineWidth(0.5)
c.rect(tx, ry, tw, 16, stroke=1, fill=0)
fn = "Helvetica-Bold" if bold else "Helvetica"
c.setFont(fn, 8); c.setFillColor(colors.black)
vals = [
label, desc, data.get("qty",""), data.get("u",""),
data.get("l",""), data.get("t",""), data.get("kt",""),
data.get("b",""), data.get("ut",""), data.get("pk",""),
data.get("pb","")
]
cx = tx
for i, (v, cw) in enumerate(zip(vals, cols)):
if v not in (0, ""):
if i in (0, 1): # label and desc left-aligned
c.drawString(cx+4, ry+4, str(v))
else:
c.drawCentredString(cx+cw/2, ry+4, str(v))
if i > 0: c.line(cx, ry, cx, ry+16)
cx += cw
ry = ty - 32
tot_qty = 0
tot_pk = 0
tot_pb = 0
rh = 16
for r in heritage_matrix_data:
ry -= rh
qty = unit_totals.get(r["qty_key"], 0)
kt = r["u"] + r["l"] + r["t"]
ut = kt + r["b"]
pk = kt * qty
pb = r["b"] * qty
draw_row(ry, r["unit"], r["desc"],
{"qty": qty, "u": r["u"], "l": r["l"], "t": r["t"] or "",
"kt": kt, "b": r["b"], "ut": ut, "pk": pk, "pb": pb})
tot_qty += qty
tot_pk += pk
tot_pb += pb
# Totals row
ry -= rh
c.setFont("Helvetica-Bold", 8.5); c.setFillColor(colors.black)
c.rect(tx, ry, tw, rh, stroke=1, fill=0)
vals = ["PROJECT TOTALS", "", tot_qty, "", "", "", "", "", "", tot_pk, tot_pb]
cx = tx
for i, (v, cw) in enumerate(zip(vals, cols)):
if v not in (0, ""):
if i == 0:
c.drawString(cx+4, ry+4, str(v))
else:
c.drawCentredString(cx+cw/2, ry+4, str(v))
if i > 0: c.line(cx, ry, cx, ry+rh)
cx += cw
# Summary totals
c.setFont("Helvetica-Bold", 11); c.setFillColor(colors.black)
c.drawString(tx+50, ry-30, f"KITCHEN TOTAL QTY = {tot_pk}")
c.drawString(tx+50, ry-50, f"VANITY TOTAL QTY = {tot_pb}")
def _draw_generic_matrix(c: canvas.Canvas, config: dict, unit_schedules: dict,
unit_totals: dict, total_pages: int):
_draw_page_border(c)
_draw_title_block(c, config, 2, total_pages, "PROJECT MATRIX")
@@ -265,9 +633,9 @@ def _draw_matrix_page(c: canvas.Canvas, config: dict, unit_schedules: dict,
table_y = DA_T - 50
# Draw header row
c.setFillColor(NAVY)
c.setFillColor(LTGRAY)
c.rect(table_x, table_y - 14, sum(col_widths), 14, fill=1, stroke=0)
c.setFillColor(WHITE)
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 7)
x = table_x
for w, h in zip(col_widths, headers):
@@ -351,8 +719,277 @@ def _draw_unit_page(c: canvas.Canvas, config: dict, unit_type: str, schedule,
# Page header
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 12)
c.drawString(DA_L + 4, DA_T - 18, f"UNIT {unit_type} — CABINET SCHEDULE")
c.drawString(DA_L + 4, DA_T - 18, f"UNIT {unit_type} — CABINET SCHEDULE & LAYOUTS")
# Render Geometries from GeometryEngine on the Left
wall_length_inches = 90.0
if schedule:
from core.geometry_engine import GeometryEngine
# Build walls for GeometryEngine
walls_info = []
for ev in schedule.elevations:
cabs_list = []
base_x = 0
for cab in ev.cabinets:
w_in = round(cab.width_mm / 25.4)
h_in = round(cab.height_mm / 25.4)
cabs_list.append({
"id": cab.cabinet_id or cab.code,
"x": base_x,
"width": w_in,
"height": h_in,
"type": cab.cabinet_type,
"cabinet_type": cab.cabinet_type
})
base_x += w_in
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
if wall_name.upper() in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
wall_name = "A"
walls_info.append({
"name": wall_name,
"length": max(90.0, base_x),
"cabinets": cabs_list
})
if not walls_info:
walls_info.append({
"name": "A",
"length": 90.0,
"cabinets": []
})
geom_engine = GeometryEngine()
ceiling_height = 108.0
for ev in schedule.elevations:
if ev.ceiling_height_in is not None:
ceiling_height = ev.ceiling_height_in
break
geom_data = geom_engine.generate_layout_geometry(
walls = walls_info,
appliances = [],
ceiling_height = ceiling_height,
soffit_height = ceiling_height - 12.0
)
# Left visual drawings area: X from 40 to 460 (width 420 pt).
# We reserve 280 pt for plan/elevation width, and the rest for side view.
visual_width_allowed = 280.0
# Calculate total width of all walls including 100pt spacing (which is 25 inches)
total_length_inches = sum(w.get("length", 90.0) for w in walls_info) + (len(walls_info) - 1) * 25.0
wall_length_inches = total_length_inches
draw_scale = 1.0
if wall_length_inches * 4.0 > visual_width_allowed:
draw_scale = visual_width_allowed / (wall_length_inches * 4.0)
GE_PLAN_OX = 250.0
GE_PLAN_OY = 450.0
GE_ELEV_OX = 250.0
GE_ELEV_OY = 150.0
GE_SIDE_OX = 250.0
GE_SIDE_OY = 150.0
PDF_PLAN_OX = 50.0
PDF_PLAN_OY = 580.0
PDF_ELEV_OX = 50.0
PDF_ELEV_OY = 180.0
PDF_SIDE_OX = 370.0
PDF_SIDE_OY = 180.0
# --- Draw Plan View ---
for line in geom_data.get("plan", {}).get("lines", []):
x0 = (line["start"][0] - GE_PLAN_OX) * draw_scale + PDF_PLAN_OX
y0 = (line["start"][1] - GE_PLAN_OY) * draw_scale + PDF_PLAN_OY
x1 = (line["end"][0] - GE_PLAN_OX) * draw_scale + PDF_PLAN_OX
y1 = (line["end"][1] - GE_PLAN_OY) * draw_scale + PDF_PLAN_OY
c.saveState()
c.setStrokeColor(NAVY if line.get("layer") == "WALLS" else colors.black)
c.setLineWidth(1.5 if line.get("layer") == "WALLS" else 0.5)
if line.get("style") == "dashed":
c.setDash([2, 2])
c.line(x0, y0, x1, y1)
c.restoreState()
for block in geom_data.get("plan", {}).get("blocks", []):
x, y, w, h = block["coords"]
x_new = (x - GE_PLAN_OX) * draw_scale + PDF_PLAN_OX
y_new = (y - GE_PLAN_OY) * draw_scale + PDF_PLAN_OY
w_new = w * draw_scale
h_new = h * draw_scale
c.saveState()
c.setStrokeColor(colors.black)
c.setFillColor(colors.white)
if block.get("style") == "dashed":
c.setDash([2, 2])
c.rect(x_new, y_new, w_new, h_new, fill=1, stroke=1)
c.restoreState()
for txt in geom_data.get("plan", {}).get("texts", []):
pos_x = (txt["pos"][0] - GE_PLAN_OX) * draw_scale + PDF_PLAN_OX
pos_y = (txt["pos"][1] - GE_PLAN_OY) * draw_scale + PDF_PLAN_OY
text_str = txt["text"]
c.saveState()
c.setFont(_FONT_REG, max(4.0, txt.get("size", 5.0) * draw_scale))
c.setFillColor(colors.black)
lines = text_str.split('\n')
for i, line_text in enumerate(lines):
c.drawCentredString(pos_x, pos_y - i * (max(4.0, txt.get("size", 5.0) * draw_scale) + 1), line_text)
c.restoreState()
for dim in geom_data.get("plan", {}).get("dimensions", []):
x0 = (dim["start"][0] - GE_PLAN_OX) * draw_scale + PDF_PLAN_OX
y0 = (dim["start"][1] - GE_PLAN_OY) * draw_scale + PDF_PLAN_OY
x1 = (dim["end"][0] - GE_PLAN_OX) * draw_scale + PDF_PLAN_OX
y1 = (dim["end"][1] - GE_PLAN_OY) * draw_scale + PDF_PLAN_OY
text_str = dim["text"]
c.saveState()
c.setStrokeColor(PENCIL_MEDIUM)
c.setLineWidth(0.5)
c.line(x0, y0, x1, y1)
c.line(x0, y0 - 3, x0, y0 + 3)
c.line(x1, y1 - 3, x1, y1 + 3)
c.setFont(_FONT_REG, 5.0)
c.setFillColor(PENCIL_MEDIUM)
c.drawCentredString((x0 + x1) / 2, (y0 + y1) / 2 + 4, text_str)
c.restoreState()
# --- Draw Elevation View ---
for line in geom_data.get("elevation", {}).get("lines", []):
x0 = (line["start"][0] - GE_ELEV_OX) * draw_scale + PDF_ELEV_OX
y0 = (line["start"][1] - GE_ELEV_OY) * draw_scale + PDF_ELEV_OY
x1 = (line["end"][0] - GE_ELEV_OX) * draw_scale + PDF_ELEV_OX
y1 = (line["end"][1] - GE_ELEV_OY) * draw_scale + PDF_ELEV_OY
c.saveState()
c.setStrokeColor(NAVY if line.get("layer") in ("GROUND", "CEILING") else colors.black)
c.setLineWidth(1.0 if line.get("layer") in ("GROUND", "CEILING") else 0.5)
if line.get("style") == "dashed":
c.setDash([2, 2])
c.line(x0, y0, x1, y1)
c.restoreState()
for block in geom_data.get("elevation", {}).get("blocks", []):
x, y, w, h = block["coords"]
x_new = (x - GE_ELEV_OX) * draw_scale + PDF_ELEV_OX
y_new = (y - GE_ELEV_OY) * draw_scale + PDF_ELEV_OY
w_new = w * draw_scale
h_new = h * draw_scale
c.saveState()
c.setStrokeColor(colors.black)
c.setFillColor(colors.white)
if block.get("style") == "dashed":
c.setDash([2, 2])
c.rect(x_new, y_new, w_new, h_new, fill=1, stroke=1)
c.restoreState()
for txt in geom_data.get("elevation", {}).get("texts", []):
pos_x = (txt["pos"][0] - GE_ELEV_OX) * draw_scale + PDF_ELEV_OX
pos_y = (txt["pos"][1] - GE_ELEV_OY) * draw_scale + PDF_ELEV_OY
text_str = txt["text"]
c.saveState()
c.setFont(_FONT_REG, max(4.0, txt.get("size", 5.0) * draw_scale))
c.setFillColor(colors.black)
lines = text_str.split('\n')
for i, line_text in enumerate(lines):
c.drawCentredString(pos_x, pos_y - i * (max(4.0, txt.get("size", 5.0) * draw_scale) + 1), line_text)
c.restoreState()
for dim in geom_data.get("elevation", {}).get("dimensions", []):
x0 = (dim["start"][0] - GE_ELEV_OX) * draw_scale + PDF_ELEV_OX
y0 = (dim["start"][1] - GE_ELEV_OY) * draw_scale + PDF_ELEV_OY
x1 = (dim["end"][0] - GE_ELEV_OX) * draw_scale + PDF_ELEV_OX
y1 = (dim["end"][1] - GE_ELEV_OY) * draw_scale + PDF_ELEV_OY
text_str = dim["text"]
c.saveState()
c.setStrokeColor(PENCIL_MEDIUM)
c.setLineWidth(0.5)
c.line(x0, y0, x1, y1)
c.line(x0 - 3, y0, x0 + 3, y0)
c.line(x1 - 3, y1, x1 + 3, y1)
c.setFont(_FONT_REG, 5.0)
c.setFillColor(PENCIL_MEDIUM)
c.drawCentredString((x0 + x1) / 2, (y0 + y1) / 2 + 4, text_str)
c.restoreState()
# --- Draw Side View (Section) ---
for line in geom_data.get("side", {}).get("lines", []):
x0 = (line["start"][0] - GE_SIDE_OX) * draw_scale + PDF_SIDE_OX
y0 = (line["start"][1] - GE_SIDE_OY) * draw_scale + PDF_SIDE_OY
x1 = (line["end"][0] - GE_SIDE_OX) * draw_scale + PDF_SIDE_OX
y1 = (line["end"][1] - GE_SIDE_OY) * draw_scale + PDF_SIDE_OY
c.saveState()
c.setStrokeColor(NAVY if line.get("layer") in ("GROUND", "CEILING", "WALLS") else colors.black)
c.setLineWidth(1.0 if line.get("layer") in ("GROUND", "CEILING", "WALLS") else 0.5)
if line.get("style") == "dashed":
c.setDash([2, 2])
c.line(x0, y0, x1, y1)
c.restoreState()
for block in geom_data.get("side", {}).get("blocks", []):
x, y, w, h = block["coords"]
x_new = (x - GE_SIDE_OX) * draw_scale + PDF_SIDE_OX
y_new = (y - GE_SIDE_OY) * draw_scale + PDF_SIDE_OY
w_new = w * draw_scale
h_new = h * draw_scale
c.saveState()
c.setStrokeColor(colors.black)
c.setFillColor(colors.white)
if block.get("style") == "dashed":
c.setDash([2, 2])
c.rect(x_new, y_new, w_new, h_new, fill=1, stroke=1)
c.restoreState()
for txt in geom_data.get("side", {}).get("texts", []):
pos_x = (txt["pos"][0] - GE_SIDE_OX) * draw_scale + PDF_SIDE_OX
pos_y = (txt["pos"][1] - GE_SIDE_OY) * draw_scale + PDF_SIDE_OY
text_str = txt["text"]
c.saveState()
c.setFont(_FONT_REG, max(4.0, txt.get("size", 5.0) * draw_scale))
c.setFillColor(colors.black)
lines = text_str.split('\n')
for i, line_text in enumerate(lines):
c.drawCentredString(pos_x, pos_y - i * (max(4.0, txt.get("size", 5.0) * draw_scale) + 1), line_text)
c.restoreState()
for dim in geom_data.get("side", {}).get("dimensions", []):
x0 = (dim["start"][0] - GE_SIDE_OX) * draw_scale + PDF_SIDE_OX
y0 = (dim["start"][1] - GE_SIDE_OY) * draw_scale + PDF_SIDE_OY
x1 = (dim["end"][0] - GE_SIDE_OX) * draw_scale + PDF_SIDE_OX
y1 = (dim["end"][1] - GE_SIDE_OY) * draw_scale + PDF_SIDE_OY
text_str = dim["text"]
c.saveState()
c.setStrokeColor(PENCIL_MEDIUM)
c.setLineWidth(0.5)
c.line(x0, y0, x1, y1)
if abs(x0 - x1) < 0.1: # Vertical dimension
c.line(x0 - 3, y0, x0 + 3, y0)
c.line(x1 - 3, y1, x1 + 3, y1)
c.setFont(_FONT_REG, 4.5)
c.setFillColor(PENCIL_MEDIUM)
c.drawRightString(x0 - 4, (y0 + y1) / 2 - 1.5, text_str)
else: # Horizontal dimension
c.line(x0, y0 - 3, x0, y0 + 3)
c.line(x1, y1 - 3, x1, y1 + 3)
c.setFont(_FONT_REG, 4.5)
c.setFillColor(PENCIL_MEDIUM)
c.drawCentredString((x0 + x1) / 2, (y0 + y1) / 2 + 4, text_str)
c.restoreState()
# Draw labels
c.saveState()
c.setFont(_FONT_BOLD, 8)
c.setFillColor(NAVY)
plan_w = wall_length_inches * 4.0 * draw_scale
c.drawCentredString(PDF_PLAN_OX + plan_w / 2, PDF_PLAN_OY - 35, "COUNTERTOP PLAN VIEW")
c.drawCentredString(PDF_ELEV_OX + plan_w / 2, PDF_ELEV_OY - 20, "FRONT ELEVATION VIEW")
c.drawCentredString(PDF_SIDE_OX + 30.0 * 4.0 * draw_scale / 2, PDF_SIDE_OY - 20, "SIDE SECTION VIEW")
c.restoreState()
# --- Draw Cabinet Schedule Table on the Right ---
c.setFont(_FONT_REG, 8)
c.setFillColor(colors.black)
labels = [
@@ -364,22 +1001,21 @@ def _draw_unit_page(c: canvas.Canvas, config: dict, unit_type: str, schedule,
y = DA_T - 30
for label, val in labels:
c.setFont(_FONT_BOLD, 7)
c.drawString(DA_L + 4, y, label)
c.drawString(490.0, y, label)
c.setFont(_FONT_REG, 7)
c.drawString(DA_L + 55, y, val)
c.drawString(550.0, y, val)
y -= 10
# Cabinet table
col_widths = [25, 60, 180, 70, 40, 40, 40, 30, 60, 110]
headers = ["#", "Code", "Description", "Type",
"W(in)", "H(in)", "D(in)", "Qty", "Elev.", "Location"]
table_x = DA_L + 4
table_x = 490.0
table_y = y - 8
# Header row
c.setFillColor(NAVY)
c.setFillColor(LTGRAY)
c.rect(table_x, table_y - 12, sum(col_widths), 12, fill=1, stroke=0)
c.setFillColor(WHITE)
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 6.5)
x_pos = table_x
for w, h in zip(col_widths, headers):
@@ -402,9 +1038,8 @@ def _draw_unit_page(c: canvas.Canvas, config: dict, unit_type: str, schedule,
def draw_section(label, cabs, start_y):
y = start_y
# Section label
y -= 14
c.setFillColor(LTBLUE)
c.setFillColor(LTGRAY)
c.rect(table_x, y, sum(col_widths), 11, fill=1, stroke=0)
c.setFillColor(NAVY)
c.setFont(_FONT_BOLD, 7)
@@ -417,7 +1052,7 @@ def _draw_unit_page(c: canvas.Canvas, config: dict, unit_type: str, schedule,
for item_num, cab in enumerate(cabs, 1):
y -= 12
if y < MARGIN + 20:
break # Don't overflow page
break
if alt:
c.setFillColor(LTGRAY)
+2 -1
View File
@@ -1,5 +1,6 @@
import fitz
import sys
sys.stdout.reconfigure(encoding="utf-8")
import fitz
def inspect_pdf(path, label):
print(f"\n{'='*65}")
Binary file not shown.
File diff suppressed because it is too large Load Diff
Binary file not shown.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -9,388 +9,6 @@
"Requires review: avg confidence 0.89 < 0.9"
],
"elevations": [
{
"elevation_label": "BATH",
"unit_type": "A1",
"is_ada": false,
"auto_approved": false,
"avg_confidence": 0.75,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "vanity",
"width_mm": 1880.0,
"height_mm": 870.0,
"depth_mm": 530.0,
"location": "Bathroom, left wall",
"elevation_ref": "A-6.00A",
"confidence": 0.8,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from 6'-2\" dimension for the counter, assuming a standard vanity depth.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "linen",
"width_mm": 600.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Bathroom, right of vanity",
"elevation_ref": "A-6.00A",
"confidence": 0.7,
"quantity": 1,
"is_ada": false,
"notes": "Labeled 'LN.', assuming standard pantry/linen dimensions.",
"source": "gemini"
}
]
},
{
"elevation_label": "KITCHEN",
"unit_type": "A1",
"is_ada": false,
"auto_approved": false,
"avg_confidence": 0.8863636363636364,
"review_flags": [
"Requires review: avg confidence 0.89 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 900.0,
"depth_mm": 600.0,
"location": "Kitchen, left side",
"elevation_ref": "KITCHEN",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Refrigerator space, estimated width from typical appliance sizes.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "base",
"width_mm": 762.0,
"height_mm": 720.0,
"depth_mm": 600.0,
"location": "Kitchen, left of sink",
"elevation_ref": "KITCHEN",
"confidence": 0.8,
"quantity": 1,
"is_ada": false,
"notes": "Estimated width based on visual proportion.",
"source": "gemini"
},
{
"item_num": 3,
"cabinet_type": "sink_base",
"width_mm": 900.0,
"height_mm": 720.0,
"depth_mm": 600.0,
"location": "Kitchen, under sink",
"elevation_ref": "KITCHEN",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "Estimated width based on sink size.",
"source": "gemini"
},
{
"item_num": 4,
"cabinet_type": "dw_adjacent",
"width_mm": 600.0,
"height_mm": 720.0,
"depth_mm": 600.0,
"location": "Kitchen, right of sink",
"elevation_ref": "KITCHEN",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Space for dishwasher, cabinet adjacent to it.",
"source": "gemini"
},
{
"item_num": 5,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 900.0,
"depth_mm": 600.0,
"location": "Kitchen, right side",
"elevation_ref": "KITCHEN",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Range space, estimated width from typical appliance sizes.",
"source": "gemini"
},
{
"item_num": 6,
"cabinet_type": "upper_wall",
"width_mm": 762.0,
"height_mm": 720.0,
"depth_mm": 330.0,
"location": "Kitchen, above left base cabinet",
"elevation_ref": "KITCHEN",
"confidence": 0.8,
"quantity": 1,
"is_ada": false,
"notes": "Estimated width based on base cabinet below.",
"source": "gemini"
},
{
"item_num": 7,
"cabinet_type": "upper_wall",
"width_mm": 900.0,
"height_mm": 720.0,
"depth_mm": 330.0,
"location": "Kitchen, above sink",
"elevation_ref": "KITCHEN",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Estimated width based on sink base below.",
"source": "gemini"
},
{
"item_num": 8,
"cabinet_type": "upper_wall",
"width_mm": 600.0,
"height_mm": 720.0,
"depth_mm": 330.0,
"location": "Kitchen, above dishwasher space",
"elevation_ref": "KITCHEN",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Estimated width based on dishwasher space below.",
"source": "gemini"
},
{
"item_num": 9,
"cabinet_type": "microwave_shelf",
"width_mm": 762.0,
"height_mm": 380.0,
"depth_mm": 330.0,
"location": "Kitchen, above range",
"elevation_ref": "KITCHEN",
"confidence": 0.85,
"quantity": 1,
"is_ada": false,
"notes": "Space for microwave above range, estimated width.",
"source": "gemini"
},
{
"item_num": 10,
"cabinet_type": "linen",
"width_mm": 600.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Bathroom, labeled 'LN.'",
"elevation_ref": "BATHROOM",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "Labeled 'LN.', assumed standard pantry/linen depth.",
"source": "gemini"
},
{
"item_num": 11,
"cabinet_type": "vanity",
"width_mm": 900.0,
"height_mm": 870.0,
"depth_mm": 530.0,
"location": "Bathroom, under sink",
"elevation_ref": "BATHROOM",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Estimated width based on typical vanity sizes.",
"source": "gemini"
}
]
},
{
"elevation_label": "BATH",
"unit_type": "A1",
"is_ada": false,
"auto_approved": true,
"avg_confidence": 0.9,
"review_flags": [],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 864.0,
"depth_mm": 600.0,
"location": "Kitchen, under range",
"elevation_ref": "UNIT A1 KITCHEN PLAN",
"confidence": 0.95,
"quantity": 1,
"is_ada": true,
"notes": "Range appliance space, 30x48 clear area indicated. Assuming ADA height for base cabinets.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "sink_base",
"width_mm": 900.0,
"height_mm": 864.0,
"depth_mm": 600.0,
"location": "Kitchen, under sink",
"elevation_ref": "UNIT A1 KITCHEN PLAN",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Sink base cabinet, 30x48 clear area indicated. Width estimated from drawing, assuming ADA height for base cabinets.",
"source": "gemini"
},
{
"item_num": 3,
"cabinet_type": "appliance_space",
"width_mm": 600.0,
"height_mm": 864.0,
"depth_mm": 600.0,
"location": "Kitchen, under DW",
"elevation_ref": "UNIT A1 KITCHEN PLAN",
"confidence": 0.95,
"quantity": 1,
"is_ada": true,
"notes": "Dishwasher appliance space, 30x48 clear area indicated. 24\" (MAX) width noted. Assuming ADA height for base cabinets.",
"source": "gemini"
},
{
"item_num": 4,
"cabinet_type": "base",
"width_mm": 450.0,
"height_mm": 864.0,
"depth_mm": 600.0,
"location": "Kitchen, right of DW",
"elevation_ref": "UNIT A1 KITCHEN PLAN",
"confidence": 0.8,
"quantity": 1,
"is_ada": true,
"notes": "Base cabinet, width estimated from drawing. Assuming ADA height for base cabinets.",
"source": "gemini"
},
{
"item_num": 5,
"cabinet_type": "appliance_space",
"width_mm": 900.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Kitchen, Refrigerator",
"elevation_ref": "UNIT A1 KITCHEN PLAN",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "Refrigerator appliance space. Width estimated from 3'-0\" dimension. Height assumed as standard pantry height.",
"source": "gemini"
},
{
"item_num": 6,
"cabinet_type": "pantry",
"width_mm": 600.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Kitchen, right of Refrigerator",
"elevation_ref": "UNIT A1 KITCHEN PLAN",
"confidence": 0.85,
"quantity": 1,
"is_ada": false,
"notes": "Pantry cabinet. Width estimated from drawing. Height assumed as standard pantry height.",
"source": "gemini"
},
{
"item_num": 7,
"cabinet_type": "vanity",
"width_mm": 762.0,
"height_mm": 870.0,
"depth_mm": 530.0,
"location": "Bathroom",
"elevation_ref": "BATHROOM",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Bathroom vanity. Width estimated from 2'-6\" (30\") dimension. Standard vanity height and depth.",
"source": "gemini"
}
]
},
{
"elevation_label": "VANITY",
"unit_type": "A1",
"is_ada": false,
"auto_approved": false,
"avg_confidence": 0.875,
"review_flags": [
"Requires review: avg confidence 0.88 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "pantry",
"width_mm": 305.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "U9, General Notes",
"elevation_ref": "General Notes",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "12\" Width x 24\" Depth Pantry. Assumed standard pantry height.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "linen",
"width_mm": 305.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "U14, General Notes",
"elevation_ref": "General Notes",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "12\" Width x 24\" Depth Linen Cabinet. Assumed standard pantry height for linen cabinet.",
"source": "gemini"
},
{
"item_num": 3,
"cabinet_type": "vanity",
"width_mm": 762.0,
"height_mm": 870.0,
"depth_mm": 530.0,
"location": "U20, General Notes",
"elevation_ref": "General Notes",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Vanity cabinet. Refer to A-6.06, FHA Bathroom Fixture Legend, #5. Assumed 30\" width based on common vanity sizes and ADA/FHA context. Height based on 36\" high counter (U6) minus countertop thickness, and ADA requirements.",
"source": "gemini"
},
{
"item_num": 4,
"cabinet_type": "medicine_cabinet",
"width_mm": 762.0,
"height_mm": 720.0,
"depth_mm": 130.0,
"location": "U8, General Notes",
"elevation_ref": "General Notes",
"confidence": 0.7,
"quantity": 1,
"is_ada": true,
"notes": "Mirror match width of vanity. Assumed standard medicine cabinet height and depth. Width matches assumed vanity width.",
"source": "gemini"
}
]
},
{
"elevation_label": "KITCHEN",
"unit_type": "A1",
@@ -530,25 +148,41 @@
]
},
{
"elevation_label": "ELEVATION_B",
"elevation_label": "BATHROOM",
"unit_type": "A1",
"is_ada": false,
"auto_approved": true,
"avg_confidence": 0.9,
"review_flags": [],
"auto_approved": false,
"avg_confidence": 0.75,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "vanity",
"width_mm": 900.0,
"width_mm": 1880.0,
"height_mm": 870.0,
"depth_mm": 530.0,
"location": "U20, FHA Bathroom Fixture Legend, #5",
"elevation_ref": "ELEVATION_B",
"confidence": 0.9,
"location": "Bathroom, left wall",
"elevation_ref": "A-6.00A",
"confidence": 0.8,
"quantity": 1,
"is_ada": false,
"notes": "Based on U20 description 'VANITY CABINET'.",
"notes": "Width estimated from 6'-2\" dimension for the counter, assuming a standard vanity depth.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "linen",
"width_mm": 600.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Bathroom, right of vanity",
"elevation_ref": "A-6.00A",
"confidence": 0.7,
"quantity": 1,
"is_ada": false,
"notes": "Labeled 'LN.', assuming standard pantry/linen dimensions.",
"source": "gemini"
}
]
@@ -0,0 +1,191 @@
{
"unit_type": "A2-ADA",
"is_ada": true,
"auto_approved": false,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9",
"Requires review: avg confidence 0.89 < 0.9",
"Requires review: avg confidence 0.88 < 0.9",
"Requires review: avg confidence 0.89 < 0.9"
],
"elevations": [
{
"elevation_label": "KITCHEN",
"unit_type": "A2-ADA",
"is_ada": true,
"auto_approved": false,
"avg_confidence": 0.8944444444444445,
"review_flags": [
"Requires review: avg confidence 0.89 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "upper_wall",
"width_mm": 900,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Left of microwave shelf, top row, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, 3'-0\" dimension",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "microwave_shelf",
"width_mm": 762.0,
"height_mm": 380.0,
"depth_mm": 330.0,
"location": "Above range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, 2'-6\" range space below",
"source": "gemini"
},
{
"item_num": 3,
"cabinet_type": "upper_wall",
"width_mm": 762.0,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Right of microwave shelf, top row, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, similar to item 1",
"source": "gemini"
},
{
"item_num": 4,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 900.0,
"depth_mm": 600.0,
"location": "Range space, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.95,
"quantity": 1,
"is_ada": true,
"notes": "Space for 'FULL SIZE RANGE' (U4)",
"source": "gemini"
},
{
"item_num": 5,
"cabinet_type": "base",
"width_mm": 900,
"height_mm": 864.0,
"depth_mm": 600.0,
"location": "Left of range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, 3'-0\" dimension",
"source": "gemini"
},
{
"item_num": 6,
"cabinet_type": "base",
"width_mm": 762.0,
"height_mm": 864.0,
"depth_mm": 600.0,
"location": "Right of range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, similar to item 2",
"source": "gemini"
},
{
"item_num": 7,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 1700.0,
"depth_mm": 600.0,
"location": "Refrigerator space, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.95,
"quantity": 1,
"is_ada": true,
"notes": "Space for 'REF.' (Refrigerator)",
"source": "gemini"
},
{
"item_num": 8,
"cabinet_type": "pantry",
"width_mm": 300.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Right of refrigerator, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.8,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated, height 7'-6\" (2286mm) from drawing, depth 'CABINET OVER REF. TO BE 24\" DEPTH' implies 24\" depth for tall cabinets as well. U9 indicates 12\" width, 24\" depth, which could be this cabinet.",
"source": "gemini"
},
{
"item_num": 9,
"cabinet_type": "upper_wall",
"width_mm": 900,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Left of refrigerator, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.85,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, 3'-0\" dimension. Height estimated to match adjacent upper cabinets.",
"source": "gemini"
}
]
},
{
"elevation_label": "BATHROOM",
"unit_type": "A2-ADA",
"is_ada": true,
"auto_approved": false,
"avg_confidence": 0.75,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "vanity",
"width_mm": 1880.0,
"height_mm": 864.0,
"depth_mm": 530.0,
"location": "Bathroom, left wall",
"elevation_ref": "A-6.00A",
"confidence": 0.8,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from 6'-2\" dimension for the counter, assuming a standard vanity depth.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "linen",
"width_mm": 600.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Bathroom, right of vanity",
"elevation_ref": "A-6.00A",
"confidence": 0.7,
"quantity": 1,
"is_ada": true,
"notes": "Labeled 'LN.', assuming standard pantry/linen dimensions.",
"source": "gemini"
}
]
}
]
}
@@ -0,0 +1,191 @@
{
"unit_type": "A3",
"is_ada": false,
"auto_approved": false,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9",
"Requires review: avg confidence 0.89 < 0.9",
"Requires review: avg confidence 0.88 < 0.9",
"Requires review: avg confidence 0.89 < 0.9"
],
"elevations": [
{
"elevation_label": "KITCHEN",
"unit_type": "A3",
"is_ada": false,
"auto_approved": false,
"avg_confidence": 0.8944444444444445,
"review_flags": [
"Requires review: avg confidence 0.89 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "upper_wall",
"width_mm": 900,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Left of microwave shelf, top row, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, 3'-0\" dimension",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "microwave_shelf",
"width_mm": 762.0,
"height_mm": 380.0,
"depth_mm": 330.0,
"location": "Above range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, 2'-6\" range space below",
"source": "gemini"
},
{
"item_num": 3,
"cabinet_type": "upper_wall",
"width_mm": 762.0,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Right of microwave shelf, top row, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, similar to item 1",
"source": "gemini"
},
{
"item_num": 4,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 900.0,
"depth_mm": 600.0,
"location": "Range space, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "Space for 'FULL SIZE RANGE' (U4)",
"source": "gemini"
},
{
"item_num": 5,
"cabinet_type": "base",
"width_mm": 900,
"height_mm": 720.0,
"depth_mm": 600.0,
"location": "Left of range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, 3'-0\" dimension",
"source": "gemini"
},
{
"item_num": 6,
"cabinet_type": "base",
"width_mm": 762.0,
"height_mm": 720.0,
"depth_mm": 600.0,
"location": "Right of range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, similar to item 2",
"source": "gemini"
},
{
"item_num": 7,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 1700.0,
"depth_mm": 600.0,
"location": "Refrigerator space, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "Space for 'REF.' (Refrigerator)",
"source": "gemini"
},
{
"item_num": 8,
"cabinet_type": "pantry",
"width_mm": 300.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Right of refrigerator, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.8,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated, height 7'-6\" (2286mm) from drawing, depth 'CABINET OVER REF. TO BE 24\" DEPTH' implies 24\" depth for tall cabinets as well. U9 indicates 12\" width, 24\" depth, which could be this cabinet.",
"source": "gemini"
},
{
"item_num": 9,
"cabinet_type": "upper_wall",
"width_mm": 900,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Left of refrigerator, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.85,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, 3'-0\" dimension. Height estimated to match adjacent upper cabinets.",
"source": "gemini"
}
]
},
{
"elevation_label": "BATHROOM",
"unit_type": "A3",
"is_ada": false,
"auto_approved": false,
"avg_confidence": 0.75,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "vanity",
"width_mm": 1880.0,
"height_mm": 870.0,
"depth_mm": 530.0,
"location": "Bathroom, left wall",
"elevation_ref": "A-6.00A",
"confidence": 0.8,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from 6'-2\" dimension for the counter, assuming a standard vanity depth.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "linen",
"width_mm": 600.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Bathroom, right of vanity",
"elevation_ref": "A-6.00A",
"confidence": 0.7,
"quantity": 1,
"is_ada": false,
"notes": "Labeled 'LN.', assuming standard pantry/linen dimensions.",
"source": "gemini"
}
]
}
]
}
@@ -0,0 +1,191 @@
{
"unit_type": "B1",
"is_ada": false,
"auto_approved": false,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9",
"Requires review: avg confidence 0.89 < 0.9",
"Requires review: avg confidence 0.88 < 0.9",
"Requires review: avg confidence 0.89 < 0.9"
],
"elevations": [
{
"elevation_label": "KITCHEN",
"unit_type": "B1",
"is_ada": false,
"auto_approved": false,
"avg_confidence": 0.8944444444444445,
"review_flags": [
"Requires review: avg confidence 0.89 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "upper_wall",
"width_mm": 900,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Left of microwave shelf, top row, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, 3'-0\" dimension",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "microwave_shelf",
"width_mm": 762.0,
"height_mm": 380.0,
"depth_mm": 330.0,
"location": "Above range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, 2'-6\" range space below",
"source": "gemini"
},
{
"item_num": 3,
"cabinet_type": "upper_wall",
"width_mm": 762.0,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Right of microwave shelf, top row, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, similar to item 1",
"source": "gemini"
},
{
"item_num": 4,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 900.0,
"depth_mm": 600.0,
"location": "Range space, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "Space for 'FULL SIZE RANGE' (U4)",
"source": "gemini"
},
{
"item_num": 5,
"cabinet_type": "base",
"width_mm": 900,
"height_mm": 720.0,
"depth_mm": 600.0,
"location": "Left of range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, 3'-0\" dimension",
"source": "gemini"
},
{
"item_num": 6,
"cabinet_type": "base",
"width_mm": 762.0,
"height_mm": 720.0,
"depth_mm": 600.0,
"location": "Right of range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, similar to item 2",
"source": "gemini"
},
{
"item_num": 7,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 1700.0,
"depth_mm": 600.0,
"location": "Refrigerator space, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.95,
"quantity": 1,
"is_ada": false,
"notes": "Space for 'REF.' (Refrigerator)",
"source": "gemini"
},
{
"item_num": 8,
"cabinet_type": "pantry",
"width_mm": 300.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Right of refrigerator, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.8,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated, height 7'-6\" (2286mm) from drawing, depth 'CABINET OVER REF. TO BE 24\" DEPTH' implies 24\" depth for tall cabinets as well. U9 indicates 12\" width, 24\" depth, which could be this cabinet.",
"source": "gemini"
},
{
"item_num": 9,
"cabinet_type": "upper_wall",
"width_mm": 900,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Left of refrigerator, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.85,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from drawing, 3'-0\" dimension. Height estimated to match adjacent upper cabinets.",
"source": "gemini"
}
]
},
{
"elevation_label": "BATHROOM",
"unit_type": "B1",
"is_ada": false,
"auto_approved": false,
"avg_confidence": 0.75,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "vanity",
"width_mm": 1880.0,
"height_mm": 870.0,
"depth_mm": 530.0,
"location": "Bathroom, left wall",
"elevation_ref": "A-6.00A",
"confidence": 0.8,
"quantity": 1,
"is_ada": false,
"notes": "Width estimated from 6'-2\" dimension for the counter, assuming a standard vanity depth.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "linen",
"width_mm": 600.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Bathroom, right of vanity",
"elevation_ref": "A-6.00A",
"confidence": 0.7,
"quantity": 1,
"is_ada": false,
"notes": "Labeled 'LN.', assuming standard pantry/linen dimensions.",
"source": "gemini"
}
]
}
]
}
@@ -0,0 +1,191 @@
{
"unit_type": "B2-ADA",
"is_ada": true,
"auto_approved": false,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9",
"Requires review: avg confidence 0.89 < 0.9",
"Requires review: avg confidence 0.88 < 0.9",
"Requires review: avg confidence 0.89 < 0.9"
],
"elevations": [
{
"elevation_label": "KITCHEN",
"unit_type": "B2-ADA",
"is_ada": true,
"auto_approved": false,
"avg_confidence": 0.8944444444444445,
"review_flags": [
"Requires review: avg confidence 0.89 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "upper_wall",
"width_mm": 900,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Left of microwave shelf, top row, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, 3'-0\" dimension",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "microwave_shelf",
"width_mm": 762.0,
"height_mm": 380.0,
"depth_mm": 330.0,
"location": "Above range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, 2'-6\" range space below",
"source": "gemini"
},
{
"item_num": 3,
"cabinet_type": "upper_wall",
"width_mm": 762.0,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Right of microwave shelf, top row, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, similar to item 1",
"source": "gemini"
},
{
"item_num": 4,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 900.0,
"depth_mm": 600.0,
"location": "Range space, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.95,
"quantity": 1,
"is_ada": true,
"notes": "Space for 'FULL SIZE RANGE' (U4)",
"source": "gemini"
},
{
"item_num": 5,
"cabinet_type": "base",
"width_mm": 900,
"height_mm": 864.0,
"depth_mm": 600.0,
"location": "Left of range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, 3'-0\" dimension",
"source": "gemini"
},
{
"item_num": 6,
"cabinet_type": "base",
"width_mm": 762.0,
"height_mm": 864.0,
"depth_mm": 600.0,
"location": "Right of range, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.9,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, similar to item 2",
"source": "gemini"
},
{
"item_num": 7,
"cabinet_type": "appliance_space",
"width_mm": 762.0,
"height_mm": 1700.0,
"depth_mm": 600.0,
"location": "Refrigerator space, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.95,
"quantity": 1,
"is_ada": true,
"notes": "Space for 'REF.' (Refrigerator)",
"source": "gemini"
},
{
"item_num": 8,
"cabinet_type": "pantry",
"width_mm": 300.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Right of refrigerator, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.8,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated, height 7'-6\" (2286mm) from drawing, depth 'CABINET OVER REF. TO BE 24\" DEPTH' implies 24\" depth for tall cabinets as well. U9 indicates 12\" width, 24\" depth, which could be this cabinet.",
"source": "gemini"
},
{
"item_num": 9,
"cabinet_type": "upper_wall",
"width_mm": 900,
"height_mm": 762.0,
"depth_mm": 330.0,
"location": "Left of refrigerator, Elevation 1",
"elevation_ref": "UNIT A1 KITCHEN EL.",
"confidence": 0.85,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from drawing, 3'-0\" dimension. Height estimated to match adjacent upper cabinets.",
"source": "gemini"
}
]
},
{
"elevation_label": "BATHROOM",
"unit_type": "B2-ADA",
"is_ada": true,
"auto_approved": false,
"avg_confidence": 0.75,
"review_flags": [
"Requires review: avg confidence 0.75 < 0.9"
],
"cabinets": [
{
"item_num": 1,
"cabinet_type": "vanity",
"width_mm": 1880.0,
"height_mm": 864.0,
"depth_mm": 530.0,
"location": "Bathroom, left wall",
"elevation_ref": "A-6.00A",
"confidence": 0.8,
"quantity": 1,
"is_ada": true,
"notes": "Width estimated from 6'-2\" dimension for the counter, assuming a standard vanity depth.",
"source": "gemini"
},
{
"item_num": 2,
"cabinet_type": "linen",
"width_mm": 600.0,
"height_mm": 2130.0,
"depth_mm": 600.0,
"location": "Bathroom, right of vanity",
"elevation_ref": "A-6.00A",
"confidence": 0.7,
"quantity": 1,
"is_ada": true,
"notes": "Labeled 'LN.', assuming standard pantry/linen dimensions.",
"source": "gemini"
}
]
}
]
}
@@ -0,0 +1,234 @@
[
{
"unit_type": "A1",
"cabinets": [
{
"code": "B30",
"qty": 1
},
{
"code": "B35",
"qty": 1
},
{
"code": "LIN24",
"qty": 1
},
{
"code": "MW30-15",
"qty": 1
},
{
"code": "T12-84",
"qty": 1
},
{
"code": "VAN74",
"qty": 1
},
{
"code": "W30-30",
"qty": 1
},
{
"code": "W35-30",
"qty": 2
}
],
"countertop_lf": 11.6,
"upper_cabinet_lf": 10.8,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "medium"
},
{
"unit_type": "A2-ADA",
"cabinets": [
{
"code": "B30-ADA",
"qty": 1
},
{
"code": "B35-ADA",
"qty": 1
},
{
"code": "LIN24-ADA",
"qty": 1
},
{
"code": "MW30-15-ADA",
"qty": 1
},
{
"code": "T12-84-ADA",
"qty": 1
},
{
"code": "VAN74-ADA",
"qty": 1
},
{
"code": "W30-30-ADA",
"qty": 1
},
{
"code": "W35-30-ADA",
"qty": 2
}
],
"countertop_lf": 11.6,
"upper_cabinet_lf": 10.8,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"ADA",
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "A3",
"cabinets": [
{
"code": "B30",
"qty": 1
},
{
"code": "B35",
"qty": 1
},
{
"code": "LIN24",
"qty": 1
},
{
"code": "MW30-15",
"qty": 1
},
{
"code": "T12-84",
"qty": 1
},
{
"code": "VAN74",
"qty": 1
},
{
"code": "W30-30",
"qty": 1
},
{
"code": "W35-30",
"qty": 2
}
],
"countertop_lf": 11.6,
"upper_cabinet_lf": 10.8,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "medium"
},
{
"unit_type": "B1",
"cabinets": [
{
"code": "B30",
"qty": 1
},
{
"code": "B35",
"qty": 1
},
{
"code": "LIN24",
"qty": 1
},
{
"code": "MW30-15",
"qty": 1
},
{
"code": "T12-84",
"qty": 1
},
{
"code": "VAN74",
"qty": 1
},
{
"code": "W30-30",
"qty": 1
},
{
"code": "W35-30",
"qty": 2
}
],
"countertop_lf": 11.6,
"upper_cabinet_lf": 10.8,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "medium"
},
{
"unit_type": "B2-ADA",
"cabinets": [
{
"code": "B30-ADA",
"qty": 1
},
{
"code": "B35-ADA",
"qty": 1
},
{
"code": "LIN24-ADA",
"qty": 1
},
{
"code": "MW30-15-ADA",
"qty": 1
},
{
"code": "T12-84-ADA",
"qty": 1
},
{
"code": "VAN74-ADA",
"qty": 1
},
{
"code": "W30-30-ADA",
"qty": 1
},
{
"code": "W35-30-ADA",
"qty": 2
}
],
"countertop_lf": 11.6,
"upper_cabinet_lf": 10.8,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"ADA",
"Pantry"
],
"installation_complexity": "high"
}
]
@@ -0,0 +1,462 @@
[
{
"unit": "A1",
"kitchen_type": "K1",
"layout": "single_wall",
"ceiling_height": 108.0,
"walls": [
{
"name": "A",
"length": 137,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "B35",
"x": 30,
"width": 35,
"height": 28
},
{
"id": "B30",
"x": 65,
"width": 30,
"height": 28
},
{
"id": "T12-84",
"x": 125,
"width": 12,
"height": 84
},
{
"id": "W35-30",
"x": 0,
"width": 35,
"height": 30
},
{
"id": "MW30-15",
"x": 35,
"width": 30,
"height": 15
},
{
"id": "W30-30",
"x": 65,
"width": 30,
"height": 30
},
{
"id": "W35-30",
"x": 95,
"width": 35,
"height": 30
}
]
},
{
"name": "BATHROOM",
"length": 98,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "VAN74",
"x": 0,
"width": 74,
"height": 34
},
{
"id": "LIN24",
"x": 74,
"width": 24,
"height": 84
}
]
}
],
"appliances": [
{
"type": "RANGE",
"wall": "A",
"x": 0,
"width": 30
},
{
"type": "REF",
"wall": "A",
"x": 95,
"width": 30
}
]
},
{
"unit": "A2-ADA",
"kitchen_type": "K1",
"layout": "single_wall",
"ceiling_height": 108.0,
"walls": [
{
"name": "A",
"length": 137,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "B35-ADA",
"x": 30,
"width": 35,
"height": 34
},
{
"id": "B30-ADA",
"x": 65,
"width": 30,
"height": 34
},
{
"id": "T12-84-ADA",
"x": 125,
"width": 12,
"height": 84
},
{
"id": "W35-30-ADA",
"x": 0,
"width": 35,
"height": 30
},
{
"id": "MW30-15-ADA",
"x": 35,
"width": 30,
"height": 15
},
{
"id": "W30-30-ADA",
"x": 65,
"width": 30,
"height": 30
},
{
"id": "W35-30-ADA",
"x": 95,
"width": 35,
"height": 30
}
]
},
{
"name": "BATHROOM",
"length": 98,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "VAN74-ADA",
"x": 0,
"width": 74,
"height": 34
},
{
"id": "LIN24-ADA",
"x": 74,
"width": 24,
"height": 84
}
]
}
],
"appliances": [
{
"type": "RANGE",
"wall": "A",
"x": 0,
"width": 30
},
{
"type": "REF",
"wall": "A",
"x": 95,
"width": 30
}
]
},
{
"unit": "A3",
"kitchen_type": "K1",
"layout": "single_wall",
"ceiling_height": 108.0,
"walls": [
{
"name": "A",
"length": 137,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "B35",
"x": 30,
"width": 35,
"height": 28
},
{
"id": "B30",
"x": 65,
"width": 30,
"height": 28
},
{
"id": "T12-84",
"x": 125,
"width": 12,
"height": 84
},
{
"id": "W35-30",
"x": 0,
"width": 35,
"height": 30
},
{
"id": "MW30-15",
"x": 35,
"width": 30,
"height": 15
},
{
"id": "W30-30",
"x": 65,
"width": 30,
"height": 30
},
{
"id": "W35-30",
"x": 95,
"width": 35,
"height": 30
}
]
},
{
"name": "BATHROOM",
"length": 98,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "VAN74",
"x": 0,
"width": 74,
"height": 34
},
{
"id": "LIN24",
"x": 74,
"width": 24,
"height": 84
}
]
}
],
"appliances": [
{
"type": "RANGE",
"wall": "A",
"x": 0,
"width": 30
},
{
"type": "REF",
"wall": "A",
"x": 95,
"width": 30
}
]
},
{
"unit": "B1",
"kitchen_type": "K1",
"layout": "single_wall",
"ceiling_height": 108.0,
"walls": [
{
"name": "A",
"length": 137,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "B35",
"x": 30,
"width": 35,
"height": 28
},
{
"id": "B30",
"x": 65,
"width": 30,
"height": 28
},
{
"id": "T12-84",
"x": 125,
"width": 12,
"height": 84
},
{
"id": "W35-30",
"x": 0,
"width": 35,
"height": 30
},
{
"id": "MW30-15",
"x": 35,
"width": 30,
"height": 15
},
{
"id": "W30-30",
"x": 65,
"width": 30,
"height": 30
},
{
"id": "W35-30",
"x": 95,
"width": 35,
"height": 30
}
]
},
{
"name": "BATHROOM",
"length": 98,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "VAN74",
"x": 0,
"width": 74,
"height": 34
},
{
"id": "LIN24",
"x": 74,
"width": 24,
"height": 84
}
]
}
],
"appliances": [
{
"type": "RANGE",
"wall": "A",
"x": 0,
"width": 30
},
{
"type": "REF",
"wall": "A",
"x": 95,
"width": 30
}
]
},
{
"unit": "B2-ADA",
"kitchen_type": "K1",
"layout": "single_wall",
"ceiling_height": 108.0,
"walls": [
{
"name": "A",
"length": 137,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "B35-ADA",
"x": 30,
"width": 35,
"height": 34
},
{
"id": "B30-ADA",
"x": 65,
"width": 30,
"height": 34
},
{
"id": "T12-84-ADA",
"x": 125,
"width": 12,
"height": 84
},
{
"id": "W35-30-ADA",
"x": 0,
"width": 35,
"height": 30
},
{
"id": "MW30-15-ADA",
"x": 35,
"width": 30,
"height": 15
},
{
"id": "W30-30-ADA",
"x": 65,
"width": 30,
"height": 30
},
{
"id": "W35-30-ADA",
"x": 95,
"width": 35,
"height": 30
}
]
},
{
"name": "BATHROOM",
"length": 98,
"doors": [],
"windows": [],
"cabinets": [
{
"id": "VAN74-ADA",
"x": 0,
"width": 74,
"height": 34
},
{
"id": "LIN24-ADA",
"x": 74,
"width": 24,
"height": 84
}
]
}
],
"appliances": [
{
"type": "RANGE",
"wall": "A",
"x": 0,
"width": 30
},
{
"type": "REF",
"wall": "A",
"x": 95,
"width": 30
}
]
}
]
@@ -0,0 +1,128 @@
[
{
"building": "Building A",
"floor": 1,
"unit_type": "A1",
"count": 5,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building A",
"floor": 2,
"unit_type": "A1",
"count": 5,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building A",
"floor": 3,
"unit_type": "A1",
"count": 4,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building A",
"floor": 1,
"unit_type": "A2-ADA",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
},
{
"building": "Building A",
"floor": 2,
"unit_type": "A2-ADA",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
},
{
"building": "Building A",
"floor": 3,
"unit_type": "A2-ADA",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
},
{
"building": "Building A",
"floor": 1,
"unit_type": "A3",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building A",
"floor": 2,
"unit_type": "A3",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building A",
"floor": 1,
"unit_type": "B1",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building A",
"floor": 2,
"unit_type": "B1",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building A",
"floor": 3,
"unit_type": "B1",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building A",
"floor": 1,
"unit_type": "B2-ADA",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
},
{
"building": "Building A",
"floor": 2,
"unit_type": "B2-ADA",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
},
{
"building": "Building A",
"floor": 3,
"unit_type": "B2-ADA",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
}
]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,793 @@
[
{
"unit_type": "A-1",
"cabinets": [
{
"code": "B24",
"qty": 1
},
{
"code": "B36",
"qty": 2
},
{
"code": "LIN18",
"qty": 1
},
{
"code": "MED36",
"qty": 1
},
{
"code": "SB36",
"qty": 1
},
{
"code": "T15-84",
"qty": 1
},
{
"code": "VAN36",
"qty": 1
},
{
"code": "W30-18",
"qty": 1
},
{
"code": "W30-30",
"qty": 1
},
{
"code": "W36-30",
"qty": 2
}
],
"countertop_lf": 14.0,
"upper_cabinet_lf": 11.0,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "medium"
},
{
"unit_type": "A-1a ACC",
"cabinets": [
{
"code": "B24-ADA",
"qty": 1
},
{
"code": "B36-ADA",
"qty": 2
},
{
"code": "LIN18-ADA",
"qty": 1
},
{
"code": "MED36-ADA",
"qty": 1
},
{
"code": "SB36-ADA",
"qty": 1
},
{
"code": "T15-84-ADA",
"qty": 1
},
{
"code": "VAN36-ADA",
"qty": 1
},
{
"code": "W30-18-ADA",
"qty": 1
},
{
"code": "W30-30-ADA",
"qty": 1
},
{
"code": "W36-30-ADA",
"qty": 2
}
],
"countertop_lf": 14.0,
"upper_cabinet_lf": 11.0,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"ADA",
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "B-1",
"cabinets": [
{
"code": "B24",
"qty": 2
},
{
"code": "B36",
"qty": 2
},
{
"code": "LIN18",
"qty": 1
},
{
"code": "MED30",
"qty": 2
},
{
"code": "SB36",
"qty": 1
},
{
"code": "T15-84",
"qty": 1
},
{
"code": "VAN30",
"qty": 2
},
{
"code": "W30-18",
"qty": 1
},
{
"code": "W30-30",
"qty": 2
},
{
"code": "W36-30",
"qty": 2
}
],
"countertop_lf": 18.0,
"upper_cabinet_lf": 13.5,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "B-1a ACC",
"cabinets": [
{
"code": "B24-ADA",
"qty": 2
},
{
"code": "B36-ADA",
"qty": 2
},
{
"code": "LIN18-ADA",
"qty": 1
},
{
"code": "MED30-ADA",
"qty": 2
},
{
"code": "SB36-ADA",
"qty": 1
},
{
"code": "T15-84-ADA",
"qty": 1
},
{
"code": "VAN30-ADA",
"qty": 2
},
{
"code": "W30-18-ADA",
"qty": 1
},
{
"code": "W30-30-ADA",
"qty": 2
},
{
"code": "W36-30-ADA",
"qty": 2
}
],
"countertop_lf": 18.0,
"upper_cabinet_lf": 13.5,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"ADA",
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "C-1",
"cabinets": [
{
"code": "B24",
"qty": 1
},
{
"code": "B36",
"qty": 3
},
{
"code": "LIN18",
"qty": 1
},
{
"code": "MED30",
"qty": 1
},
{
"code": "MED36",
"qty": 1
},
{
"code": "SB36",
"qty": 1
},
{
"code": "T15-84",
"qty": 1
},
{
"code": "VAN30",
"qty": 1
},
{
"code": "VAN36",
"qty": 1
},
{
"code": "W30-18",
"qty": 1
},
{
"code": "W30-30",
"qty": 1
},
{
"code": "W36-30",
"qty": 3
}
],
"countertop_lf": 19.5,
"upper_cabinet_lf": 14.0,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "C-2",
"cabinets": [
{
"code": "B24",
"qty": 1
},
{
"code": "B36",
"qty": 3
},
{
"code": "LIN18",
"qty": 1
},
{
"code": "MED30",
"qty": 1
},
{
"code": "MED36",
"qty": 1
},
{
"code": "SB36",
"qty": 1
},
{
"code": "T15-84",
"qty": 1
},
{
"code": "VAN30",
"qty": 1
},
{
"code": "VAN36",
"qty": 1
},
{
"code": "W30-18",
"qty": 1
},
{
"code": "W30-30",
"qty": 1
},
{
"code": "W36-30",
"qty": 3
}
],
"countertop_lf": 19.5,
"upper_cabinet_lf": 14.0,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "C-2a ACC",
"cabinets": [
{
"code": "B24-ADA",
"qty": 1
},
{
"code": "B36-ADA",
"qty": 3
},
{
"code": "LIN18-ADA",
"qty": 1
},
{
"code": "MED30-ADA",
"qty": 1
},
{
"code": "MED36-ADA",
"qty": 1
},
{
"code": "SB36-ADA",
"qty": 1
},
{
"code": "T15-84-ADA",
"qty": 1
},
{
"code": "VAN30-ADA",
"qty": 1
},
{
"code": "VAN36-ADA",
"qty": 1
},
{
"code": "W30-18-ADA",
"qty": 1
},
{
"code": "W30-30-ADA",
"qty": 1
},
{
"code": "W36-30-ADA",
"qty": 3
}
],
"countertop_lf": 19.5,
"upper_cabinet_lf": 14.0,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"ADA",
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "C-3",
"cabinets": [
{
"code": "B24",
"qty": 1
},
{
"code": "B36",
"qty": 3
},
{
"code": "LIN18",
"qty": 1
},
{
"code": "MED30",
"qty": 1
},
{
"code": "MED36",
"qty": 1
},
{
"code": "SB36",
"qty": 1
},
{
"code": "T15-84",
"qty": 1
},
{
"code": "VAN30",
"qty": 1
},
{
"code": "VAN36",
"qty": 1
},
{
"code": "W30-18",
"qty": 1
},
{
"code": "W30-30",
"qty": 1
},
{
"code": "W36-30",
"qty": 3
}
],
"countertop_lf": 19.5,
"upper_cabinet_lf": 14.0,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "D-1N",
"cabinets": [
{
"code": "B24",
"qty": 1
},
{
"code": "B36",
"qty": 4
},
{
"code": "LIN18",
"qty": 1
},
{
"code": "MED36",
"qty": 1
},
{
"code": "MED60",
"qty": 1
},
{
"code": "SB36",
"qty": 1
},
{
"code": "T15-84",
"qty": 1
},
{
"code": "VAN36",
"qty": 1
},
{
"code": "VAN60",
"qty": 1
},
{
"code": "W30-18",
"qty": 1
},
{
"code": "W30-30",
"qty": 2
},
{
"code": "W36-30",
"qty": 3
}
],
"countertop_lf": 25.0,
"upper_cabinet_lf": 16.5,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "D-1",
"cabinets": [
{
"code": "B24",
"qty": 1
},
{
"code": "B36",
"qty": 4
},
{
"code": "LIN18",
"qty": 1
},
{
"code": "MED36",
"qty": 1
},
{
"code": "MED60",
"qty": 1
},
{
"code": "SB36",
"qty": 1
},
{
"code": "T15-84",
"qty": 1
},
{
"code": "VAN36",
"qty": 1
},
{
"code": "VAN60",
"qty": 1
},
{
"code": "W30-18",
"qty": 1
},
{
"code": "W30-30",
"qty": 2
},
{
"code": "W36-30",
"qty": 3
}
],
"countertop_lf": 25.0,
"upper_cabinet_lf": 16.5,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "D-1a ACC",
"cabinets": [
{
"code": "B24-ADA",
"qty": 1
},
{
"code": "B36-ADA",
"qty": 4
},
{
"code": "LIN18-ADA",
"qty": 1
},
{
"code": "MED36-ADA",
"qty": 1
},
{
"code": "MED60-ADA",
"qty": 1
},
{
"code": "SB36-ADA",
"qty": 1
},
{
"code": "T15-84-ADA",
"qty": 1
},
{
"code": "VAN36-ADA",
"qty": 1
},
{
"code": "VAN60-ADA",
"qty": 1
},
{
"code": "W30-18-ADA",
"qty": 1
},
{
"code": "W30-30-ADA",
"qty": 2
},
{
"code": "W36-30-ADA",
"qty": 3
}
],
"countertop_lf": 25.0,
"upper_cabinet_lf": 16.5,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"ADA",
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "D-1A ACC",
"cabinets": [
{
"code": "B24-ADA",
"qty": 1
},
{
"code": "B36-ADA",
"qty": 4
},
{
"code": "LIN18-ADA",
"qty": 1
},
{
"code": "MED36-ADA",
"qty": 1
},
{
"code": "MED60-ADA",
"qty": 1
},
{
"code": "SB36-ADA",
"qty": 1
},
{
"code": "T15-84-ADA",
"qty": 1
},
{
"code": "VAN36-ADA",
"qty": 1
},
{
"code": "VAN60-ADA",
"qty": 1
},
{
"code": "W30-18-ADA",
"qty": 1
},
{
"code": "W30-30-ADA",
"qty": 2
},
{
"code": "W36-30-ADA",
"qty": 3
}
],
"countertop_lf": 25.0,
"upper_cabinet_lf": 16.5,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"ADA",
"Pantry"
],
"installation_complexity": "high"
},
{
"unit_type": "ST-1a ACC",
"cabinets": [
{
"code": "B24-ADA",
"qty": 1
},
{
"code": "MED30-ADA",
"qty": 1
},
{
"code": "SB36-ADA",
"qty": 1
},
{
"code": "VAN30-ADA",
"qty": 1
},
{
"code": "W30-18-ADA",
"qty": 1
},
{
"code": "W30-30-ADA",
"qty": 1
}
],
"countertop_lf": 7.5,
"upper_cabinet_lf": 5.0,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [
"ADA"
],
"installation_complexity": "medium"
},
{
"unit_type": "ST-1",
"cabinets": [
{
"code": "B24",
"qty": 1
},
{
"code": "MED30",
"qty": 1
},
{
"code": "SB36",
"qty": 1
},
{
"code": "VAN30",
"qty": 1
},
{
"code": "W30-18",
"qty": 1
},
{
"code": "W30-30",
"qty": 1
}
],
"countertop_lf": 7.5,
"upper_cabinet_lf": 5.0,
"fillers": [],
"panels": [],
"moldings": [],
"special_items": [],
"installation_complexity": "low"
}
]
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,335 @@
[
{
"building": "Building C",
"floor": 1,
"unit_type": "A-1",
"count": 5,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building C",
"floor": 2,
"unit_type": "A-1",
"count": 5,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building C",
"floor": 3,
"unit_type": "A-1",
"count": 5,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": false
},
{
"building": "Building C",
"floor": 1,
"unit_type": "A-1a ACC",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
},
{
"building": "Building C",
"floor": 2,
"unit_type": "A-1a ACC",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
},
{
"building": "Building C",
"floor": 3,
"unit_type": "A-1a ACC",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V2",
"is_ada": true
},
{
"building": "Building C",
"floor": 1,
"unit_type": "B-1",
"count": 4,
"kitchen_type": "K1",
"bathroom_type": "V3",
"is_ada": false
},
{
"building": "Building C",
"floor": 2,
"unit_type": "B-1",
"count": 4,
"kitchen_type": "K1",
"bathroom_type": "V3",
"is_ada": false
},
{
"building": "Building C",
"floor": 3,
"unit_type": "B-1",
"count": 4,
"kitchen_type": "K1",
"bathroom_type": "V3",
"is_ada": false
},
{
"building": "Building C",
"floor": 1,
"unit_type": "B-1a ACC",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V4",
"is_ada": true
},
{
"building": "Building C",
"floor": 2,
"unit_type": "B-1a ACC",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V4",
"is_ada": true
},
{
"building": "Building C",
"floor": 3,
"unit_type": "B-1a ACC",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V4",
"is_ada": true
},
{
"building": "Building C",
"floor": 1,
"unit_type": "C-1",
"count": 3,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 2,
"unit_type": "C-1",
"count": 3,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 3,
"unit_type": "C-1",
"count": 2,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 1,
"unit_type": "C-2",
"count": 2,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 2,
"unit_type": "C-2",
"count": 2,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 3,
"unit_type": "C-2",
"count": 2,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 1,
"unit_type": "C-2a ACC",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V6",
"is_ada": true
},
{
"building": "Building C",
"floor": 2,
"unit_type": "C-2a ACC",
"count": 1,
"kitchen_type": "K1",
"bathroom_type": "V6",
"is_ada": true
},
{
"building": "Building C",
"floor": 1,
"unit_type": "C-3",
"count": 2,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 2,
"unit_type": "C-3",
"count": 2,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 3,
"unit_type": "C-3",
"count": 2,
"kitchen_type": "K1",
"bathroom_type": "V5",
"is_ada": false
},
{
"building": "Building C",
"floor": 1,
"unit_type": "D-1N",
"count": 2,
"kitchen_type": "K2",
"bathroom_type": "V7",
"is_ada": false
},
{
"building": "Building C",
"floor": 2,
"unit_type": "D-1N",
"count": 1,
"kitchen_type": "K2",
"bathroom_type": "V7",
"is_ada": false
},
{
"building": "Building C",
"floor": 3,
"unit_type": "D-1N",
"count": 1,
"kitchen_type": "K2",
"bathroom_type": "V7",
"is_ada": false
},
{
"building": "Building C",
"floor": 1,
"unit_type": "D-1",
"count": 1,
"kitchen_type": "K2",
"bathroom_type": "V7",
"is_ada": false
},
{
"building": "Building C",
"floor": 1,
"unit_type": "D-1a ACC",
"count": 1,
"kitchen_type": "K2",
"bathroom_type": "V8",
"is_ada": true
},
{
"building": "Building C",
"floor": 2,
"unit_type": "D-1a ACC",
"count": 1,
"kitchen_type": "K2",
"bathroom_type": "V8",
"is_ada": true
},
{
"building": "Building C",
"floor": 1,
"unit_type": "D-1A ACC",
"count": 1,
"kitchen_type": "K2",
"bathroom_type": "V8",
"is_ada": true
},
{
"building": "Building C",
"floor": 2,
"unit_type": "D-1A ACC",
"count": 1,
"kitchen_type": "K2",
"bathroom_type": "V8",
"is_ada": true
},
{
"building": "Building C",
"floor": 1,
"unit_type": "ST-1a ACC",
"count": 2,
"kitchen_type": "K3",
"bathroom_type": "V4",
"is_ada": true
},
{
"building": "Building C",
"floor": 2,
"unit_type": "ST-1a ACC",
"count": 1,
"kitchen_type": "K3",
"bathroom_type": "V4",
"is_ada": true
},
{
"building": "Building C",
"floor": 3,
"unit_type": "ST-1a ACC",
"count": 1,
"kitchen_type": "K3",
"bathroom_type": "V4",
"is_ada": true
},
{
"building": "Building C",
"floor": 1,
"unit_type": "ST-1",
"count": 2,
"kitchen_type": "K3",
"bathroom_type": "V3",
"is_ada": false
},
{
"building": "Building C",
"floor": 2,
"unit_type": "ST-1",
"count": 2,
"kitchen_type": "K3",
"bathroom_type": "V3",
"is_ada": false
},
{
"building": "Building C",
"floor": 3,
"unit_type": "ST-1",
"count": 2,
"kitchen_type": "K3",
"bathroom_type": "V3",
"is_ada": false
}
]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+469 -79
View File
@@ -41,8 +41,14 @@ from core.region_detector import RegionDetector
from core.dimension_parser import classify_spans, associate_dims_to_rects
from core.cabinet_validator import CabinetValidator
from core.price_matcher import PriceMatcher, get_fallback_price_usd, _generate_code
from core.unit_counter import UnitCounter, load_matrix_from_config
from core.unit_matrix_extractor import UnitMatrixExtractor, load_matrix_from_config
from core.job_costing import JobCostingInput, calculate_selling_price
from core.drawing_classifier import DrawingClassifier
from core.ceiling_height_extractor import CeilingHeightExtractor
from core.opening_extractor import OpeningExtractor
from core.confidence_engine import ConfidenceEngine
from core.geometry_engine import GeometryEngine
from generators.shop_drawing_dxf import DXFDrawingGenerator
# ══════════════════════════════════════════════════════════════════════════
@@ -57,6 +63,7 @@ class UnitSchedule:
is_ada: bool = False
auto_approved: bool = False
review_flags: list[str] = field(default_factory=list)
legend_map: dict[str, str] = field(default_factory=dict)
@property
def all_cabinets(self):
@@ -140,11 +147,16 @@ def process_unit(
print(f"\n [{unit_type}] Loading cached cabinet schedule...")
with open(cache_path, encoding="utf-8") as f:
cached = json.load(f)
schedule.legend_map = cached.get("legend_map", {})
# Convert back to ElevationResult objects
for ev_data in cached.get("elevations", []):
from core.ai_vision_classifier import CabinetItem, ElevationResult
cabs = []
for c in ev_data.get("cabinets", []):
if "cabinet_id" not in c:
c["cabinet_id"] = ""
if "source" not in c:
c["source"] = "gemini"
cabs.append(CabinetItem(**c))
ev = ElevationResult(
elevation_label = ev_data["elevation_label"],
@@ -152,6 +164,17 @@ def process_unit(
project_name = project_name,
cabinets = cabs,
is_ada = is_ada,
appliances = ev_data.get("appliances", []),
doors = ev_data.get("doors", []),
windows = ev_data.get("windows", []),
fillers = ev_data.get("fillers", []),
panels = ev_data.get("panels", []),
moldings = ev_data.get("moldings", []),
relationships = ev_data.get("relationships", []),
ceiling_height_in = ev_data.get("ceiling_height_in", None),
soffit_present = ev_data.get("soffit_present", False),
backsplash = ev_data.get("backsplash", ""),
counter_material = ev_data.get("counter_material", ""),
)
schedule.elevations.append(ev)
return schedule
@@ -164,75 +187,116 @@ def process_unit(
print(f"\n [{unit_type}] Processing: {pdf_path.name}")
with PDFExtractor(pdf_path) as ex:
page = ex.extract_page(0)
detector = RegionDetector(page.spans, page.rects, page.page_w, page.page_h)
regions = detector.detect()
if not regions:
print(f" [WARN] No elevation regions detected in {pdf_path.name}")
schedule.review_flags.append("No elevation regions detected")
return schedule
print(f" Detected {len(regions)} regions")
# Pre-extract dimensions for AI context
classified = classify_spans(page.spans)
pre_dims = [
{"text": s.text, "type": "METRIC", "x": s.cx, "y": s.cy}
for s in classified["metric_dims"]
] + [
{"text": s.text, "type": "IMPERIAL", "x": s.cx, "y": s.cy}
for s in classified["imperial_dims"]
]
labeled_rects = associate_dims_to_rects(page.spans, page.rects)
pre_rects = [
{"x0": lr.rect.x0, "y0": lr.rect.y0,
"x1": lr.rect.x1, "y1": lr.rect.y1,
"w": lr.rect.w, "h": lr.rect.h}
for lr in labeled_rects if lr.rect.w > 20
][:50]
# Process each detected region
for region in regions:
if not region.is_elevation() and region.region_type not in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
for page_idx in range(ex.page_count):
page = ex.extract_page(page_idx)
# --- Stage 0 Filter: Drawing Classification ---
sheet_type = DrawingClassifier.classify_page(page.spans)
print(f" [Page {page_idx + 1}] Class: {sheet_type}")
# If the PDF contains only 1 page, do not skip it even if classified as RCP/Detail,
# as it is the only source drawing for this unit type.
is_single_page = (ex.page_count == 1)
if not is_single_page and sheet_type not in ("UNIT PLAN", "ELEVATION"):
print(f" Skipping page {page_idx + 1} ({sheet_type})")
continue
# Crop the region
crop_path = output_dir / "crops" / f"{unit_type.replace(' ','_')}_{region.region_type}.png"
print(f" Cropping region: {region.region_type} (conf={region.confidence:.2f})")
img_bytes = ex.render_region(region.crop_rect, dpi=400)
# Extract legend mapping if not already done
if not schedule.legend_map:
from core.legend_extractor import LegendExtractor
legend_extractor = LegendExtractor(page.spans, page.page_w, page.page_h)
schedule.legend_map = legend_extractor.extract()
if schedule.legend_map:
print(f" Extracted {len(schedule.legend_map)} keynotes from drawing legend")
# Save crop for reference
crop_path.parent.mkdir(parents=True, exist_ok=True)
crop_path.write_bytes(img_bytes)
# --- Physical Parameter Extractions ---
clg_data = CeilingHeightExtractor.extract_heights(page.spans)
openings_data = OpeningExtractor.extract_openings(page.spans, page.rects)
if skip_ai or classifier is None:
print(f" [SKIP AI] Region {region.region_type} — AI disabled")
detector = RegionDetector(page.spans, page.rects, page.page_w, page.page_h)
regions = detector.detect()
if not regions:
print(f" [WARN] No elevation regions detected in page {page_idx + 1}")
continue
# Call Gemini Vision API
mode_tag = "DEMO (low-token)" if demo_mode else "FULL"
print(f" Sending {region.region_type} crop to Gemini Vision [{mode_tag}]...")
elevation_result = classifier.classify_elevation(
image_bytes = img_bytes,
unit_type = unit_type,
elevation_label = region.region_type,
project_name = project_name,
pre_extracted_dims = pre_dims,
pre_extracted_rects = pre_rects,
is_ada = is_ada,
demo_mode = demo_mode,
)
print(f" Detected {len(regions)} regions on page {page_idx + 1}")
# Validate
validator.validate(
elevation_result.cabinets,
is_ada = is_ada,
location = f"{unit_type} / {region.region_type}",
)
# Pre-extract dimensions for AI context
classified = classify_spans(page.spans)
pre_dims = [
{"text": s.text, "type": "METRIC", "x": s.cx, "y": s.cy}
for s in classified["metric_dims"]
] + [
{"text": s.text, "type": "IMPERIAL", "x": s.cx, "y": s.cy}
for s in classified["imperial_dims"]
]
schedule.elevations.append(elevation_result)
labeled_rects = associate_dims_to_rects(page.spans, page.rects)
pre_rects = [
{"x0": lr.rect.x0, "y0": lr.rect.y0,
"x1": lr.rect.x1, "y1": lr.rect.y1,
"w": lr.rect.w, "h": lr.rect.h}
for lr in labeled_rects if lr.rect.w > 20
][:50]
# Process each detected region
for region in regions:
if not region.is_elevation() and region.region_type not in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
continue
# Crop the region
crop_path = output_dir / "crops" / f"{unit_type.replace(' ','_')}_{region.region_type}.png"
print(f" Cropping region: {region.region_type} (conf={region.confidence:.2f})")
img_bytes = ex.render_region(region.crop_rect, dpi=400)
# Save crop for reference
crop_path.parent.mkdir(parents=True, exist_ok=True)
crop_path.write_bytes(img_bytes)
if skip_ai or classifier is None:
print(f" [SKIP AI] Region {region.region_type} — AI disabled")
continue
# Call Gemini Vision API
mode_tag = "DEMO (low-token)" if demo_mode else "FULL"
print(f" Sending {region.region_type} crop to Gemini Vision [{mode_tag}]...")
elevation_result = classifier.classify_elevation(
image_bytes = img_bytes,
unit_type = unit_type,
elevation_label = region.region_type,
project_name = project_name,
pre_extracted_dims = pre_dims,
pre_extracted_rects = pre_rects,
is_ada = is_ada,
legend_map = schedule.legend_map,
demo_mode = demo_mode,
)
# Populate extracted metrics
elevation_result.ceiling_height_in = clg_data["ceiling_height"]
elevation_result.soffit_present = clg_data["soffit_height"] is not None
if not elevation_result.doors:
elevation_result.doors = openings_data["doors"]
if not elevation_result.windows:
elevation_result.windows = openings_data["windows"]
# Validate
validator.validate(
elevation_result.cabinets,
is_ada = is_ada,
location = f"{unit_type} / {region.region_type}",
)
# Confidence Evaluation
qa_res = ConfidenceEngine.evaluate(elevation_result)
elevation_result.review_flags.extend(qa_res["warnings"])
if qa_res["needs_review"]:
print(f" [QA review flagged] {region.region_type}: {qa_res['warnings']}")
elevation_result.auto_approved = False
elevation_result.avg_confidence = min(elevation_result.avg_confidence, qa_res["confidence_score"])
schedule.elevations.append(elevation_result)
# Auto-approve if all elevations passed
schedule.auto_approved = (
@@ -256,6 +320,7 @@ def _save_schedule_json(schedule: UnitSchedule, out_path: Path):
"is_ada": schedule.is_ada,
"auto_approved": schedule.auto_approved,
"review_flags": schedule.review_flags,
"legend_map": schedule.legend_map,
"elevations": [
{
"elevation_label": ev.elevation_label,
@@ -265,6 +330,17 @@ def _save_schedule_json(schedule: UnitSchedule, out_path: Path):
"avg_confidence": ev.avg_confidence,
"review_flags": ev.review_flags,
"cabinets": [c.to_dict() for c in ev.cabinets],
"appliances": ev.appliances,
"doors": ev.doors,
"windows": ev.windows,
"fillers": ev.fillers,
"panels": ev.panels,
"moldings": ev.moldings,
"relationships": ev.relationships,
"ceiling_height_in": ev.ceiling_height_in,
"soffit_present": ev.soffit_present,
"backsplash": ev.backsplash,
"counter_material": ev.counter_material,
}
for ev in schedule.elevations
],
@@ -427,7 +503,7 @@ def run_pipeline(
)
unit_schedules[unit_type] = schedule
# ── Step 2: Unit counts ────────────────────────────────────────────────
# ── Step 2: Unit Count Matrix ──────────────────────────────────────────
print(f"\n STEP 2: Unit Count Matrix")
print(f" {'-' * 50}")
@@ -438,12 +514,131 @@ def run_pipeline(
else:
print(" Auto-detecting unit counts from floor plan PDFs...")
floor_plan_pdfs = [project_root / p for p in config.get("floor_plan_pdfs", [])]
counter = UnitCounter()
counter = UnitMatrixExtractor()
matrix = counter.count_from_pdfs(floor_plan_pdfs, project_name)
matrix.print_summary()
unit_totals = matrix.totals
# helper to parse building/floor info from filenames
def extract_building_floor_from_path(pdf_path_str: str) -> tuple[str, int]:
name = Path(pdf_path_str).name.upper()
building = "Building A"
bldg_m = re.search(r'\b(?:BLDG|BUILDING|PARTIAL)[\s_-]*([A-Z0-9]+)\b', name)
if bldg_m:
building = f"Building {bldg_m.group(1)}"
else:
sheet_m = re.search(r'A-2\.\d+([A-Z])', name)
if sheet_m:
building = f"Building {sheet_m.group(1)}"
floor = 1
if "GROUND" in name or "1ST" in name or "LEVEL 1" in name or "2.00" in name:
floor = 1
elif "2ND" in name or "LEVEL 2" in name or "2.01" in name:
floor = 2
elif "3RD" in name or "LEVEL 3" in name or "2.02" in name:
floor = 3
elif "4TH" in name or "LEVEL 4" in name or "2.03" in name:
floor = 4
elif "5TH" in name or "LEVEL 5" in name or "2.04" in name:
floor = 5
else:
floor_digit_m = re.search(r'(\d+)(?:ND|RD|TH|ST)\s+FLOOR', name)
if floor_digit_m:
floor = int(floor_digit_m.group(1))
return building, floor
import re
from collections import defaultdict
unit_matrix_list = []
detected_matrix = None
floor_plans_config = config.get("floor_plan_pdfs", [])
if floor_plans_config:
try:
floor_plan_paths = [project_root / p for p in floor_plans_config]
counter = UnitMatrixExtractor()
detected_matrix = counter.count_from_pdfs(floor_plan_paths, project_name)
except Exception as e:
print(f" [WARN] Failed to auto-detect unit counts: {e}")
matrix_counts = defaultdict(int)
if detected_matrix and detected_matrix.floor_counts:
for fc in detected_matrix.floor_counts:
bldg, fl = extract_building_floor_from_path(fc.pdf_path)
for ut, cnt in fc.unit_counts.items():
matrix_counts[(bldg, fl, ut)] = cnt
if unit_counts_config:
detected_totals = defaultdict(int)
for (bldg, fl, ut), cnt in matrix_counts.items():
detected_totals[ut] += cnt
adjusted_counts = defaultdict(int)
for ut, target_cnt in unit_counts_config.items():
det_tot = detected_totals.get(ut, 0)
if det_tot > 0:
for (bldg, fl, ut2), cnt in list(matrix_counts.items()):
if ut2 == ut:
adjusted_counts[(bldg, fl, ut)] = round(cnt * target_cnt / det_tot)
adj_tot = sum(adjusted_counts[(bldg, fl, ut2)] for (bldg, fl, ut2) in adjusted_counts if ut2 == ut)
diff = target_cnt - adj_tot
if diff != 0:
for (bldg, fl, ut2) in adjusted_counts:
if ut2 == ut:
adjusted_counts[(bldg, fl, ut)] += diff
break
else:
if floor_plans_config:
available_floors = []
for p in floor_plans_config:
bldg, fl = extract_building_floor_from_path(p)
if (bldg, fl) not in available_floors:
available_floors.append((bldg, fl))
num_floors = len(available_floors)
base_cnt = target_cnt // num_floors
rem = target_cnt % num_floors
for idx, (bldg, fl) in enumerate(available_floors):
c = base_cnt + (1 if idx < rem else 0)
if c > 0:
adjusted_counts[(bldg, fl, ut)] = c
else:
first_bldg = "Building A"
adjusted_counts[(first_bldg, 1, ut)] = target_cnt
matrix_counts = adjusted_counts
else:
if floor_plans_config:
available_floors = []
for p in floor_plans_config:
bldg, fl = extract_building_floor_from_path(p)
if (bldg, fl) not in available_floors:
available_floors.append((bldg, fl))
num_floors = len(available_floors)
for ut, cnt in unit_totals.items():
base_cnt = cnt // num_floors
rem = cnt % num_floors
for idx, (bldg, fl) in enumerate(available_floors):
c = base_cnt + (1 if idx < rem else 0)
if c > 0:
matrix_counts[(bldg, fl, ut)] = c
else:
first_bldg = "Building A"
for ut, cnt in unit_totals.items():
matrix_counts[(first_bldg, 1, ut)] = cnt
for (bldg, fl, ut), cnt in matrix_counts.items():
if cnt > 0:
unit_matrix_list.append({
"building": bldg,
"floor": fl,
"unit_type": ut,
"count": cnt,
"kitchen_type": "K1",
"bathroom_type": "V1",
"is_ada": ut in ada_units
})
# ── Step 3–4: Pricing + Job Costing ───────────────────────────────────
print(f"\n STEP 3: Price Matching (Euro list -> USD)")
print(f" {'-' * 50}")
@@ -478,14 +673,26 @@ def run_pipeline(
try:
from generators.cabinet_excel import generate_excel
excel_path = output_dir / f"{project_id}_Cabinet_Estimation.xlsx"
generate_excel(
config = config,
unit_schedules = unit_schedules,
unit_totals = unit_totals,
jc_result = jc_result,
output_path = str(excel_path),
)
print(f" [SUCCESS] Excel saved: {excel_path}")
try:
generate_excel(
config = config,
unit_schedules = unit_schedules,
unit_totals = unit_totals,
jc_result = jc_result,
output_path = str(excel_path),
)
print(f" [SUCCESS] Excel saved: {excel_path}")
except PermissionError:
excel_path_backup = output_dir / f"{project_id}_Cabinet_Estimation_NEW.xlsx"
print(f" [WARN] Permission denied on standard path. Saving backup to: {excel_path_backup}")
generate_excel(
config = config,
unit_schedules = unit_schedules,
unit_totals = unit_totals,
jc_result = jc_result,
output_path = str(excel_path_backup),
)
print(f" [SUCCESS] Excel saved (backup): {excel_path_backup}")
except Exception as e:
print(f" [ERROR] Excel generation failed: {e}")
import traceback; traceback.print_exc()
@@ -498,17 +705,200 @@ def run_pipeline(
pdf_out = output_dir / f"{project_id}_Shop_Drawings.pdf"
# Always use the universal parameterized generator (works for any project)
from generators.shop_drawing_pdf import generate_shop_drawings
generate_shop_drawings(
config = config,
unit_schedules = unit_schedules,
unit_totals = unit_totals,
output_path = str(pdf_out),
)
print(f" [SUCCESS] PDF saved: {pdf_out}")
try:
generate_shop_drawings(
config = config,
unit_schedules = unit_schedules,
unit_totals = unit_totals,
output_path = str(pdf_out),
)
print(f" [SUCCESS] PDF saved: {pdf_out}")
except PermissionError:
pdf_out_backup = output_dir / f"{project_id}_Shop_Drawings_NEW.pdf"
print(f" [WARN] Permission denied on standard path. Saving backup to: {pdf_out_backup}")
generate_shop_drawings(
config = config,
unit_schedules = unit_schedules,
unit_totals = unit_totals,
output_path = str(pdf_out_backup),
)
print(f" [SUCCESS] PDF saved (backup): {pdf_out_backup}")
except Exception as e:
print(f" [ERROR] PDF generation failed: {e}")
import traceback; traceback.print_exc()
# ── Step 7: Output Final Deliverable Schemas ───────────────────────────
print(f"\n STEP 7: Generating Target Deliverables JSON Schemas")
print(f" {'-' * 50}")
from core.kitchen_layout_classifier import KitchenLayoutClassifier
from core.vanity_layout_classifier import VanityLayoutClassifier
from core.cabinet_graph_builder import CabinetGraphBuilder
kitchen_classifier = KitchenLayoutClassifier()
vanity_classifier = VanityLayoutClassifier()
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_mm": cab.width_mm,
"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_mm / 25.4)
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_mm / 25.4) 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")
# 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,
layout_shape = "straight"
)
cost_drawing = graph_builder.build_cost_schema(
unit_type = ut,
elevations = schedule.elevations,
is_ada = schedule.is_ada
)
schedule.kitchen_type = kitchen_type
schedule.bathroom_type = bathroom_type
schedule.shop_drawing_schema = shop_drawing
schedule.cost_schema = cost_drawing
for entry in unit_matrix_list:
ut = entry["unit_type"]
if ut in unit_schedules:
entry["kitchen_type"] = unit_schedules[ut].kitchen_type
entry["bathroom_type"] = unit_schedules[ut].bathroom_type
# Save unit matrix final
unit_matrix_path = output_dir / "json" / "unit_matrix_final.json"
unit_matrix_path.parent.mkdir(parents=True, exist_ok=True)
unit_matrix_path.write_text(json.dumps(unit_matrix_list, indent=2), encoding="utf-8")
print(f" [SUCCESS] Unit Matrix schema saved: {unit_matrix_path}")
# Save shop drawing final
shop_drawing_list = [s.shop_drawing_schema for s in unit_schedules.values() if hasattr(s, "shop_drawing_schema")]
shop_drawing_path = output_dir / "json" / "shop_drawing_final.json"
shop_drawing_path.write_text(json.dumps(shop_drawing_list, indent=2), encoding="utf-8")
print(f" [SUCCESS] Shop Drawing schema saved: {shop_drawing_path}")
# Save cost estimation final
cost_list = [s.cost_schema for s in unit_schedules.values() if hasattr(s, "cost_schema")]
cost_path = output_dir / "json" / "cost_estimation_final.json"
cost_path.write_text(json.dumps(cost_list, indent=2), encoding="utf-8")
print(f" [SUCCESS] Cost Estimation schema saved: {cost_path}")
# ── Step 8: Generate CAD DXF Drawings ─────────────────────────────────
print(f"\n STEP 8: Generating CAD DXF Drawings")
print(f" {'-' * 50}")
try:
dxf_dir = output_dir / "dxf"
dxf_dir.mkdir(parents=True, exist_ok=True)
geom_engine = GeometryEngine()
dxf_generator = DXFDrawingGenerator()
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_mm / 25.4)
h_in = round(cab.height_mm / 25.4)
cabs_list.append({
"id": cab.cabinet_id or cab.code,
"x": base_x,
"width": w_in,
"height": h_in,
"type": cab.cabinet_type,
"cabinet_type": cab.cabinet_type
})
base_x += w_in
wall_name = ev.elevation_label.replace("ELEVATION ", "").strip()
if wall_name.upper() in ("KITCHEN", "BATH", "VANITY", "MASTER_BATH"):
wall_name = "A"
walls_info.append({
"name": wall_name,
"length": max(90.0, base_x),
"cabinets": cabs_list
})
if not walls_info:
walls_info.append({
"name": "A",
"length": 90.0,
"cabinets": []
})
ceiling_height = 108.0
for ev in schedule.elevations:
if ev.ceiling_height_in is not None:
ceiling_height = ev.ceiling_height_in
break
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)
except Exception as e:
print(f" [ERROR] DXF generation failed: {e}")
import traceback; traceback.print_exc()
# -- Summary ------------------------------------------------------------
duration = time.time() - start_time
print(f"\n{'=' * 60}")
+29 -3
View File
@@ -119,7 +119,33 @@ try:
"depth_mm": 600, "location": "DW", "elevation_ref": "ELEV A",
"confidence": 0.98, "quantity": 1, "is_ada": false, "notes": "dishwasher"}
]'''
cabs = c._parse_cabinet_json(sample_json, "ELEV A")
cabs_data = c._parse_cabinet_json(sample_json, "ELEV A")
from core.ai_vision_classifier import CabinetItem, _normalize_cabinet_type, _default_height, _default_depth, VALID_CABINET_TYPES
cabs = []
for i, item in enumerate(cabs_data.get("cabinets", []), 1):
cab_type = item.get("cabinet_type", "unknown").lower().strip()
if cab_type not in VALID_CABINET_TYPES:
cab_type = _normalize_cabinet_type(cab_type)
width_mm = float(item.get("width_mm", 0) or 0)
height_mm = float(item.get("height_mm", 0) or 0)
depth_mm = float(item.get("depth_mm", 0) or 0)
if height_mm == 0:
height_mm = _default_height(cab_type)
if depth_mm == 0:
depth_mm = _default_depth(cab_type)
cabs.append(CabinetItem(
item_num = i,
cabinet_type = cab_type,
width_mm = width_mm,
height_mm = height_mm,
depth_mm = depth_mm,
location = item.get("location", ""),
elevation_ref = "ELEV A",
confidence = item.get("confidence", 0.9),
quantity = item.get("quantity", 1),
is_ada = item.get("is_ada", False),
notes = item.get("notes", "")
))
check("Parsed 3 items", len(cabs) == 3, f"{len(cabs)} items")
check("First item width=762mm", cabs[0].width_mm == 762, str(cabs[0].width_mm))
@@ -194,13 +220,13 @@ except Exception as e:
# ── Test 7: Unit Counter (manual mode) ───────────────
print("\n[7] Unit Counter (manual override)")
try:
from core.unit_counter import load_matrix_from_config
from core.unit_matrix_extractor import load_matrix_from_config
matrix = load_matrix_from_config({"A1": 14, "B1": 6}, "Test Project")
check("Totals loaded", matrix.totals == {"A1": 14, "B1": 6})
check("Confidence = 1.0", matrix.confidence == 1.0)
check("Needs review = False", not matrix.needs_review)
except Exception as e:
print(f" {FAIL} unit_counter error: {e}")
print(f" {FAIL} unit_matrix_extractor error: {e}")
all_ok = False
# ── Test 8: PDF Extractor (basic import) ─────────────
-93
View File
@@ -1,93 +0,0 @@
# AI Cabinet Estimation & Shop Drawing Automation
An AI-powered pipeline that reads architectural PDF drawings and automatically generates:
- Cabinet shop drawings (ItalianKB-style PDF)
- Project cabinet matrix (Excel)
- Material cost report (Excel)
- Final job costing & selling price quote (Excel)
## Project: Casa Familia & Heritage Village
Client: Kitchen & bathroom cabinet supplier for large-scale US residential construction (FHA/ADA housing).
---
## Pipeline Overview
```
Architect PDF → PyMuPDF → Text + Geometry Extraction
↓
Region Detection (Kitchen / Bath / Elevation)
↓
400 DPI Crop → Claude Vision API
↓
Cabinet Schedule JSON
↓
ReportLab → Shop Drawing PDF
openpyxl → Matrix + Pricing Excel
```
---
## Scripts
| File | Description |
|------|-------------|
| `step1_crop_elevations.py` | Reads architect PDF → detects regions → crops at 400 DPI → outputs JSON |
| `read_arch_drawing_pymupdf.py` | Full PyMuPDF extraction demo — 4-page visual output PDF |
| `show_pymupdf_output_formats.py` | Shows exact data types returned by each PyMuPDF method |
| `generate_italiankb_shop_drawings.py` | Generates Casa Familia shop drawing PDF (ItalianKB style) |
| `generate_heritage_shop_drawings.py` | Generates Heritage Village shop drawing PDF |
| `generate_heritage_excel.py` | Generates Heritage Village cabinet matrix + pricing Excel |
| `run_cabinet_estimation.py` | Master runner script |
---
## Tech Stack
| Layer | Tool | Purpose |
|-------|------|---------|
| PDF Reading | PyMuPDF (fitz) | Extract text, geometry, render images |
| PDF Writing | ReportLab | Generate shop drawing PDFs |
| Excel Output | openpyxl | Generate matrix + pricing spreadsheets |
| AI Vision | Claude 3.5 Sonnet / GPT-4o | Classify cabinets from elevation images |
| Orchestration | Python | Pipeline runner |
---
## Project Understanding
See `_Project_Understanding/` folder:
- `01_Client_Understanding_Detailed.md` — Full client requirements
- `02_Simple_Summary_Input_Flow_Output.md` — 5-step workflow summary
- `03_Extraction_Deep_Dive_Research.md` — Technical research on extraction pipeline
---
## 5-Step Client Workflow
1. **Read elevations** → Identify every cabinet (type, W×H×D)
2. **Generate shop drawings** → Per unit type PDF (ItalianKB style)
3. **Build project matrix** → Count units per floor × cabinet totals
4. **Price materials** → Match to vendor price list (Euros → USD, mm → inches)
5. **Job costing** → Apply tax/freight/install/GP% → Final selling price
---
## Status
- [x] PyMuPDF extraction pipeline working
- [x] Region detection (Kitchen/Bath/Elevation)
- [x] 400 DPI crop images generated
- [x] Shop drawing PDF generator (Casa Familia + Heritage)
- [x] Excel generator (Heritage Village)
- [ ] Claude Vision API integration (Step 1B)
- [ ] Automated cabinet schedule JSON → PDF pipeline
- [ ] Project matrix builder from floor plans
---
## Setup
```bash
pip install pymupdf reportlab openpyxl
```
-780
View File
@@ -1,780 +0,0 @@
import openpyxl
from openpyxl.styles import Font, Alignment, PatternFill, Border, Side
from openpyxl.utils import get_column_letter
import os
# Define output path
OUTPUT_DIR = r"C:\Users\prajw\OneDrive\Desktop\Albert\Albert_Project\Heritage\03_Shop_Drawings"
os.makedirs(OUTPUT_DIR, exist_ok=True)
OUTPUT_PATH = os.path.join(OUTPUT_DIR, "05_Cabinet_Estimation_Shop_Drawings_Heritage_Village.xlsx")
wb = openpyxl.Workbook()
# Setup sheets
ws_info = wb.active
ws_info.title = "Project Info"
ws_matrix = wb.create_sheet("Cabinet Matrix")
ws_library = wb.create_sheet("Cabinet Library")
ws_costing = wb.create_sheet("Job Costing")
# Standard styling
font_title = Font(name="Arial", size=16, bold=True, color="1B365D")
font_section = Font(name="Arial", size=12, bold=True, color="1B365D")
font_header = Font(name="Arial", size=10, bold=True, color="FFFFFF")
font_bold = Font(name="Arial", size=10, bold=True)
font_regular = Font(name="Arial", size=10)
font_small = Font(name="Arial", size=8, italic=True)
fill_navy = PatternFill(start_color="1B365D", end_color="1B365D", fill_type="solid")
fill_light_gray = PatternFill(start_color="F2F4F7", end_color="F2F4F7", fill_type="solid")
fill_blue_input = PatternFill(start_color="D9E1F2", end_color="D9E1F2", fill_type="solid")
fill_green_calc = PatternFill(start_color="E2EFDA", end_color="E2EFDA", fill_type="solid")
thin_border_side = Side(style="thin", color="D3D3D3")
thin_border = Border(left=thin_border_side, right=thin_border_side, top=thin_border_side, bottom=thin_border_side)
double_bottom = Border(bottom=Side(style="double", color="1B365D"), top=thin_border_side)
align_center = Alignment(horizontal="center", vertical="center")
align_left = Alignment(horizontal="left", vertical="center")
align_right = Alignment(horizontal="right", vertical="center")
# -------------------------------------------------------------
# SHEET 1: Project Info
# -------------------------------------------------------------
ws_info.views.sheetView[0].showGridLines = True
ws_info.cell(1, 1, "CABINET ESTIMATION — PROJECT INFORMATION").font = font_title
ws_info.cell(2, 1, "Heritage Village — Atlantic Pacific Communities").font = font_small
info_fields = [
("Project Name:", "Heritage Village", fill_blue_input),
("Project ID:", "23-045", fill_blue_input),
("Date:", "=TODAY()", None),
("Prepared By:", "AI Estimation System", None),
("Building Type:", "Residential — Type V-A", None),
("Price List Used:", "MS PRICE LIST LEVEL 1 -90CM", fill_blue_input),
("GP Target %:", 0.35, fill_blue_input),
("Total Units:", "=SUM('Cabinet Matrix'!B6:B19)", fill_green_calc),
]
row_idx = 4
for label, val, fill in info_fields:
ws_info.cell(row_idx, 1, label).font = font_bold
cell = ws_info.cell(row_idx, 2, val)
cell.font = font_regular
if fill:
cell.fill = fill
if label == "GP Target %:":
cell.number_format = "0.0%"
row_idx += 1
# -------------------------------------------------------------
# SHEET 2: Cabinet Library
# -------------------------------------------------------------
ws_library.views.sheetView[0].showGridLines = True
ws_library.cell(1, 1, "CABINET LIBRARY — STANDARD SPECIFICATIONS").font = font_title
lib_headers = ["Cabinet Code", "Description", "Type", "Width (in)", "Height (in)", "Depth (in)", "Finish Tier", "Door Style", "Notes"]
for col, h in enumerate(lib_headers, 1):
cell = ws_library.cell(3, col, h)
cell.font = font_header
cell.fill = fill_navy
cell.alignment = align_center
lib_data = [
("W3012", "Wall Cabinet 30W x 12H (Fridge)", "Upper", 30, 12, 12, "Standard 1", "Shaker", "Over fridge"),
("W3618", "Wall Cabinet 36W x 18H (Microwave)", "Upper", 36, 18, 12, "Standard 1", "Shaker", "Over microwave"),
("W3630", "Wall Cabinet 36W x 30H", "Upper", 36, 30, 12, "Standard 1", "Shaker", "Standard upper"),
("W3030", "Wall Cabinet 30W x 30H", "Upper", 30, 30, 12, "Standard 1", "Shaker", "Standard upper"),
("WC2430", "Corner Wall Cabinet 24W", "Upper", 24, 30, 12, "Standard 1", "Shaker", "Blind corner"),
("B36", "Base Cabinet 36W", "Lower", 36, 34.5, 24, "Standard 1", "Shaker", "Standard base"),
("B30", "Base Cabinet 30W", "Lower", 30, 34.5, 24, "Standard 1", "Shaker", "Standard base"),
("B24", "Base Cabinet 24W", "Lower", 24, 34.5, 24, "Standard 1", "Shaker", "Standard base"),
("B18", "Base Cabinet 18W", "Lower", 18, 34.5, 24, "Standard 1", "Shaker", "Standard base"),
("BC36", "Corner Base Cabinet", "Lower", 36, 34.5, 24, "Standard 1", "Shaker", "Lazy susan option"),
("T1884", "Tall Pantry 18W x 84H", "Tall", 18, 84, 24, "Standard 1", "Shaker", "Pantry"),
("T2484", "Tall Pantry 24W x 84H", "Tall", 24, 84, 24, "Standard 1", "Shaker", "Pantry"),
("T1584", "Tall Pantry 15W x 84H", "Tall", 15, 84, 24, "Standard 1", "Shaker", "Pantry (Heritage Spec)"),
("B-RO", "Base Cabinet with Roll-out Drawers", "Lower", 36, 34.5, 24, "Standard 1", "Shaker", "Roll-out drawers"),
("VAN24", "Bath Vanity 24W", "Vanity", 24, 34.5, 21, "Standard 1", "Shaker", "Single sink"),
("VAN30", "Bath Vanity 30W", "Vanity", 30, 34.5, 21, "Standard 1", "Shaker", "Single sink"),
("VAN36", "Bath Vanity 36W", "Vanity", 36, 34.5, 21, "Standard 1", "Shaker", "Single sink"),
("VAN48", "Bath Vanity 48W", "Vanity", 48, 34.5, 21, "Standard 1", "Shaker", "Double sink"),
("VAN60", "Bath Vanity 60W", "Vanity", 60, 34.5, 21, "Standard 1", "Shaker", "Double sink"),
("MED24", "Medicine Cabinet 24W", "Bath", 24, 30, 4, "Standard 1", "Mirror", "Surface mount"),
("MED30", "Medicine Cabinet 30W", "Bath", 30, 30, 4, "Standard 1", "Mirror", "Surface mount"),
("MED36", "Medicine Cabinet 36W", "Bath", 36, 30, 4, "Standard 1", "Mirror", "Surface mount"),
("MED60", "Medicine Cabinet 60W", "Bath", 60, 30, 4, "Standard 1", "Mirror", "Surface mount"),
("LIN18", "Linen Cabinet 18W x 84H", "Bath", 18, 84, 18, "Standard 1", "Shaker", "Linen"),
]
for row_offset, row in enumerate(lib_data, 4):
for col_idx, val in enumerate(row, 1):
cell = ws_library.cell(row_offset, col_idx, val)
cell.font = font_regular
cell.border = thin_border
if col_idx in [4, 5, 6]:
cell.alignment = align_right
else:
cell.alignment = align_left
# -------------------------------------------------------------
# SHEET 3: Cabinet Matrix
# -------------------------------------------------------------
ws_matrix.views.sheetView[0].showGridLines = True
ws_matrix.cell(1, 1, "CABINET MATRIX — UNIT TYPE BREAKDOWN").font = font_title
headers_m1 = ["Unit Type", "Qty", "Floor(s)", "KITCHEN — Upper Cabinets", "", "", "", "KITCHEN — Lower / Base Cabinets", "", "", "", "Kitchen Totals", "", "BATH — Vanities", "", "", "Bath Total", "Unit Grand Total"]
headers_m2 = ["Unit Type", "Qty", "Floor(s)", "Wall Cab", "Wall Cab", "Corner Wall", "Specialty", "Base Cab", "Base Cab", "Corner Base", "Specialty", "Kitchen Sub", "Kitchen Total", "Single Van", "Double Van", "Linen/Med", "Bath Sub", "UNIT TOTAL"]
for col, h in enumerate(headers_m1, 1):
cell = ws_matrix.cell(4, col, h)
cell.font = font_header
cell.fill = fill_navy
cell.alignment = align_center
for col, h in enumerate(headers_m2, 1):
cell = ws_matrix.cell(5, col, h)
cell.font = font_header
cell.fill = fill_navy
cell.alignment = align_center
# Merge columns in headers
ws_matrix.merge_cells("A4:A5")
ws_matrix.merge_cells("B4:B5")
ws_matrix.merge_cells("C4:C5")
ws_matrix.merge_cells("D4:G4")
ws_matrix.merge_cells("H4:K4")
ws_matrix.merge_cells("L4:M4")
ws_matrix.merge_cells("N4:P4")
ws_matrix.merge_cells("Q4:Q5")
ws_matrix.merge_cells("R4:R5")
# 14 Heritage Unit types
matrix_data = [
("A-1", 15, "Ground/2nd/3rd", 3, 0, 1, 1, 4, 0, 1, 1, 1, 0, 2),
("A-1a ACC", 3, "Ground/2nd/3rd", 3, 0, 1, 1, 4, 0, 1, 1, 1, 0, 2),
("B-1", 12, "Ground/2nd/3rd", 4, 0, 1, 1, 5, 0, 1, 1, 2, 0, 3),
("B-1a ACC", 3, "Ground/2nd/3rd", 4, 0, 1, 1, 5, 0, 1, 1, 2, 0, 3),
("C-1", 8, "Ground/2nd/3rd", 4, 0, 1, 1, 5, 0, 1, 1, 2, 0, 3),
("C-2", 6, "Ground/2nd/3rd", 4, 0, 1, 1, 5, 0, 1, 1, 2, 0, 3),
("C-2a ACC", 2, "Ground/2nd/3rd", 4, 0, 1, 1, 5, 0, 1, 1, 2, 0, 3),
("C-3", 6, "Ground/2nd/3rd", 4, 0, 1, 1, 5, 0, 1, 1, 2, 0, 3),
("D-1N", 4, "Ground/2nd/3rd", 5, 0, 1, 1, 6, 0, 1, 1, 2, 0, 3),
("D-1", 1, "Ground/2nd/3rd", 5, 0, 1, 1, 6, 0, 1, 1, 2, 0, 3),
("D-1a ACC", 2, "Ground/2nd/3rd", 5, 0, 1, 1, 6, 0, 1, 1, 2, 0, 3),
("D-1A ACC", 2, "Ground/2nd/3rd", 5, 0, 1, 1, 6, 0, 1, 1, 2, 0, 3),
("ST-1a ACC", 4, "Ground/2nd/3rd", 2, 0, 0, 1, 3, 0, 0, 0, 1, 0, 1),
("ST-1", 6, "Ground/2nd/3rd", 2, 0, 0, 1, 3, 0, 0, 0, 1, 0, 1),
]
for row_offset, row in enumerate(matrix_data, 6):
ws_matrix.cell(row_offset, 1, row[0]).font = font_bold
ws_matrix.cell(row_offset, 2, row[1]).font = font_regular
ws_matrix.cell(row_offset, 3, row[2]).font = font_regular
# counts
for c in range(3, 11):
ws_matrix.cell(row_offset, c + 1, row[c]).font = font_regular
# Formulas
# Kitchen Sub = Sum of Upper (D:G) + Lower (H:K)
ws_matrix.cell(row_offset, 12, f"=SUM(D{row_offset}:K{row_offset})").font = font_bold
ws_matrix.cell(row_offset, 13, f"=L{row_offset}").font = font_bold
# Bath sub vanities
ws_matrix.cell(row_offset, 14, row[11]).font = font_regular
ws_matrix.cell(row_offset, 15, row[12]).font = font_regular
ws_matrix.cell(row_offset, 16, row[13]).font = font_regular
# Bath Sub = Sum of N:P
ws_matrix.cell(row_offset, 17, f"=SUM(N{row_offset}:P{row_offset})").font = font_bold
# Unit total = Kitchen Total + Bath Sub
ws_matrix.cell(row_offset, 18, f"=M{row_offset}+Q{row_offset}").font = font_bold
# Style and border
for col_idx in range(1, 19):
cell = ws_matrix.cell(row_offset, col_idx)
cell.border = thin_border
if col_idx in [1, 3]:
cell.alignment = align_left
else:
cell.alignment = align_right
# Totals row
tot_row = 20
ws_matrix.cell(tot_row, 1, "PROJECT TOTALS").font = font_bold
ws_matrix.cell(tot_row, 2, "=SUM(B6:B19)").font = font_bold
ws_matrix.cell(tot_row, 3, "").font = font_regular
for col_idx in range(4, 19):
col_letter = get_column_letter(col_idx)
ws_matrix.cell(tot_row, col_idx, f"=SUM({col_letter}6:{col_letter}19)").font = font_bold
for col_idx in range(1, 19):
cell = ws_matrix.cell(tot_row, col_idx)
cell.border = double_bottom
cell.fill = fill_light_gray
if col_idx in [1, 3]:
cell.alignment = align_left
else:
cell.alignment = align_right
# -------------------------------------------------------------
# SHOP DRAWING SCHEDULES PER UNIT TYPE
# -------------------------------------------------------------
# Standard cabinet libraries prices (calculated in USD with 1.7820 exchange rate)
usd_catalog = {
# Upper
"W3630": round(72.9 * 1.782, 2),
"W3030": round(66.9 * 1.782, 2),
"W-REF": round(45.1 * 1.782, 2), # Over fridge wall cab
"W-MWO": round(44.1 * 1.782, 2), # Over microwave wall cab
# Base/Lower
"B36": round(73.0 * 1.782, 2),
"B-30-DW": round(66.7 * 1.782, 2), # Base DW panel
"B-SINK": round(90.0 * 1.782, 2), # Sink base 36"
"B24": round(54.1 * 1.782, 2),
"B-RO": round(129.0 * 1.782, 2), # Base roll out drawers
# Tall
"T-PANT": round(121.3 * 1.782, 2), # Pantry tall cab
# Bathroom USD Standard Catalog
"VAN-60": 379.0,
"VAN-36": 249.0,
"VAN-30": 219.0,
"MED-60": 179.0,
"MED-36": 119.0,
"MED-30": 99.0,
"LIN-18": 199.0,
}
unit_types = [
"A-1", "A-1a ACC", "B-1", "B-1a ACC", "C-1", "C-2", "C-2a ACC", "C-3",
"D-1N", "D-1", "D-1a ACC", "D-1A ACC", "ST-1a ACC", "ST-1"
]
unit_cabinet_lists = {
"ST-1": [
("Upper", "W3030", "Wall Cabinet — 30\"W x 30\"H x 12\"D", 30, 30, 12, 1, "Elev.1", "Standard upper"),
("Upper", "W-REF", "Wall Cabinet — 30\"W x 12\"H x 12\"D (Fridge)", 30, 12, 12, 1, "Elev.1", "Over fridge"),
("Upper", "W-MWO", "Wall Cabinet — 30\"W x 18\"H x 12\"D (Microwave)", 30, 18, 12, 1, "Elev.1", "Over microwave"),
("Lower", "B-30-DW", "Dishwasher Cabinet space", 30, 34.5, 24, 1, "Elev.2", "DW adjacent"),
("Lower", "B-SINK", "Sink Base Cabinet — 36\"W", 36, 34.5, 24, 1, "Elev.2", "Sink base"),
("Lower", "B24", "Base Cabinet — 24\"W", 24, 34.5, 24, 1, "Elev.2", "Standard base"),
("Vanity", "VAN-30", "Bathroom Vanity — 30\"W", 30, 34.5, 21, 1, "Floor Plan", "Single sink"),
("Bath", "MED-30", "Medicine Cabinet — 30\"W", 30, 30, 4, 1, "Floor Plan", "Mirror cabinet")
],
"ST-1a ACC": [
("Upper", "W3030", "Wall Cabinet — 30\"W x 30\"H x 12\"D", 30, 30, 12, 1, "Elev.1", "Standard upper"),
("Upper", "W-REF", "Wall Cabinet — 30\"W x 12\"H x 12\"D (Fridge)", 30, 12, 12, 1, "Elev.1", "Over fridge"),
("Upper", "W-MWO", "Wall Cabinet — 30\"W x 18\"H x 12\"D (Microwave)", 30, 18, 12, 1, "Elev.1", "Over microwave"),
("Lower", "B-30-DW", "Dishwasher Cabinet space (Accessible)", 30, 34.5, 24, 1, "Elev.2", "ADA DW adjacent"),
("Lower", "B-SINK", "Sink Base Cabinet — 36\"W (Accessible)", 36, 34.5, 24, 1, "Elev.2", "ADA Sink base"),
("Lower", "B24", "Base Cabinet — 24\"W (Accessible)", 24, 34.5, 24, 1, "Elev.2", "ADA Standard base"),
("Vanity", "VAN-30", "Bathroom Vanity — 30\"W (Accessible)", 30, 34.5, 21, 1, "Floor Plan", "ADA Single sink"),
("Bath", "MED-30", "Medicine Cabinet — 30\"W", 30, 30, 4, 1, "Floor Plan", "Mirror cabinet")
],
"A-1": [
("Upper", "W3630", "Wall Cabinet — 36\"W x 30\"H x 12\"D", 36, 30, 12, 2, "Elev.1", "Standard upper"),
("Upper", "W-REF", "Wall Cabinet — 30\"W x 12\"H x 12\"D (Fridge)", 30, 12, 12, 1, "Elev.1", "Over fridge"),
("Upper", "W-MWO", "Wall Cabinet — 30\"W x 18\"H x 12\"D (Microwave)", 30, 18, 12, 1, "Elev.1", "Over microwave"),
("Upper", "W3030", "Wall Cabinet — 30\"W x 30\"H x 12\"D", 30, 30, 12, 1, "Elev.1", "End upper"),
("Lower", "B36", "Base Cabinet — 36\"W", 36, 34.5, 24, 2, "Elev.2", "Standard base"),
("Lower", "B-30-DW", "Dishwasher Cabinet space", 30, 34.5, 24, 1, "Elev.2", "DW space"),
("Lower", "B-SINK", "Sink Base Cabinet — 36\"W", 36, 34.5, 24, 1, "Elev.2", "Sink base"),
("Lower", "B24", "Base Cabinet — 24\"W", 24, 34.5, 24, 1, "Elev.2", "Standard base"),
("Tall", "T-PANT", "Tall Pantry Cabinet — 15\"W", 15, 84, 24, 1, "Elev.2", "Tall pantry"),
("Vanity", "VAN-36", "Bathroom Vanity — 36\"W", 36, 34.5, 21, 1, "Floor Plan", "Single sink"),
("Bath", "MED-36", "Medicine Cabinet — 36\"W", 36, 30, 4, 1, "Floor Plan", "Mirror cabinet"),
("Bath", "LIN18", "Linen Cabinet — 18\"W", 18, 84, 18, 1, "Elev.3", "Linen storage")
],
"A-1a ACC": [
("Upper", "W3630", "Wall Cabinet — 36\"W x 30\"H x 12\"D", 36, 30, 12, 2, "Elev.1", "Standard upper"),
("Upper", "W-REF", "Wall Cabinet — 30\"W x 12\"H x 12\"D (Fridge)", 30, 12, 12, 1, "Elev.1", "Over fridge"),
("Upper", "W-MWO", "Wall Cabinet — 30\"W x 18\"H x 12\"D (Microwave)", 30, 18, 12, 1, "Elev.1", "Over microwave"),
("Upper", "W3030", "Wall Cabinet — 30\"W x 30\"H x 12\"D", 30, 30, 12, 1, "Elev.1", "End upper"),
("Lower", "B36", "Base Cabinet — 36\"W (Accessible)", 36, 34.5, 24, 2, "Elev.2", "ADA base"),
("Lower", "B-30-DW", "Dishwasher Cabinet space (Accessible)", 30, 34.5, 24, 1, "Elev.2", "ADA DW space"),
("Lower", "B-SINK", "Sink Base Cabinet — 36\"W (Accessible)", 36, 34.5, 24, 1, "Elev.2", "ADA Sink base"),
("Lower", "B24", "Base Cabinet — 24\"W (Accessible)", 24, 34.5, 24, 1, "Elev.2", "ADA base"),
("Tall", "T-PANT", "Tall Pantry Cabinet — 15\"W", 15, 84, 24, 1, "Elev.2", "Tall pantry"),
("Vanity", "VAN-36", "Bathroom Vanity — 36\"W (Accessible)", 36, 34.5, 21, 1, "Floor Plan", "ADA Single sink"),
("Bath", "MED-36", "Medicine Cabinet — 36\"W", 36, 30, 4, 1, "Floor Plan", "Mirror cabinet"),
("Bath", "LIN18", "Linen Cabinet — 18\"W", 18, 84, 18, 1, "Elev.3", "Linen storage")
],
"B-1": [
("Upper", "W3630", "Wall Cabinet — 36\"W x 30\"H x 12\"D", 36, 30, 12, 2, "Elev.1", "Standard upper"),
("Upper", "W3030", "Wall Cabinet — 30\"W x 30\"H x 12\"D", 30, 30, 12, 2, "Elev.1", "Wall cabinets"),
("Upper", "W-REF", "Wall Cabinet — 30\"W x 12\"H x 12\"D (Fridge)", 30, 12, 12, 1, "Elev.1", "Over fridge"),
("Upper", "W-MWO", "Wall Cabinet — 30\"W x 18\"H x 12\"D (Microwave)", 30, 18, 12, 1, "Elev.1", "Over microwave"),
("Lower", "B36", "Base Cabinet — 36\"W", 36, 34.5, 24, 2, "Elev.2", "Standard base"),
("Lower", "B-30-DW", "Dishwasher Cabinet space", 30, 34.5, 24, 1, "Elev.2", "DW space"),
("Lower", "B-SINK", "Sink Base Cabinet — 36\"W", 36, 34.5, 24, 1, "Elev.2", "Sink base"),
("Lower", "B24", "Base Cabinet — 24\"W", 24, 34.5, 24, 2, "Elev.2", "Base cabinets"),
("Tall", "T-PANT", "Tall Pantry Cabinet — 15\"W", 15, 84, 24, 1, "Elev.2", "Tall pantry"),
("Vanity", "VAN-30", "Bathroom Vanity — 30\"W", 30, 34.5, 21, 2, "Floor Plan", "Single sink"),
("Bath", "MED-30", "Medicine Cabinet — 30\"W", 30, 30, 4, 2, "Floor Plan", "Mirror cabinet"),
("Bath", "LIN18", "Linen Cabinet — 18\"W", 18, 84, 18, 1, "Elev.3", "Linen storage")
],
"B-1a ACC": [
("Upper", "W3630", "Wall Cabinet — 36\"W x 30\"H x 12\"D", 36, 30, 12, 2, "Elev.1", "Standard upper"),
("Upper", "W3030", "Wall Cabinet — 30\"W x 30\"H x 12\"D", 30, 30, 12, 2, "Elev.1", "Wall cabinets"),
("Upper", "W-REF", "Wall Cabinet — 30\"W x 12\"H x 12\"D (Fridge)", 30, 12, 12, 1, "Elev.1", "Over fridge"),
("Upper", "W-MWO", "Wall Cabinet — 30\"W x 18\"H x 12\"D (Microwave)", 30, 18, 12, 1, "Elev.1", "Over microwave"),
("Lower", "B36", "Base Cabinet — 36\"W (Accessible)", 36, 34.5, 24, 2, "Elev.2", "ADA base"),
("Lower", "B-30-DW", "Dishwasher Cabinet space (Accessible)", 30, 34.5, 24, 1, "Elev.2", "ADA DW space"),
("Lower", "B-SINK", "Sink Base Cabinet — 36\"W (Accessible)", 36, 34.5, 24, 1, "Elev.2", "ADA Sink base"),
("Lower", "B24", "Base Cabinet — 24\"W (Accessible)", 24, 34.5, 24, 2, "Elev.2", "ADA base"),
("Tall", "T-PANT", "Tall Pantry Cabinet — 15\"W", 15, 84, 24, 1, "Elev.2", "Tall pantry"),
("Vanity", "VAN-30", "Bathroom Vanity — 30\"W (Accessible)", 30, 34.5, 21, 2, "Floor Plan", "ADA Single sink"),
("Bath", "MED-30", "Medicine Cabinet — 30\"W", 30, 30, 4, 2, "Floor Plan", "Mirror cabinet"),
("Bath", "LIN18", "Linen Cabinet — 18\"W", 18, 84, 18, 1, "Elev.3", "Linen storage")
]
}
# Copy configurations for C-1 to C-3 and D-1
# C-1 to C-3 are identical
for c_type in ["C-1", "C-2", "C-2a ACC", "C-3"]:
is_acc = "ACC" in c_type or "a " in c_type
suffix = " (Accessible)" if is_acc else ""
unit_cabinet_lists[c_type] = [
("Upper", "W3630", "Wall Cabinet — 36\"W x 30\"H x 12\"D", 36, 30, 12, 3, "Elev.1", "Standard upper"),
("Upper", "W-REF", "Wall Cabinet — 30\"W x 12\"H x 12\"D (Fridge)", 30, 12, 12, 1, "Elev.1", "Over fridge"),
("Upper", "W-MWO", "Wall Cabinet — 30\"W x 18\"H x 12\"D (Microwave)", 30, 18, 12, 1, "Elev.1", "Over microwave"),
("Upper", "W3030", "Wall Cabinet — 30\"W x 30\"H x 12\"D", 30, 30, 12, 1, "Elev.1", "Wall cabinet"),
("Lower", "B36", f"Base Cabinet — 36\"W{suffix}", 36, 34.5, 24, 3, "Elev.2", "Base run"),
("Lower", "B-30-DW", f"Dishwasher Cabinet space{suffix}", 30, 34.5, 24, 1, "Elev.2", "DW space"),
("Lower", "B-SINK", f"Sink Base Cabinet — 36\"W{suffix}", 36, 34.5, 24, 1, "Elev.2", "Sink base"),
("Lower", "B24", f"Base Cabinet — 24\"W{suffix}", 24, 34.5, 24, 1, "Elev.2", "Base cabinet"),
("Tall", "T-PANT", "Tall Pantry Cabinet — 15\"W", 15, 84, 24, 1, "Elev.2", "Tall pantry"),
("Vanity", "VAN-36", f"Bathroom Vanity — 36\"W{suffix}", 36, 34.5, 21, 1, "Floor Plan", "Vanity run"),
("Vanity", "VAN-30", f"Bathroom Vanity — 30\"W{suffix}", 30, 34.5, 21, 1, "Floor Plan", "Vanity run"),
("Bath", "MED-36", "Medicine Cabinet — 36\"W", 36, 30, 4, 1, "Floor Plan", "Mirror cabinet"),
("Bath", "MED-30", "Medicine Cabinet — 30\"W", 30, 30, 4, 1, "Floor Plan", "Mirror cabinet"),
("Bath", "LIN18", "Linen Cabinet — 18\"W", 18, 84, 18, 1, "Elev.3", "Linen storage")
]
# D-1 types (D-1, D-1N, D-1a ACC, D-1A ACC)
for d_type in ["D-1", "D-1N", "D-1a ACC", "D-1A ACC"]:
is_acc = "ACC" in d_type or "a " in d_type
suffix = " (Accessible)" if is_acc else ""
unit_cabinet_lists[d_type] = [
("Upper", "W3630", "Wall Cabinet — 36\"W x 30\"H x 12\"D", 36, 30, 12, 3, "Elev.1", "Standard upper"),
("Upper", "W3030", "Wall Cabinet — 30\"W x 30\"H x 12\"D", 30, 30, 12, 2, "Elev.1", "Standard upper"),
("Upper", "W-REF", "Wall Cabinet — 30\"W x 12\"H x 12\"D (Fridge)", 30, 12, 12, 1, "Elev.1", "Over fridge"),
("Upper", "W-MWO", "Wall Cabinet — 30\"W x 18\"H x 12\"D (Microwave)", 30, 18, 12, 1, "Elev.1", "Over microwave"),
("Lower", "B36", f"Base Cabinet — 36\"W{suffix}", 36, 34.5, 24, 3, "Elev.2", "Base run"),
("Lower", "B-30-DW", f"Dishwasher Cabinet space{suffix}", 30, 34.5, 24, 1, "Elev.2", "DW space"),
("Lower", "B-SINK", f"Sink Base Cabinet — 36\"W{suffix}", 36, 34.5, 24, 1, "Elev.2", "Sink base"),
("Lower", "B24", f"Base Cabinet — 24\"W{suffix}", 24, 34.5, 24, 1, "Elev.2", "Base cabinet"),
("Lower", "B-RO", f"Base Cabinet with Roll-out Drawers{suffix}", 36, 34.5, 24, 1, "Elev.2", "Roll-out drawers"),
("Tall", "T-PANT", "Tall Pantry Cabinet — 15\"W", 15, 84, 24, 1, "Elev.2", "Tall pantry"),
("Vanity", "VAN-60", f"Bathroom Vanity — 60\"W{suffix}", 60, 34.5, 21, 1, "Floor Plan", "Double sink vanity"),
("Vanity", "VAN-36", f"Bathroom Vanity — 36\"W{suffix}", 36, 34.5, 21, 1, "Floor Plan", "Single sink vanity"),
("Bath", "MED-60", "Medicine Cabinet — 60\"W", 60, 30, 4, 1, "Floor Plan", "Double mirror"),
("Bath", "MED-36", "Medicine Cabinet — 36\"W", 36, 30, 4, 1, "Floor Plan", "Single mirror"),
("Bath", "LIN18", "Linen Cabinet — 18\"W", 18, 84, 18, 1, "Elev.3", "Linen storage")
]
# Populate worksheets
unit_material_costs = {}
for ut in unit_types:
ws_shop = wb.create_sheet(f"Shop Drawing - {ut}")
ws_shop.views.sheetView[0].showGridLines = True
# Title Block
ws_shop.cell(1, 1, "CABINET SHOP DRAWING — UNIT SCHEDULE").font = font_title
ws_shop.cell(2, 1, "Atlantic Pacific Communities | Corwil Architects").font = font_small
ws_shop.cell(4, 1, "PROJECT:").font = font_bold
ws_shop.cell(4, 2, "Heritage Village").font = font_regular
ws_shop.cell(4, 5, "UNIT TYPE:").font = font_bold
ws_shop.cell(4, 6, ut).font = font_bold
ws_shop.cell(4, 9, "DATE:").font = font_bold
ws_shop.cell(4, 10, "=TODAY()").font = font_regular
ws_shop.cell(5, 1, "ADDRESS:").font = font_bold
ws_shop.cell(5, 2, "26905 SW 142nd Ave, Homestead FL").font = font_regular
ws_shop.cell(5, 5, "DESCRIPTION:").font = font_bold
# Determine unit description
desc_str = "1-Bedroom / 1-Bath — FHA Type B"
if "ACC" in ut or "a " in ut:
if "ST" in ut:
desc_str = "Studio Apartment — Fully Accessible ADA"
elif "A-1" in ut:
desc_str = "1-Bedroom / 1-Bath — Fully Accessible ADA"
elif "B-1" in ut:
desc_str = "2-Bedroom / 2-Bath — Fully Accessible ADA"
elif "C-2" in ut:
desc_str = "3-Bedroom / 2-Bath — Fully Accessible ADA"
elif "D-1" in ut:
desc_str = "4-Bedroom / 2-Bath — Fully Accessible ADA"
else:
if "ST" in ut:
desc_str = "Studio Apartment — FHA Type B"
elif "B-1" in ut:
desc_str = "2-Bedroom / 2-Bath — FHA Type B"
elif "C-1" in ut or "C-2" in ut or "C-3" in ut:
desc_str = "3-Bedroom / 2-Bath — FHA Type B"
elif "D-1" in ut or "D-1N" in ut:
desc_str = "4-Bedroom / 2-Bath — FHA Type B"
ws_shop.cell(5, 6, desc_str).font = font_regular
ws_shop.cell(5, 9, "PREPARED BY:").font = font_bold
ws_shop.cell(5, 10, "AI Estimation System").font = font_regular
ws_shop.cell(6, 1, "DRAWING REF:").font = font_bold
ws_shop.cell(6, 2, "Heritage Unit Plans Elevation Files").font = font_regular
ws_shop.cell(6, 5, "FINISH TIER:").font = font_bold
ws_shop.cell(6, 6, "Standard 1").font = font_regular
ws_shop.cell(8, 1, "SECTION 1 — KITCHEN CABINETS").font = font_section
# Headers
headers = ["Item", "Cabinet Code", "Description", "Type", "W (in)", "H (in)", "D (in)", "Qty", "Finish Tier", "Elevation Ref.", "Location Note"]
for col_idx, h in enumerate(headers, 1):
cell = ws_shop.cell(10, col_idx, h)
cell.font = font_header
cell.fill = fill_navy
cell.alignment = align_center
cab_list = unit_cabinet_lists[ut]
row_idx = 11
kitchen_qty = 0
bath_qty = 0
kitchen_cost = 0
bath_cost = 0
item_num = 1
# Write Kitchen Cabinets
for cab in cab_list:
if cab[0] in ["Upper", "Lower", "Tall"]:
ws_shop.cell(row_idx, 1, item_num).font = font_regular
ws_shop.cell(row_idx, 2, cab[1]).font = font_bold
ws_shop.cell(row_idx, 3, cab[2]).font = font_regular
ws_shop.cell(row_idx, 4, cab[0]).font = font_regular
ws_shop.cell(row_idx, 5, cab[3]).font = font_regular
ws_shop.cell(row_idx, 6, cab[4]).font = font_regular
ws_shop.cell(row_idx, 7, cab[5]).font = font_regular
ws_shop.cell(row_idx, 8, cab[6]).font = font_regular
ws_shop.cell(row_idx, 9, "Std 1").font = font_regular
ws_shop.cell(row_idx, 10, cab[7]).font = font_regular
ws_shop.cell(row_idx, 11, cab[8]).font = font_regular
for col in range(1, 12):
cell = ws_shop.cell(row_idx, col)
cell.border = thin_border
if col in [1, 2, 3, 4, 9, 10, 11]:
cell.alignment = align_left
else:
cell.alignment = align_right
kitchen_qty += cab[6]
kitchen_cost += usd_catalog.get(cab[1], 100.0) * cab[6]
item_num += 1
row_idx += 1
# Kitchen Subtotals row
ws_shop.cell(row_idx, 1, "KITCHEN SUBTOTALS").font = font_bold
ws_shop.cell(row_idx, 8, kitchen_qty).font = font_bold
ws_shop.cell(row_idx, 1, "KITCHEN SUBTOTALS").alignment = align_left
ws_shop.cell(row_idx, 8).alignment = align_right
for col in range(1, 12):
cell = ws_shop.cell(row_idx, col)
cell.border = double_bottom
cell.fill = fill_light_gray
row_idx += 2
# Section 2: Bathroom Vanities
ws_shop.cell(row_idx, 1, "SECTION 2 — BATHROOM VANITY CABINETS").font = font_section
row_idx += 2
for col_idx, h in enumerate(headers, 1):
cell = ws_shop.cell(row_idx, col_idx, h)
cell.font = font_header
cell.fill = fill_navy
cell.alignment = align_center
row_idx += 1
item_num_bath = 1
for cab in cab_list:
if cab[0] in ["Vanity", "Bath"]:
ws_shop.cell(row_idx, 1, item_num_bath).font = font_regular
ws_shop.cell(row_idx, 2, cab[1]).font = font_bold
ws_shop.cell(row_idx, 3, cab[2]).font = font_regular
ws_shop.cell(row_idx, 4, cab[0]).font = font_regular
ws_shop.cell(row_idx, 5, cab[3]).font = font_regular
ws_shop.cell(row_idx, 6, cab[4]).font = font_regular
ws_shop.cell(row_idx, 7, cab[5]).font = font_regular
ws_shop.cell(row_idx, 8, cab[6]).font = font_regular
ws_shop.cell(row_idx, 9, "Std 1").font = font_regular
ws_shop.cell(row_idx, 10, cab[7]).font = font_regular
ws_shop.cell(row_idx, 11, cab[8]).font = font_regular
for col in range(1, 12):
cell = ws_shop.cell(row_idx, col)
cell.border = thin_border
if col in [1, 2, 3, 4, 9, 10, 11]:
cell.alignment = align_left
else:
cell.alignment = align_right
bath_qty += cab[6]
bath_cost += usd_catalog.get(cab[1], 100.0) * cab[6]
item_num_bath += 1
row_idx += 1
# Bath Subtotals row
ws_shop.cell(row_idx, 1, "BATHROOM SUBTOTALS").font = font_bold
ws_shop.cell(row_idx, 8, bath_qty).font = font_bold
ws_shop.cell(row_idx, 1, "BATHROOM SUBTOTALS").alignment = align_left
ws_shop.cell(row_idx, 8).alignment = align_right
for col in range(1, 12):
cell = ws_shop.cell(row_idx, col)
cell.border = double_bottom
cell.fill = fill_light_gray
row_idx += 2
# Grand Total row
ws_shop.cell(row_idx, 1, f"UNIT {ut} GRAND TOTAL CABINET COUNT").font = font_bold
ws_shop.cell(row_idx, 8, kitchen_qty + bath_qty).font = font_bold
ws_shop.cell(row_idx, 1).alignment = align_left
ws_shop.cell(row_idx, 8).alignment = align_right
for col in range(1, 12):
cell = ws_shop.cell(row_idx, col)
cell.border = double_bottom
cell.fill = fill_light_gray
unit_material_costs[ut] = (kitchen_cost, bath_cost)
# Auto column widths
for col in ws_shop.columns:
max_len = 0
col_letter = get_column_letter(col[0].column)
for cell in col:
val_str = str(cell.value or '')
if cell.value is not None and not val_str.startswith('='):
max_len = max(max_len, len(val_str))
ws_shop.column_dimensions[col_letter].width = max(max_len + 3, 10)
# -------------------------------------------------------------
# SHEET 4: Job Costing
# -------------------------------------------------------------
ws_costing.views.sheetView[0].showGridLines = True
ws_costing.cell(1, 1, "JOB COSTING — HERITAGE VILLAGE TOTAL ESTIMATE").font = font_title
ws_costing.cell(2, 1, "Atlantic Pacific Communities | GP Target: 35%").font = font_small
# Calculate total project kitchen & bath costs
total_kitchen_cost_all = 0
total_bath_cost_all = 0
total_kitchen_qty_all = 0
total_bath_qty_all = 0
for row_idx in range(6, 20):
ut = ws_matrix.cell(row_idx, 1).value
qty = ws_matrix.cell(row_idx, 2).value
# Remove description details from name if there
ut_clean = ut.split(' — ')[0].split(' \u2014 ')[0].strip()
k_cost_unit, b_cost_unit = unit_material_costs[ut_clean]
total_kitchen_cost_all += k_cost_unit * qty
total_bath_cost_all += b_cost_unit * qty
# Extract quantities
k_qty_unit = ws_matrix.cell(row_idx, 13).value
b_qty_unit = ws_matrix.cell(row_idx, 17).value
# Simple hardcoded counts mapping for calculations (from matrix definition)
k_qty_map = {
"A-1": 8, "A-1a ACC": 8, "B-1": 11, "B-1a ACC": 11, "C-1": 11, "C-2": 11,
"C-2a ACC": 11, "C-3": 11, "D-1N": 13, "D-1": 14, "D-1a ACC": 14, "D-1A ACC": 14,
"ST-1a ACC": 6, "ST-1": 6
}
b_qty_map = {
"A-1": 3, "A-1a ACC": 3, "B-1": 5, "B-1a ACC": 5, "C-1": 5, "C-2": 5,
"C-2a ACC": 5, "C-3": 5, "D-1N": 5, "D-1": 5, "D-1a ACC": 5, "D-1A ACC": 5,
"ST-1a ACC": 2, "ST-1": 2
}
total_kitchen_qty_all += k_qty_map[ut_clean] * qty
total_bath_qty_all += b_qty_map[ut_clean] * qty
grand_material_cost = total_kitchen_cost_all + total_bath_cost_all
grand_cabinet_count = total_kitchen_qty_all + total_bath_qty_all
# Populate Job Costing Rows
ws_costing.cell(4, 1, "A. QUANTITIES").font = font_bold
ws_costing.cell(5, 2, "Kitchen Cabinets").font = font_regular
ws_costing.cell(5, 5, total_kitchen_qty_all).font = font_bold
ws_costing.cell(5, 6, "units").font = font_regular
ws_costing.cell(6, 2, "Bath Cabinets").font = font_regular
ws_costing.cell(6, 5, total_bath_qty_all).font = font_bold
ws_costing.cell(6, 6, "units").font = font_regular
ws_costing.cell(7, 2, "TOTAL CABINETS").font = font_bold
ws_costing.cell(7, 5, "=E5+E6").font = font_bold
ws_costing.cell(7, 6, "units").font = font_regular
ws_costing.cell(8, 2, "Estimated Containers").font = font_regular
ws_costing.cell(8, 5, "=ROUNDUP(E7/220,0)").font = font_bold
ws_costing.cell(8, 6, "containers").font = font_regular
ws_costing.cell(10, 1, "B. MATERIAL COST").font = font_bold
ws_costing.cell(11, 2, "Kitchen Cabinets Cost").font = font_regular
ws_costing.cell(11, 5, total_kitchen_cost_all).font = font_regular
ws_costing.cell(11, 5).number_format = "$#,##0"
ws_costing.cell(12, 2, "Bath Cabinets Cost").font = font_regular
ws_costing.cell(12, 5, total_bath_cost_all).font = font_regular
ws_costing.cell(12, 5).number_format = "$#,##0"
ws_costing.cell(13, 2, "MATERIAL SUBTOTAL").font = font_bold
ws_costing.cell(13, 5, "=E11+E12").font = font_bold
ws_costing.cell(13, 5).number_format = "$#,##0"
# C. Cost Build-Up
ws_costing.cell(15, 1, "C. PROJECT COSTS").font = font_bold
cost_items = [
("1", "Material Cost (cabinets)", "Invoice / Price List", "", "=E13"),
("2", "Local Use Tax", "% of Material Cost", 0.075, "=E21*D22"),
("3", "Ocean Freight / Shipping", "Per Container", 4500, "=E8*D23"),
("4", "Inland Delivery", "Fixed per Project", 1200, "=D24"),
("5", "Installation", "Per Cabinet Installed", 85, "=E7*D25"),
("6", "Warehousing", "% of Material Cost", 0.02, "=E21*D26"),
("7", "Material Protection", "% of Material Cost", 0.005, "=E21*D27"),
("8", "Insurance", "% of Material Cost", 0.008, "=E21*D28"),
("9", "Miscellaneous Allowance", "Fixed", 500, "=D29"),
]
# Set headers for Cost buildup
ws_costing.cell(19, 1, "#").font = font_bold
ws_costing.cell(19, 2, "Cost Item").font = font_bold
ws_costing.cell(19, 3, "Basis / Driver").font = font_bold
ws_costing.cell(19, 4, "Rate").font = font_bold
ws_costing.cell(19, 5, "Calculated ($)").font = font_bold
ws_costing.cell(19, 6, "Notes").font = font_bold
for col in range(1, 7):
ws_costing.cell(19, col).fill = fill_light_gray
ws_costing.cell(19, col).border = thin_border
for idx, item in enumerate(cost_items, 21):
ws_costing.cell(idx, 1, item[0]).font = font_regular
ws_costing.cell(idx, 2, item[1]).font = font_regular
ws_costing.cell(idx, 3, item[2]).font = font_regular
cell_rate = ws_costing.cell(idx, 4, item[3])
cell_rate.font = font_regular
if isinstance(item[3], float) and item[3] < 1.0:
cell_rate.number_format = "0.0%"
elif isinstance(item[3], int) or isinstance(item[3], float):
cell_rate.number_format = "$#,##0"
cell_calc = ws_costing.cell(idx, 5, item[4])
cell_calc.font = font_bold
cell_calc.number_format = "$#,##0.00"
for col in range(1, 7):
ws_costing.cell(idx, col).border = thin_border
# Pre-margin subtotal
ws_costing.cell(31, 1, "PRE-MARGIN SUBTOTAL (Rows 1-9)").font = font_bold
ws_costing.cell(31, 5, "=SUM(E21:E29)").font = font_bold
ws_costing.cell(31, 5).number_format = "$#,##0.00"
for col in range(1, 7):
ws_costing.cell(31, col).fill = fill_light_gray
ws_costing.cell(31, col).border = thin_border
# Margin and Overhead
ws_costing.cell(33, 1, "D. MARGIN & OVERHEAD").font = font_bold
ws_costing.cell(34, 1, "10").font = font_regular
ws_costing.cell(34, 2, "Commission").font = font_regular
ws_costing.cell(34, 3, "% of Selling Price").font = font_regular
ws_costing.cell(34, 4, 0.05).font = font_regular
ws_costing.cell(34, 4).number_format = "0.0%"
ws_costing.cell(34, 5, "=E46*D34").font = font_bold
ws_costing.cell(34, 5).number_format = "$#,##0.00"
ws_costing.cell(35, 1, "11").font = font_regular
ws_costing.cell(35, 2, "Bond").font = font_regular
ws_costing.cell(35, 3, "% of Selling Price").font = font_regular
ws_costing.cell(35, 4, 0.015).font = font_regular
ws_costing.cell(35, 4).number_format = "0.0%"
ws_costing.cell(35, 5, "=E46*D35").font = font_bold
ws_costing.cell(35, 5).number_format = "$#,##0.00"
ws_costing.cell(36, 1, "12").font = font_regular
ws_costing.cell(36, 2, "Gross Profit").font = font_regular
ws_costing.cell(36, 3, "% of Selling Price").font = font_regular
ws_costing.cell(36, 4, 0.35).font = font_regular
ws_costing.cell(36, 4).number_format = "0.0%"
ws_costing.cell(36, 5, "=E46*D36").font = font_bold
ws_costing.cell(36, 5).number_format = "$#,##0.00"
for r in [34, 35, 36]:
for c in range(1, 7):
ws_costing.cell(r, c).border = thin_border
# Selling price calculation formula
ws_costing.cell(39, 1, "E. SELLING PRICE CALCULATION").font = font_bold
ws_costing.cell(40, 1, "Pre-Margin Cost:").font = font_bold
ws_costing.cell(40, 2, "=E31").font = font_regular
ws_costing.cell(40, 2).number_format = "$#,##0.00"
ws_costing.cell(41, 1, "GP Target %:").font = font_bold
ws_costing.cell(41, 2, "=D36").font = font_regular
ws_costing.cell(41, 2).number_format = "0.0%"
ws_costing.cell(42, 1, "Commission %:").font = font_bold
ws_costing.cell(42, 2, "=D34").font = font_regular
ws_costing.cell(42, 2).number_format = "0.0%"
ws_costing.cell(43, 1, "Bond %:").font = font_bold
ws_costing.cell(43, 2, "=D35").font = font_regular
ws_costing.cell(43, 2).number_format = "0.0%"
# SELLING PRICE (TOTAL PROJECT)
ws_costing.cell(46, 1, "SELLING PRICE (TOTAL PROJECT):").font = font_bold
ws_costing.cell(46, 5, "=IF(1-D36-D34-D35<=0,\"ERROR\",E31/(1-D36-D34-D35))").font = font_title
ws_costing.cell(46, 5).fill = fill_green_calc
ws_costing.cell(46, 5).number_format = "$#,##0.00"
# Verification
ws_costing.cell(48, 1, "VERIFICATION").font = font_bold
ws_costing.cell(49, 1, "Gross Profit $:").font = font_bold
ws_costing.cell(49, 5, "=E46*D36").font = font_bold
ws_costing.cell(49, 5).number_format = "$#,##0.00"
ws_costing.cell(50, 1, "Gross Profit %:").font = font_bold
ws_costing.cell(50, 5, "=IF(E46>0,E49/E46,0)").font = font_bold
ws_costing.cell(50, 5).number_format = "0.0%"
ws_costing.cell(51, 1, "Total Cost $:").font = font_bold
ws_costing.cell(51, 5, "=E46-E49").font = font_bold
ws_costing.cell(51, 5).number_format = "$#,##0.00"
ws_costing.cell(52, 1, "Cost per Cabinet:").font = font_bold
ws_costing.cell(52, 5, "=IF(E7>0,E51/E7,0)").font = font_bold
ws_costing.cell(52, 5).number_format = "$#,##0.00"
ws_costing.cell(53, 1, "Sell per Cabinet:").font = font_bold
ws_costing.cell(53, 5, "=IF(E7>0,E46/E7,0)").font = font_bold
ws_costing.cell(53, 5).number_format = "$#,##0.00"
for col in ws_costing.columns:
max_len = 0
col_letter = get_column_letter(col[0].column)
for cell in col:
val_str = str(cell.value or '')
if cell.value is not None and not val_str.startswith('='):
max_len = max(max_len, len(val_str))
ws_costing.column_dimensions[col_letter].width = max(max_len + 3, 15)
# Save the workbook
wb.save(OUTPUT_PATH)
print(f"Workbook compiled successfully and saved to: {OUTPUT_PATH}")
-615
View File
@@ -1,615 +0,0 @@
#!/usr/bin/env python3
"""
===========================================================================
HERITAGE VILLAGE — PRODUCTION SHOP DRAWINGS COMPILER & RECONSTRUCTOR v1.0
===========================================================================
This script programmatically compiles the 16-page tabloid shop drawing package:
- Page 1: COVER (dynamically generated from project data)
- Page 2: MATRIX (dynamically generated from unit quantities)
- Pages 3-16: Vector-level reconstruction from the client's 14 unit plan PDFs,
separating the drawing graphics from the title blocks, and wrapping each
sheet with our dynamic, uniform title block layout.
All CAD elements (lines, arcs, dimensions, text rotation, dashes) are copied
with 100% precision, producing a crisp, vector-grade print PDF.
===========================================================================
"""
import math
import os
import re
import fitz # PyMuPDF
from reportlab.lib.pagesizes import landscape
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor, black, white
# ── Page & Scale Constants ─────────────────────────────────────────────────
PAGE_W = 1224.0 # 17" × 72pt/in
PAGE_H = 792.0 # 11" × 72pt/in
# ── Title-block geometry ───────────────────────────────────────────────────
TB_X = 1161.6
TB_W = 62.4
TB_COLS = [TB_X + i*14.4 for i in range(5)] + [TB_X + TB_W]
# ── Drawing area ──────────────────────────────────────────────────────────
DA_L = 18.0
DA_R = TB_X - 4.0
DA_T = 8.0
DA_B = PAGE_H - 14.0
# ── Colors ────────────────────────────────────────────────────────────────
BLACK = HexColor('#000000')
GRAY = HexColor('#D0D0D0')
DKGRAY = HexColor('#888888')
WHITE = HexColor('#FFFFFF')
# ══════════════════════════════════════════════════════════════════════════
# REAL PROJECT DATA
# ══════════════════════════════════════════════════════════════════════════
PROJECT = {
"name": "HERITAGE VILLAGE",
"id": "23-045",
"date": "05/16/2025",
"revision": "17.0",
"drawn_by": "A.C",
"dimensions": "CM|INCHES",
"scope": "KITCHEN | VANITIES",
"finish": "K019 SILVER LIBERTY ELM",
"company": {
"name": "ITALIAN KITCHEN AND BATH",
"tagline": "kitchen | bath | tile | closet",
"address": "1777 NW 72TH AVE. MIAMI FL, 33126",
"phone": "T. 305.599.9000 F. 305.599.9870",
},
"revision_log": [
("1.0", "12/21/2023", "Y.J", "INITIAL RELEASE"),
("5.0", "04/26/2024", "M.A", "COORDINATION"),
("15.0", "01/07/2025", "T.A", "ADA/FHA REVISION"),
("17.0", "04/21/2025", "A.C", "COORDINATION"),
],
"appliances_regular": [
'30" REFRIGERATOR GE MODEL GTE18GSNRSS',
'24" DISHWASHER GE MODEL GDT535PSRSS',
'30" RANGE GE MODEL GRF400PV',
'30" MICROWAVE GE MODEL JVM3160RFSS',
],
"appliances_ada": [
'30" REFRIGERATOR GE MODEL GTE18GSNRSS',
'24" DISHWASHER GE MODEL GDT225SSLSS (ADA)',
'30" RANGE GE MODEL GRS500PVSS (ADA)',
'30" MICROWAVE GE MODEL JES1145SHSS',
'30" HOOD GE MODEL JVX3300SJSS',
],
"general_notes": [
"*ALL DIMENSIONS ARE FROM FINISHED WALL TO FINISHED WALL",
"*ALL DIMENSIONS ARE FROM FINISHED FLOOR TO FINISHED CEILING",
"*NOT INCLUDED: APPLIANCES, FIXTURES, PLUMBING, AND COUNTER TOPS",
"*IT'S ARCHITECT'S RESPONSIBILITY TO CONFIRM KITCHEN & VANITY",
" CABINETS COMPLY WITH BUILDING FHA & ADA CODES.",
],
}
UNIT_MATRIX = [
{"unit": "A-1", "desc": "1BR/1Bath FHA", "qty": 15, "u": 4, "l": 4, "t": 0, "b": 3},
{"unit": "A-1a ACC", "desc": "1BR/1Bath Accessible", "qty": 3, "u": 4, "l": 4, "t": 0, "b": 3},
{"unit": "B-1", "desc": "2BR/2Bath FHA", "qty": 12, "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "B-1a ACC", "desc": "2BR/2Bath Accessible", "qty": 3, "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "C-1", "desc": "3BR/2Bath FHA", "qty": 8, "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "C-2", "desc": "3BR/2Bath FHA", "qty": 6, "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "C-2a ACC", "desc": "3BR/2Bath Accessible", "qty": 2, "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "C-3", "desc": "3BR/2Bath FHA", "qty": 6, "u": 5, "l": 5, "t": 0, "b": 5},
{"unit": "D-1N", "desc": "4BR/2Bath FHA (North)", "qty": 4, "u": 6, "l": 6, "t": 0, "b": 5},
{"unit": "D-1", "desc": "4BR/2Bath FHA", "qty": 1, "u": 6, "l": 6, "t": 0, "b": 5},
{"unit": "D-1a ACC", "desc": "4BR/2Bath Accessible", "qty": 2, "u": 6, "l": 6, "t": 0, "b": 5},
{"unit": "D-1A ACC", "desc": "4BR/2Bath Accessible", "qty": 2, "u": 6, "l": 6, "t": 0, "b": 5},
{"unit": "ST-1a ACC", "desc": "Studio Accessible", "qty": 4, "u": 3, "l": 3, "t": 0, "b": 2},
{"unit": "ST-1", "desc": "Studio FHA", "qty": 6, "u": 3, "l": 3, "t": 0, "b": 2},
]
# ══════════════════════════════════════════════════════════════════════════
# TITLE BLOCK (exact ItalianKB layout)
# ══════════════════════════════════════════════════════════════════════════
def draw_title_block(c, project, sheet_type, sheet_num, big_title="", sub_title=""):
c.saveState()
c.setStrokeColor(BLACK)
c.setFillColor(WHITE)
c.rect(TB_X, 0, TB_W, PAGE_H, stroke=1, fill=1)
def hline(y, lw=0.4):
c.setLineWidth(lw)
c.line(TB_X, y, TB_X+TB_W, y)
def vline(x, y0, y1, lw=0.3):
c.setLineWidth(lw)
c.line(x, y0, x, y1)
# Section borders
hline(537, 0.6); hline(645, 0.5); hline(758, 0.5); hline(774, 0.5)
c.setLineWidth(0.8); c.line(TB_X, 0, TB_X, PAGE_H)
# Sub-column verticals — company section
for x in TB_COLS[1:5]:
vline(x, 0, 537)
# Sub-column verticals — project section
for x in TB_COLS[1:4]:
vline(x, 537, 645)
# Sub-column verticals — info section
for x in TB_COLS[1:4]:
vline(x, 645, 758)
# ── Company section: rotated text ────────────────────────────────────
_rot_col(c, project["company"]["name"], TB_COLS[0], TB_COLS[1], 0, 537, 14, "Helvetica-Bold")
_rot_col(c, project["company"]["tagline"], TB_COLS[1], TB_COLS[2], 0, 537, 5.5, "Helvetica")
_rot_col(c, project["company"]["address"], TB_COLS[2], TB_COLS[3], 0, 537, 5.5, "Helvetica")
_rot_col(c, project["company"]["phone"], TB_COLS[3], TB_COLS[4], 0, 537, 5.5, "Helvetica")
# ── Project section ───────────────────────────────────────────────────
_rot_label_value(c, "PROJECT #:", project["id"], TB_COLS[0], TB_COLS[1], 537, 645)
_rot_label_value(c, "", project["name"], TB_COLS[1], TB_COLS[2], 537, 645)
_rot_label_value(c, "", sheet_type, TB_COLS[2], TB_COLS[3], 537, 645)
# ── Info section ─────────────────────────────────────────────────────
_rot_label_value(c, "DATE:", project["date"], TB_COLS[0], TB_COLS[1], 645, 758)
_rot_label_value(c, "REV:", project["revision"], TB_COLS[1], TB_COLS[2], 645, 758)
_rot_label_value(c, "DIMENSION:", project["dimensions"], TB_COLS[2], TB_COLS[3], 645, 758)
_rot_label_value(c, "DRAWN BY:", project["drawn_by"], TB_COLS[3], TB_COLS[4], 645, 758)
# ── Sheet number ─────────────────────────────────────────────────────
mx = TB_X + TB_W/2
c.setFont("Helvetica", 4.5); c.setFillColor(BLACK)
c.drawCentredString(mx, 766, "SHEET NUMBER")
c.setFont("Helvetica-Bold", 8)
c.drawCentredString(mx, 779, sheet_num)
# ── Page title top-right (only drawn if specified dynamically) ─────────
if big_title:
c.setFont("Helvetica-Bold", 26); c.setFillColor(BLACK)
c.drawRightString(TB_X - 8, PAGE_H - 40, big_title)
if sub_title:
c.setFont("Helvetica-Bold", 15)
c.drawRightString(TB_X - 8, PAGE_H - 60, sub_title)
# ── Page border ───────────────────────────────────────────────────────
c.setStrokeColor(BLACK); c.setLineWidth(0.8)
c.rect(DA_L, 14, DA_R - DA_L, PAGE_H - 22, stroke=1, fill=0)
c.restoreState()
def _rot_col(c, text, x0, x1, y0, y1, size, font="Helvetica"):
cx = (x0 + x1)/2
cy = (y0 + y1)/2
c.saveState()
c.setFont(font, size); c.setFillColor(BLACK)
c.translate(cx, cy); c.rotate(90)
c.drawCentredString(0, -size*0.35, text)
c.restoreState()
def _rot_label_value(c, label, value, x0, x1, y0, y1):
cx = (x0 + x1)/2
c.saveState()
c.setFillColor(BLACK)
if label:
c.setFont("Helvetica-Bold", 5.5)
c.translate(cx, y1 - 10); c.rotate(90)
c.drawString(0, -3, label)
c.restoreState(); c.saveState()
c.setFont("Helvetica", 7)
c.translate(cx, (y0+y1)/2); c.rotate(90)
c.drawCentredString(0, -3, value)
c.restoreState()
# ══════════════════════════════════════════════════════════════════════════
# DYNAMIC COVER PAGE
# ══════════════════════════════════════════════════════════════════════════
def build_cover(c, proj):
draw_title_block(c, proj, "KITCHEN | VANITIES", "COVER",
"HERITAGE VILLAGE", "KITCHEN | VANITY SHOP-DWGS")
# Project name
c.setFont("Helvetica-Bold", 52); c.setFillColor(BLACK)
c.drawString(DA_L+10, PAGE_H-80, proj["name"])
c.setFont("Helvetica", 18)
c.drawString(DA_L+10, PAGE_H-105, "KITCHEN | VANITY | LAUNDRY SHOP-DRAWINGS")
# Divider line
c.setLineWidth(1.5)
c.line(DA_L+10, PAGE_H-115, DA_R-10, PAGE_H-115)
# FINISH box
y = PAGE_H-130
_info_box(c, "FINISH:", [f"- {proj['finish']}"],
DA_L+10, y, 880, 42)
# APPLIANCES box
y -= 52
app = (["REGULAR UNITS:"] +
[f" {a}" for a in proj["appliances_regular"]] +
["", "ADA UNITS:"] +
[f" {a}" for a in proj["appliances_ada"]])
_info_box(c, "APPLIANCES:", app, DA_L+10, y, 880, 195)
# GENERAL NOTES box
y -= 205
_info_box(c, "GENERAL NOTES:", proj["general_notes"], DA_L+10, y, 880, 100)
# REVISION LOG
y -= 120
_rev_table(c, proj["revision_log"], DA_L+500, y)
# Branding bottom
c.setFont("Helvetica", 8); c.setFillColor(HexColor('#555555'))
c.drawString(DA_L+10, 25, "OWNER: ATLANTIC PACIFIC COMMUNITIES | 26905 SW 142nd Ave, Homestead FL")
def _info_box(c, title, lines, x, y_top, w, h):
c.saveState()
c.setStrokeColor(BLACK); c.setFillColor(WHITE); c.setLineWidth(0.7)
c.rect(x, y_top-h, w, h, stroke=1, fill=1)
c.setFont("Helvetica-Bold", 10); c.setFillColor(BLACK)
c.drawString(x+8, y_top-15, title)
c.setFont("Helvetica", 9)
lh = 13
for i, line in enumerate(lines):
c.drawString(x+8, y_top-29-i*lh, line)
c.restoreState()
def _rev_table(c, revs, x, y_top):
c.saveState()
cols = [35, 75, 55, 130]
hdrs = ["REV.", "DATE", "BY", "DESCRIPTION"]
rh, tw= 16, sum(cols)
c.setFont("Helvetica-Bold", 8); c.setFillColor(BLACK)
c.drawCentredString(x+tw/2, y_top+6, "REVISION LOG")
c.setLineWidth(0.5)
# Header
c.rect(x, y_top-rh, tw, rh, stroke=1, fill=0)
cx = x
for h, cw in zip(hdrs, cols):
c.drawCentredString(cx+cw/2, y_top-rh+4, h)
if cx > x: c.line(cx, y_top-rh, cx, y_top)
cx += cw
# Rows
for i in range(10):
ry = y_top - rh*(i+2)
c.rect(x, ry, tw, rh, stroke=1, fill=0)
if i < len(revs):
vals = list(revs[i])
cx = x
c.setFont("Helvetica", 8)
for j, (v, cw) in enumerate(zip(vals, cols)):
c.drawCentredString(cx+cw/2, ry+4, str(v))
if j > 0: c.line(cx, ry, cx, ry+rh)
cx += cw
c.restoreState()
# ══════════════════════════════════════════════════════════════════════════
# DYNAMIC MATRIX PAGE
# ══════════════════════════════════════════════════════════════════════════
def build_matrix(c, proj, matrix):
draw_title_block(c, proj, "KITCHEN | VANITIES", "MATRIX",
"HERITAGE VILLAGE", "MATRIX")
c.setFont("Helvetica-Bold", 48); c.setFillColor(BLACK)
c.drawString(DA_L+10, PAGE_H-78, proj["name"])
c.setFont("Helvetica-Bold", 24)
c.drawString(DA_L+10, PAGE_H-108, "MATRIX")
# Table columns centered
cols = [90, 160, 30, 45, 45, 45, 45, 45, 45, 60, 60]
heads = ["UNIT TYPE", "DESCRIPTION", "QTY", "KIT. UPPER", "KIT. LOWER", "KIT. TALL", "KIT. TOTAL", "BATH CABS", "UNIT TOTAL", "PROJ. KIT.", "PROJ. BATH"]
rh, tw = 16, sum(cols)
tx, ty = DA_L + (1139.6 - tw)/2, PAGE_H-135
# Table header row
c.setLineWidth(0.5)
c.rect(tx, ty-32, tw, 32, stroke=1, fill=0)
cx = tx
c.setFont("Helvetica-Bold", 7.5)
for h, cw in zip(heads, cols):
ls = h.split("\n")
for li, l in enumerate(ls):
c.drawCentredString(cx+cw/2, ty-14+li*(-10), l)
if cx > tx: c.line(cx, ty-32, cx, ty)
cx += cw
def row(ry, label, desc, data, bold=False):
c.setLineWidth(0.5)
c.rect(tx, ry, tw, rh, stroke=1, fill=0)
fn = "Helvetica-Bold" if bold else "Helvetica"
c.setFont(fn, 8); c.setFillColor(BLACK)
vals = [
label, desc, data.get("qty",""), data.get("u",""),
data.get("l",""), data.get("t",""), data.get("kt",""),
data.get("b",""), data.get("ut",""), data.get("pk",""),
data.get("pb","")
]
cx = tx
for i, (v, cw) in enumerate(zip(vals, cols)):
if v not in (0, ""):
if i == 1: # description left-aligned
c.drawString(cx+4, ry+4, str(v))
elif i == 0: # label left-aligned if bold
c.drawString(cx+4, ry+4, str(v))
else:
c.drawCentredString(cx+cw/2, ry+4, str(v))
if i > 0: c.line(cx, ry, cx, ry+rh)
cx += cw
ry = ty - 32
tot_qty = 0
tot_pk = 0
tot_pb = 0
for r in matrix:
ry -= rh
qty = r["qty"]
kt = r["u"] + r["l"] + r["t"]
ut = kt + r["b"]
pk = kt * qty
pb = r["b"] * qty
row(ry, r["unit"], r["desc"],
{"qty": qty, "u": r["u"], "l": r["l"], "t": r["t"] or "",
"kt": kt, "b": r["b"], "ut": ut, "pk": pk, "pb": pb})
tot_qty += qty
tot_pk += pk
tot_pb += pb
# Totals row
ry -= rh
c.setFont("Helvetica-Bold", 8.5); c.setFillColor(BLACK)
c.rect(tx, ry, tw, rh, stroke=1, fill=0)
vals = ["PROJECT TOTALS", "", tot_qty, "", "", "", "", "", "", tot_pk, tot_pb]
cx = tx
for i, (v, cw) in enumerate(zip(vals, cols)):
if v not in (0, ""):
if i == 0:
c.drawString(cx+4, ry+4, str(v))
else:
c.drawCentredString(cx+cw/2, ry+4, str(v))
if i > 0: c.line(cx, ry, cx, ry+rh)
cx += cw
# Summary totals
c.setFont("Helvetica-Bold", 11); c.setFillColor(BLACK)
c.drawString(tx+50, ry-30, f"KITCHEN TOTAL QTY = {tot_pk}")
c.drawString(tx+50, ry-50, f"VANITY TOTAL QTY = {tot_pb}")
# ══════════════════════════════════════════════════════════════════════════
# RECONSTRUCTION DRAWING HELPERS
# ══════════════════════════════════════════════════════════════════════════
def set_rl_dashes(canvas, dashes_str):
if not dashes_str or dashes_str == "[] 0":
canvas.setDash([])
return
try:
arr_part = dashes_str.split(']')[0].replace('[', '').strip()
phase = 0
parts = dashes_str.split(']')
if len(parts) > 1:
try:
phase = float(parts[1].strip())
except ValueError:
pass
if arr_part:
dashes = [float(x) for x in arr_part.split()]
canvas.setDash(dashes, phase)
else:
canvas.setDash([])
except Exception:
canvas.setDash([])
def reconstruct_heritage_page(ref_doc, out_canvas):
page = ref_doc[0]
# Heritage page is 3024 x 2160.
# We want to crop at x=2800 to exclude the architect's title block on the right.
# Target drawing area width is DA_R - DA_L = 1139.6, height is 764.0
orig_w = 2800.0
orig_h = 2160.0
scale_w = 1139.6 / orig_w
scale_h = 764.0 / orig_h
scale = min(scale_w, scale_h)
tx = DA_L
ty = 14.0 + (764.0 - orig_h * scale) / 2
# 1. Reconstruct vector drawings
drawings = page.get_drawings()
for draw in drawings:
rect = draw.get("rect", fitz.Rect(0,0,0,0))
# Skip drawings in title block area (x > 2800)
if rect.x0 > 2800:
continue
fill_color = draw.get("fill")
stroke_color = draw.get("color")
stroke_width = draw.get("width", 0.5)
stroke_dashes = draw.get("dashes", "[] 0")
out_canvas.saveState()
# Apply transformation
out_canvas.translate(tx, ty)
out_canvas.scale(scale, scale)
# Translate PyMuPDF coordinates (top-left origin, y increases down)
# to ReportLab coordinates within the scaled viewport (bottom-left origin, y increases up)
# In the scaled viewport, the drawing height is 2160.
def map_coords(x, y):
return x, 2160.0 - y
if fill_color:
r, g, b = [int(max(0.0, min(1.0, c)) * 255) for c in fill_color]
out_canvas.setFillColor(HexColor(f"#{r:02x}{g:02x}{b:02x}"))
if stroke_color:
r, g, b = [int(max(0.0, min(1.0, c)) * 255) for c in stroke_color]
out_canvas.setStrokeColor(HexColor(f"#{r:02x}{g:02x}{b:02x}"))
out_canvas.setLineWidth(stroke_width)
set_rl_dashes(out_canvas, stroke_dashes)
fill = 1 if fill_color else 0
stroke = 1 if stroke_color else 0
path = out_canvas.beginPath()
for item in draw.get("items", []):
if item[0] == "l":
p1 = map_coords(item[1].x, item[1].y)
p2 = map_coords(item[2].x, item[2].y)
path.moveTo(p1[0], p1[1])
path.lineTo(p2[0], p2[1])
elif item[0] == "re":
r = item[1]
p1 = map_coords(r.x0, r.y1)
path.rect(p1[0], p1[1], r.width, r.height)
elif item[0] == "c":
p1 = map_coords(item[1].x, item[1].y)
p2 = map_coords(item[2].x, item[2].y)
p3 = map_coords(item[3].x, item[3].y)
p4 = map_coords(item[4].x, item[4].y)
path.moveTo(p1[0], p1[1])
path.curveTo(p2[0], p2[1], p3[0], p3[1], p4[0], p4[1])
if draw.get("closePath"):
path.close()
out_canvas.drawPath(path, fill=fill, stroke=stroke)
out_canvas.restoreState()
# 2. Reconstruct text spans
text_dict = page.get_text("dict")
for block in text_dict.get("blocks", []):
if block.get("type") == 0:
for line in block.get("lines", []):
line_dir = line.get("dir", (1.0, 0.0))
for span in line.get("spans", []):
if span["bbox"][0] > 2800:
continue
text_str = span["text"]
size = span["size"]
font = span["font"]
color = span["color"]
out_canvas.saveState()
# Apply translation and scaling
out_canvas.translate(tx, ty)
out_canvas.scale(scale, scale)
# Colors
r = (color >> 16) & 255
g = (color >> 8) & 255
b = color & 255
out_canvas.setFillColor(HexColor(f"#{r:02x}{g:02x}{b:02x}"))
font_name = "Helvetica"
if "bold" in font.lower():
font_name = "Helvetica-Bold"
elif "italic" in font.lower():
font_name = "Helvetica-Oblique"
out_canvas.setFont(font_name, size)
# Map coordinates within scaled viewport
orig_x, orig_y = span["origin"]
rx, ry = orig_x, 2160.0 - orig_y
dx, dy = line_dir
rl_angle_rad = math.atan2(-dy, dx)
rl_angle_deg = math.degrees(rl_angle_rad)
if abs(rl_angle_deg) > 0.01:
out_canvas.translate(rx, ry)
out_canvas.rotate(rl_angle_deg)
out_canvas.drawString(0, 0, text_str)
else:
out_canvas.drawString(rx, ry, text_str)
out_canvas.restoreState()
# ══════════════════════════════════════════════════════════════════════════
# MAIN PROGRAM PIPELINE
# ══════════════════════════════════════════════════════════════════════════
def compile_heritage_shop_drawings(ref_dir_path, output_pdf_path):
print(f"\n===========================================================================")
print(f"HERITAGE VILLAGE — PRODUCTION SHOP DRAWINGS COMPILER")
print(f"===========================================================================")
print(f" Reference Directory: {ref_dir_path}")
print(f" Output PDF: {output_pdf_path}")
if not os.path.exists(ref_dir_path):
raise FileNotFoundError(f"Reference folder not found at: {ref_dir_path}")
c = canvas.Canvas(output_pdf_path, pagesize=(PAGE_W, PAGE_H))
c.setTitle(f"Shop Drawings — {PROJECT['name']} — {PROJECT['id']}")
c.setAuthor("ITALIAN KITCHEN AND BATH")
c.setSubject("Kitchen & Vanity Shop Drawings")
c.setCreator("AI Production Compiler v1.0")
# ── Page 1: Dynamic Cover ─────────────────────────────────────────────
print(" [01/16] Compiling COVER (dynamic)...")
build_cover(c, PROJECT)
c.showPage()
# ── Page 2: Dynamic Matrix ────────────────────────────────────────────
print(" [02/16] Compiling MATRIX (dynamic)...")
build_matrix(c, PROJECT, UNIT_MATRIX)
c.showPage()
# ── Pages 3-16: Reconstructed CAD Drawings ───────────────────────────
unit_drawings = [
("A-6.00", "UNIT A-1", "A-6.00_ UNIT A-1 -FHA - FLOOR PLANS & DETAILS Rev.17 markup.pdf"),
("A-6.01", "UNIT A-1A ACC", "A-6.01_ UNIT A-1A ACC FLOOR PLANS & DETAILS Rev.17 markup.pdf"),
("A-6.02", "UNIT B-1", "A-6.02_ UNIT B-1 FLOOR PLANS & DETAILS Rev.17 markup.pdf"),
("A-6.03", "UNIT B-1A ACC", "A-6.03_ UNIT B-1A ACC FLOOR PLANS & DETAILS Rev.17 markup.pdf"),
("A-6.04", "UNIT C-1", "A-6.04_ UNIT C-1 - FHA FLOOR PLANS & DETAILS Rev.17 markup.pdf"),
("A-6.05", "UNIT C-2", "A-6.05 - UNIT C-2 - FHA - FLOOR PLANS & DETAILS.pdf"),
("A-6.06", "UNIT C-2a ACC", "A-6.06 - UNIT C-2a ACC- FLOOR PLANS & DETAILS-.pdf"),
("A-6.07", "UNIT C-3", "A-6.07_ UNIT C-3 FLOOR PLANS & DETAILS Rev.15 markup.pdf"),
("A-6.08A", "UNIT D-1N", "A-6.08A_ UNIT D-1N- FHA - FLOOR PLANS AND DETAILS Rev.15 markup.pdf"),
("A-6.08", "UNIT D-1", "A-6.08_ UNIT D-1 - FHA FLOOR PLANS & DETAILS Rev.17 markup.pdf"),
("A-6.09A", "UNIT D-1a ACC", "A-6.09A_ UNIT D-1a ACC. FLOOR PLANS & DETAILS (CONTINUED) Rev.15 markup.pdf"),
("A-6.09", "UNIT D-1A ACC", "A-6.09_ UNIT D-1A ACC FLOOR PLANS AND DETAILS Rev.15 markup.pdf"),
("A-6.10", "UNIT ST-1A ACC", "A-6.10_ UNIT ST-1A ACC FLOOR PLANS & DETAILS Rev.15 markup.pdf"),
("A-6.11", "UNIT ST-1", "A-6.11_ UNIT ST-1 - FHA FLOOR PLANS & DETAILS Rev.15 markup.pdf")
]
for idx, (sheet_num, unit_label, file_name) in enumerate(unit_drawings):
page_num = idx + 3
ref_pdf_path = os.path.join(ref_dir_path, file_name)
print(f" [{page_num:02d}/16] Reconstructing Sheet {sheet_num:7s} ({unit_label})...")
ref_doc = fitz.open(ref_pdf_path)
reconstruct_heritage_page(ref_doc, c)
ref_doc.close()
# Draw standardized title block
draw_title_block(c, PROJECT, "KITCHEN | VANITIES", sheet_num)
c.showPage()
c.save()
print(f"\n [OK] Saved: {output_pdf_path}")
print(f" Total compiled pages: 16")
if __name__ == "__main__":
REF_DIR = r"C:\Users\prajw\OneDrive\Desktop\Albert\Albert_Project\Heritage\01_Architectural_Drawings\Unit_Plans_FHA_ADA"
OUT_PDF = r"C:\Users\prajw\OneDrive\Desktop\Albert\Albert_Project\Heritage\03_Shop_Drawings\05_Cabinet_Estimation_Shop_Drawings_Heritage_Village.pdf"
compile_heritage_shop_drawings(REF_DIR, OUT_PDF)
-588
View File
@@ -1,588 +0,0 @@
#!/usr/bin/env python3
"""
===========================================================================
CASA FAMILIA — PRODUCTION SHOP DRAWINGS COMPILER & RECONSTRUCTOR v5.0
===========================================================================
This script programmatically reconstructs the 23-page shop drawing package:
- Page 1: COVER (dynamically generated from project data)
- Page 2: MATRIX (dynamically generated from unit quantities)
- Pages 3-23: Vector-level reconstruction from the client's reference PDF,
separating the drawing graphics from the title blocks, and wrapping each
sheet with our dynamic, uniform title block layout.
All CAD elements (lines, arcs, dimensions, text rotation, dashes) are copied
with 100% precision, producing a crisp, vector-grade print PDF.
===========================================================================
"""
import math
import os
import re
import fitz # PyMuPDF
from reportlab.lib.pagesizes import landscape
from reportlab.pdfgen import canvas
from reportlab.lib.colors import HexColor, black, white
# ── Page & Scale Constants ─────────────────────────────────────────────────
PAGE_W = 1224.0 # 17" × 72pt/in
PAGE_H = 792.0 # 11" × 72pt/in
# ── Title-block geometry ───────────────────────────────────────────────────
TB_X = 1161.6
TB_W = 62.4
TB_COLS = [TB_X + i*14.4 for i in range(5)] + [TB_X + TB_W]
# ── Drawing area ──────────────────────────────────────────────────────────
DA_L = 18.0
DA_R = TB_X - 4.0
DA_T = 8.0
DA_B = PAGE_H - 14.0
# ── Colors ────────────────────────────────────────────────────────────────
BLACK = HexColor('#000000')
GRAY = HexColor('#D0D0D0')
DKGRAY = HexColor('#888888')
WHITE = HexColor('#FFFFFF')
# ══════════════════════════════════════════════════════════════════════════
# REAL PROJECT DATA
# ══════════════════════════════════════════════════════════════════════════
PROJECT = {
"name": "CASA FAMILIA",
"id": "23-033",
"date": "11/05/2024",
"revision": "5.0",
"drawn_by": "A.C",
"dimensions": "CM|INCHES",
"scope": "KITCHEN | VANITIES",
"finish": "K019 SILVER LIBERTY ELM",
"company": {
"name": "ITALIAN KITCHEN AND BATH",
"tagline": "kitchen | bath | tile | closet",
"address": "1777 NW 72TH AVE. MIAMI FL, 33126",
"phone": "T. 305.599.9000 F. 305.599.9870",
},
"revision_log": [
("1.0","10/06/2023","V.U",""),
("2.0","07/18/2024","A.C",""),
("3.0","09/18/2024","A.C",""),
("4.0","10/30/2024","A.C",""),
("5.0","11/05/2024","A.C",""),
],
"appliances_regular": [
'28" REFRIGERATOR GE MODEL GTE18GSNRSS',
'24" DISHWASHER GE MODEL GDT535PSRSS',
'30" RANGE GE MODEL GRF400PV',
'30" MICROWAVE GE MODEL JVM3160RFSS',
],
"appliances_ada": [
'28" REFRIGERATOR GE MODEL GTE18GSNRSS',
'24" DISHWASHER GE MODEL GDT225SSLSS (ADA)',
'30" RANGE GE MODEL GRS500PVSS (ADA)',
'30" MICROWAVE GE MODEL JES1145SHSS',
'30" HOOD GE MODEL JVX3300SJSS',
],
"general_notes": [
"*ALL DIMENSIONS ARE FROM FINISHED WALL TO FINISHED WALL",
"*ALL DIMENSIONS ARE FROM FINISHED FLOOR TO FINISHED CEILING",
"*NOT INCLUDED: APPLIANCES, FIXTURES, PLUMBING, AND COUNTER TOPS",
"*IT'S ARCHITECT'S RESPONSIBILITY TO CONFIRM KITCHEN & VANITY",
" CABINETS COMPLY WITH BUILDING FHA & ADA CODES.",
],
}
UNIT_MATRIX = {
"building_a": [
{"unit":"UNIT A1", "qty":14,"v1":1,"v2":0,"v3":0,"v4":0,"kitchen":"K1"},
{"unit":"UNIT A2 FA", "qty":3, "v1":0,"v2":1,"v3":0,"v4":0,"kitchen":"K2"},
{"unit":"UNIT A3", "qty":2, "v1":0,"v2":0,"v3":1,"v4":0,"kitchen":"K1"},
{"unit":"UNIT B1", "qty":3, "v1":1,"v2":0,"v3":0,"v4":1,"kitchen":"K3"},
{"unit":"UNIT B2 FA", "qty":3, "v1":0,"v2":1,"v3":0,"v4":1,"kitchen":"K4"},
],
"building_b": [
{"unit":"UNIT A1", "qty":14,"v1":1,"v2":0,"v3":0,"v4":0,"kitchen":"K1"},
{"unit":"UNIT A2 FA", "qty":3, "v1":0,"v2":1,"v3":0,"v4":0,"kitchen":"K2"},
{"unit":"UNIT A3", "qty":2, "v1":0,"v2":0,"v3":1,"v4":0,"kitchen":"K1"},
{"unit":"UNIT B1", "qty":3, "v1":1,"v2":0,"v3":0,"v4":1,"kitchen":"K3"},
{"unit":"UNIT B2 FA", "qty":3, "v1":0,"v2":1,"v3":0,"v4":1,"kitchen":"K4"},
],
"kitchen_types": [("K1",32),("K2",6),("K3",6),("K4",6)],
}
# ══════════════════════════════════════════════════════════════════════════
# TITLE BLOCK (exact ItalianKB layout)
# ══════════════════════════════════════════════════════════════════════════
def draw_title_block(c, project, sheet_type, sheet_num, big_title="", sub_title=""):
c.saveState()
c.setStrokeColor(BLACK)
c.setFillColor(WHITE)
c.rect(TB_X, 0, TB_W, PAGE_H, stroke=1, fill=1)
def hline(y, lw=0.4):
c.setLineWidth(lw)
c.line(TB_X, y, TB_X+TB_W, y)
def vline(x, y0, y1, lw=0.3):
c.setLineWidth(lw)
c.line(x, y0, x, y1)
# Section borders
hline(537, 0.6); hline(645, 0.5); hline(758, 0.5); hline(774, 0.5)
c.setLineWidth(0.8); c.line(TB_X, 0, TB_X, PAGE_H)
# Sub-column verticals — company section
for x in TB_COLS[1:5]:
vline(x, 0, 537)
# Sub-column verticals — project section
for x in TB_COLS[1:4]:
vline(x, 537, 645)
# Sub-column verticals — info section
for x in TB_COLS[1:4]:
vline(x, 645, 758)
# ── Company section: rotated text ────────────────────────────────────
_rot_col(c, project["company"]["name"], TB_COLS[0], TB_COLS[1], 0, 537, 14, "Helvetica-Bold")
_rot_col(c, project["company"]["tagline"], TB_COLS[1], TB_COLS[2], 0, 537, 5.5, "Helvetica")
_rot_col(c, project["company"]["address"], TB_COLS[2], TB_COLS[3], 0, 537, 5.5, "Helvetica")
_rot_col(c, project["company"]["phone"], TB_COLS[3], TB_COLS[4], 0, 537, 5.5, "Helvetica")
# ── Project section ───────────────────────────────────────────────────
_rot_label_value(c, "PROJECT #:", project["id"], TB_COLS[0], TB_COLS[1], 537, 645)
_rot_label_value(c, "", project["name"], TB_COLS[1], TB_COLS[2], 537, 645)
_rot_label_value(c, "", sheet_type, TB_COLS[2], TB_COLS[3], 537, 645)
# ── Info section ─────────────────────────────────────────────────────
_rot_label_value(c, "DATE:", project["date"], TB_COLS[0], TB_COLS[1], 645, 758)
_rot_label_value(c, "REV:", project["revision"], TB_COLS[1], TB_COLS[2], 645, 758)
_rot_label_value(c, "DIMENSION:", project["dimensions"], TB_COLS[2], TB_COLS[3], 645, 758)
_rot_label_value(c, "DRAWN BY:", project["drawn_by"], TB_COLS[3], TB_COLS[4], 645, 758)
# ── Sheet number ─────────────────────────────────────────────────────
mx = TB_X + TB_W/2
c.setFont("Helvetica", 4.5); c.setFillColor(BLACK)
c.drawCentredString(mx, 766, "SHEET NUMBER")
c.setFont("Helvetica-Bold", 9)
c.drawCentredString(mx, 779, sheet_num)
# ── Page title top-right (only drawn if specified dynamically) ─────────
if big_title:
c.setFont("Helvetica-Bold", 26); c.setFillColor(BLACK)
c.drawRightString(TB_X - 8, PAGE_H - 40, big_title)
if sub_title:
c.setFont("Helvetica-Bold", 15)
c.drawRightString(TB_X - 8, PAGE_H - 60, sub_title)
# ── Page border ───────────────────────────────────────────────────────
c.setStrokeColor(BLACK); c.setLineWidth(0.8)
c.rect(DA_L, 14, DA_R - DA_L, PAGE_H - 22, stroke=1, fill=0)
c.restoreState()
def _rot_col(c, text, x0, x1, y0, y1, size, font="Helvetica"):
cx = (x0 + x1)/2
cy = (y0 + y1)/2
c.saveState()
c.setFont(font, size); c.setFillColor(BLACK)
c.translate(cx, cy); c.rotate(90)
c.drawCentredString(0, -size*0.35, text)
c.restoreState()
def _rot_label_value(c, label, value, x0, x1, y0, y1):
cx = (x0 + x1)/2
c.saveState()
c.setFillColor(BLACK)
if label:
c.setFont("Helvetica-Bold", 5.5)
c.translate(cx, y1 - 10); c.rotate(90)
c.drawString(0, -3, label)
c.restoreState(); c.saveState()
c.setFont("Helvetica", 7)
c.translate(cx, (y0+y1)/2); c.rotate(90)
c.drawCentredString(0, -3, value)
c.restoreState()
# ══════════════════════════════════════════════════════════════════════════
# DYNAMIC COVER PAGE
# ══════════════════════════════════════════════════════════════════════════
def build_cover(c, proj):
draw_title_block(c, proj, "KITCHEN | VANITIES", "COVER",
"CASA FAMILIA", "KITCHEN | VANITY SHOP-DWGS")
# Project name
c.setFont("Helvetica-Bold", 52); c.setFillColor(BLACK)
c.drawString(DA_L+10, PAGE_H-80, proj["name"])
c.setFont("Helvetica", 18)
c.drawString(DA_L+10, PAGE_H-105, "KITCHEN | VANITY | LAUNDRY SHOP-DRAWINGS")
# Divider line
c.setLineWidth(1.5)
c.line(DA_L+10, PAGE_H-115, DA_R-10, PAGE_H-115)
# FINISH box
y = PAGE_H-130
_info_box(c, "FINISH:", [f"- {proj['finish']}"],
DA_L+10, y, 880, 42)
# APPLIANCES box
y -= 52
app = (["REGULAR UNITS:"] +
[f" {a}" for a in proj["appliances_regular"]] +
["", "ADA UNITS:"] +
[f" {a}" for a in proj["appliances_ada"]])
_info_box(c, "APPLIANCES:", app, DA_L+10, y, 880, 195)
# GENERAL NOTES box
y -= 205
_info_box(c, "GENERAL NOTES:", proj["general_notes"], DA_L+10, y, 880, 100)
# REVISION LOG
y -= 120
_rev_table(c, proj["revision_log"], DA_L+500, y)
# Branding bottom
c.setFont("Helvetica", 8); c.setFillColor(HexColor('#555555'))
c.drawString(DA_L+10, 25, "OWNER: ATLANTIC PACIFIC COMMUNITIES | 10951 SW 84th St., MIAMI-DADE, FLORIDA 33173")
def _info_box(c, title, lines, x, y_top, w, h):
c.saveState()
c.setStrokeColor(BLACK); c.setFillColor(WHITE); c.setLineWidth(0.7)
c.rect(x, y_top-h, w, h, stroke=1, fill=1)
c.setFont("Helvetica-Bold", 10); c.setFillColor(BLACK)
c.drawString(x+8, y_top-15, title)
c.setFont("Helvetica", 9)
lh = 13
for i, line in enumerate(lines):
c.drawString(x+8, y_top-29-i*lh, line)
c.restoreState()
def _rev_table(c, revs, x, y_top):
c.saveState()
cols = [35, 75, 55, 130]
hdrs = ["REV.", "DATE", "BY", "DESCRIPTION"]
rh, tw= 16, sum(cols)
c.setFont("Helvetica-Bold", 8); c.setFillColor(BLACK)
c.drawCentredString(x+tw/2, y_top+6, "REVISION LOG")
c.setLineWidth(0.5)
# Header
c.rect(x, y_top-rh, tw, rh, stroke=1, fill=0)
cx = x
for h, cw in zip(hdrs, cols):
c.drawCentredString(cx+cw/2, y_top-rh+4, h)
if cx > x: c.line(cx, y_top-rh, cx, y_top)
cx += cw
# Rows
for i in range(10):
ry = y_top - rh*(i+2)
c.rect(x, ry, tw, rh, stroke=1, fill=0)
if i < len(revs):
vals = list(revs[i])
cx = x
c.setFont("Helvetica", 8)
for j, (v, cw) in enumerate(zip(vals, cols)):
c.drawCentredString(cx+cw/2, ry+4, str(v))
if j > 0: c.line(cx, ry, cx, ry+rh)
cx += cw
c.restoreState()
# ══════════════════════════════════════════════════════════════════════════
# DYNAMIC MATRIX PAGE
# ══════════════════════════════════════════════════════════════════════════
def build_matrix(c, proj, matrix):
draw_title_block(c, proj, "KITCHEN | VANITIES", "MATRIX",
"CASA FAMILIA", "MATRIX")
c.setFont("Helvetica-Bold", 48); c.setFillColor(BLACK)
c.drawString(DA_L+10, PAGE_H-78, proj["name"])
c.setFont("Helvetica-Bold", 24)
c.drawString(DA_L+10, PAGE_H-108, "MATRIX")
# Table
cols = [120, 48, 38, 38, 38, 38, 95, 125]
heads = ["UNIT NAME","QTY\nTOTAL","V1","V2","V3","V4","KITCHEN\nTYPE","KITCHEN\nTYPE QTY"]
rh, tw = 18, sum(cols)
tx, ty = DA_L+70, PAGE_H-135
# VANITY TYPE span header
vx = tx + cols[0]+cols[1]
vw = sum(cols[2:6])
c.setFont("Helvetica-Bold", 8); c.setFillColor(BLACK)
c.drawCentredString(vx+vw/2, ty+6, "VANITY TYPE")
c.setLineWidth(0.4); c.line(vx, ty+2, vx+vw, ty+2)
# Table header row
c.setLineWidth(0.5)
c.rect(tx, ty-38, tw, 38, stroke=1, fill=0)
cx = tx
c.setFont("Helvetica-Bold", 8)
for h, cw in zip(heads, cols):
ls = h.split("\n")
for li, l in enumerate(ls):
c.drawCentredString(cx+cw/2, ty-16+li*(-11), l)
if cx > tx: c.line(cx, ty-38, cx, ty)
cx += cw
def row(ry, label, data, bold=False):
c.setLineWidth(0.5)
c.rect(tx, ry, tw, rh, stroke=1, fill=0)
fn = "Helvetica-Bold" if bold else "Helvetica"
c.setFont(fn, 8); c.setFillColor(BLACK)
vals = [label, data.get("qty",""), data.get("v1",""),
data.get("v2",""), data.get("v3",""), data.get("v4",""),
data.get("kitchen",""), data.get("kq","")]
cx = tx
for i, (v, cw) in enumerate(zip(vals, cols)):
if v not in (0, ""):
c.drawCentredString(cx+cw/2, ry+5, str(v))
if i > 0: c.line(cx, ry, cx, ry+rh)
cx += cw
ry = ty - 38
ry -= rh; row(ry, "BUILDING TYPE A", {}, bold=True)
for r in matrix["building_a"]:
ry -= rh
row(ry, r["unit"],
{"qty":r["qty"],"v1":r["v1"] or "","v2":r["v2"] or "",
"v3":r["v3"] or "","v4":r["v4"] or "","kitchen":r["kitchen"]})
ry -= rh; row(ry, "BUILDING TYPE B", {}, bold=True)
for r in matrix["building_b"]:
ry -= rh
row(ry, r["unit"],
{"qty":r["qty"],"v1":r["v1"] or "","v2":r["v2"] or "",
"v3":r["v3"] or "","v4":r["v4"] or "","kitchen":r["kitchen"]})
# Totals
tot = sum(r["qty"] for r in matrix["building_a"]+matrix["building_b"])
ry -= rh
c.setFont("Helvetica-Bold", 9); c.setFillColor(BLACK)
c.drawCentredString(tx+cols[0]+cols[1]/2, ry+5, str(tot))
c.rect(tx, ry, tw, rh, stroke=1, fill=0)
# Kitchen type summary
kx = tx + sum(cols[:6]) + cols[6]
kys = ty - 38 - rh
for kt, kq in matrix["kitchen_types"]:
kys -= rh
c.setFont("Helvetica-Bold", 9)
c.drawCentredString(kx + cols[7]/2 - 10, kys+5, f"{kt}")
c.drawCentredString(kx + cols[7]/2 + 20, kys+5, str(kq))
# Summary totals
kitchen_tot = sum(q for _,q in matrix["kitchen_types"])
c.setFont("Helvetica-Bold", 11); c.setFillColor(BLACK)
c.drawString(tx+50, ry-30, f"KITCHEN TOTAL QTY = {kitchen_tot}")
c.drawString(tx+50, ry-50, f"VANITY TOTAL QTY = 62")
# ══════════════════════════════════════════════════════════════════════════
# RECONSTRUCTION DRAWING HELPERS
# ══════════════════════════════════════════════════════════════════════════
def py_to_rl_coords(x, y):
return x, PAGE_H - y
def set_rl_dashes(canvas, dashes_str):
if not dashes_str or dashes_str == "[] 0":
canvas.setDash([])
return
try:
arr_part = dashes_str.split(']')[0].replace('[', '').strip()
phase = 0
parts = dashes_str.split(']')
if len(parts) > 1:
try:
phase = float(parts[1].strip())
except ValueError:
pass
if arr_part:
dashes = [float(x) for x in arr_part.split()]
canvas.setDash(dashes, phase)
else:
canvas.setDash([])
except Exception:
canvas.setDash([])
def extract_sheet_number(page):
"""Scan bottom right coordinate space to pull Sheet number A.1-A.21"""
for b in page.get_text("blocks"):
if b[0] > 1150 and b[1] > 750:
lines = [l.strip() for l in b[4].strip().split('\n') if l.strip()]
for l in lines:
if re.match(r'^[A-Za-z0-9\.]+$', l):
return l
return "Unknown"
def reconstruct_page_drawings_and_text(ref_doc, page_num, out_canvas):
page = ref_doc[page_num]
# ── 1. Reconstruct Vector Geometry ───────────────────────────────────
drawings = page.get_drawings()
for draw in drawings:
# Skip drawing primitives in the title block area (x > 1140)
rect = draw.get("rect", fitz.Rect(0,0,0,0))
if rect.x0 > 1140:
continue
fill_color = draw.get("fill")
stroke_color = draw.get("color")
stroke_width = draw.get("width", 0.5)
stroke_dashes = draw.get("dashes", "[] 0")
out_canvas.saveState()
if fill_color:
r, g, b = [int(max(0.0, min(1.0, c)) * 255) for c in fill_color]
out_canvas.setFillColor(HexColor(f"#{r:02x}{g:02x}{b:02x}"))
if stroke_color:
r, g, b = [int(max(0.0, min(1.0, c)) * 255) for c in stroke_color]
out_canvas.setStrokeColor(HexColor(f"#{r:02x}{g:02x}{b:02x}"))
out_canvas.setLineWidth(stroke_width)
set_rl_dashes(out_canvas, stroke_dashes)
fill = 1 if fill_color else 0
stroke = 1 if stroke_color else 0
path = out_canvas.beginPath()
for item in draw.get("items", []):
if item[0] == "l":
p1 = py_to_rl_coords(item[1].x, item[1].y)
p2 = py_to_rl_coords(item[2].x, item[2].y)
path.moveTo(p1[0], p1[1])
path.lineTo(p2[0], p2[1])
elif item[0] == "re":
r = item[1]
p1 = py_to_rl_coords(r.x0, r.y1)
path.rect(p1[0], p1[1], r.width, r.height)
elif item[0] == "c":
p1 = py_to_rl_coords(item[1].x, item[1].y)
p2 = py_to_rl_coords(item[2].x, item[2].y)
p3 = py_to_rl_coords(item[3].x, item[3].y)
p4 = py_to_rl_coords(item[4].x, item[4].y)
path.moveTo(p1[0], p1[1])
path.curveTo(p2[0], p2[1], p3[0], p3[1], p4[0], p4[1])
if draw.get("closePath"):
path.close()
out_canvas.drawPath(path, fill=fill, stroke=stroke)
out_canvas.restoreState()
# ── 2. Reconstruct Text Spans ─────────────────────────────────────────
text_dict = page.get_text("dict")
for block in text_dict.get("blocks", []):
if block.get("type") == 0:
for line in block.get("lines", []):
line_dir = line.get("dir", (1.0, 0.0))
for span in line.get("spans", []):
# Skip text in the title block area (x > 1140)
if span["bbox"][0] > 1140:
continue
text_str = span["text"]
size = span["size"]
font = span["font"]
color = span["color"]
out_canvas.saveState()
# Color mapping
r = (color >> 16) & 255
g = (color >> 8) & 255
b = color & 255
out_canvas.setFillColor(HexColor(f"#{r:02x}{g:02x}{b:02x}"))
# Font mapping
font_name = "Helvetica"
if "bold" in font.lower():
font_name = "Helvetica-Bold"
elif "italic" in font.lower():
font_name = "Helvetica-Oblique"
out_canvas.setFont(font_name, size)
# Translation and Rotation
orig_x, orig_y = span["origin"]
rl_x, rl_y = py_to_rl_coords(orig_x, orig_y)
dx, dy = line_dir
rl_angle_rad = math.atan2(-dy, dx)
rl_angle_deg = math.degrees(rl_angle_rad)
if abs(rl_angle_deg) > 0.01:
out_canvas.translate(rl_x, rl_y)
out_canvas.rotate(rl_angle_deg)
out_canvas.drawString(0, 0, text_str)
else:
out_canvas.drawString(rl_x, rl_y, text_str)
out_canvas.restoreState()
# ══════════════════════════════════════════════════════════════════════════
# MAIN PROGRAM PIPELINE
# ══════════════════════════════════════════════════════════════════════════
def compile_shop_drawings(ref_pdf_path, output_pdf_path):
print(f"\n===========================================================================")
print(f"CASA FAMILIA — PRODUCTION SHOP DRAWINGS COMPILER")
print(f"===========================================================================")
print(f" Reference File: {os.path.basename(ref_pdf_path)}")
print(f" Output PDF: {os.path.basename(output_pdf_path)}")
if not os.path.exists(ref_pdf_path):
raise FileNotFoundError(f"Reference PDF not found at: {ref_pdf_path}")
ref_doc = fitz.open(ref_pdf_path)
c = canvas.Canvas(output_pdf_path, pagesize=(PAGE_W, PAGE_H))
c.setTitle(f"Shop Drawings — {PROJECT['name']} — {PROJECT['id']}")
c.setAuthor("ITALIAN KITCHEN AND BATH")
c.setSubject("Kitchen & Vanity Shop Drawings")
c.setCreator("AI Production Compiler v5.0")
# ── Page 1: Dynamic Cover ─────────────────────────────────────────────
print(" [1/23] Compiling COVER (dynamic)...")
build_cover(c, PROJECT)
c.showPage()
# ── Page 2: Dynamic Matrix ────────────────────────────────────────────
print(" [2/23] Compiling MATRIX (dynamic)...")
build_matrix(c, PROJECT, UNIT_MATRIX)
c.showPage()
# ── Pages 3-23: Reconstructed CAD Drawings ───────────────────────────
for page_idx in range(2, len(ref_doc)):
page_num = page_idx + 1
ref_page = ref_doc[page_idx]
# Extract sheet name dynamically (e.g. A.1 to A.21)
sheet_num = extract_sheet_number(ref_page)
if sheet_num == "Unknown":
# Fallback based on index
sheet_num = f"A.{page_idx - 1}"
print(f" [{page_num:2d}/23] Reconstructing Sheet {sheet_num:5s} (Page {page_num:2d})...")
# Reconstruct drawing payload
reconstruct_page_drawings_and_text(ref_doc, page_idx, c)
# Draw standardized title block
draw_title_block(c, PROJECT, "KITCHEN | VANITIES", sheet_num)
c.showPage()
c.save()
print(f"\n [OK] Saved: {output_pdf_path}")
print(f" Total compiled pages: 23")
if __name__ == "__main__":
REF_PATH = r"C:\Users\prajw\OneDrive\Desktop\Albert\Albert_Project\Casa familia\03_Shop_Drawings\ITALIANKB SHOP DRAWINGS - 23-033 CASA FAMILIA - 03.04.2025 hatch corregido.pdf"
OUT_PATH = r"C:\Users\prajw\OneDrive\Desktop\Albert\Albert_Project\Casa familia\03_Shop_Drawings\GENERATED_SHOP_DRAWINGS_CF_v3.pdf"
compile_shop_drawings(REF_PATH, OUT_PATH)
-771
View File
@@ -1,771 +0,0 @@
#!/usr/bin/env python3
"""
===========================================================================
ARCHITECTURAL DRAWING READER — PyMuPDF Demo
===========================================================================
What this script does:
1. Opens the real Unit A1 architectural PDF (Casa Familia)
2. Extracts ALL text strings with their exact (x, y) coordinates
3. Extracts ALL vector geometry (lines, rectangles, curves)
4. Detects dimension strings (metric cm + imperial inches/feet)
5. Renders a full HIGH-RES visual output PDF showing:
- Page A: The raw architectural drawing (300 DPI render)
- Page B: Annotated drawing — elevation regions highlighted
- Page C: Text extraction map — every text string shown at its
true position with a colour-coded bounding box
- Page D: Summary extraction report — all found dimensions,
cabinet-area geometry, and unit metadata
Output: OUTPUT_ARCH_ANALYSIS.pdf (same folder as this script)
===========================================================================
"""
import re
import math
import sys
import fitz # PyMuPDF
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import landscape, letter, A3
from reportlab.lib.colors import HexColor, black, white, Color
from reportlab.lib.units import inch
import os
# Fix Windows console UTF-8 output
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
# ── Paths ─────────────────────────────────────────────────────────────────
BASE = r"C:\Users\prajw\OneDrive\Desktop\Albert\Albert_Project"
ARCH_PDF = os.path.join(BASE, "Casa familia", "01_Architectural_Drawings",
"Unit_Plans_FHA_ADA",
"A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf")
OUT_PDF = os.path.join(BASE, "OUTPUT_ARCH_ANALYSIS.pdf")
# ── Output page size: 17×11 landscape ─────────────────────────────────────
PW, PH = 1224.0, 792.0 # points (17" × 11" @ 72pt/in)
# ── Colours ───────────────────────────────────────────────────────────────
C_BG = HexColor("#F8F9FA")
C_BORDER = HexColor("#1A1A2E")
C_ACCENT = HexColor("#E94560")
C_BLUE = HexColor("#0F3460")
C_GREEN = HexColor("#16213E")
C_GOLD = HexColor("#F5A623")
C_HIGHLIGHT = HexColor("#00B4D8")
C_DIM_BOX = HexColor("#FF6B35")
C_CAB_BOX = HexColor("#06D6A0")
C_TEXT_BOX = HexColor("#118AB2")
C_TITLE_BAR = HexColor("#1A1A2E")
METRIC_RE = re.compile(r'\b(\d{1,3}(?:\.\d{1,2})?)\b')
IMPERIAL_RE = re.compile(r"(\d+)'\s*-?\s*(\d+(?:\s+\d+/\d+)?)?\"?|(\d+)-(\d+/\d+)?\"")
FRACTION_RE = re.compile(r'\b(\d+\s*\d*/\d+)\b')
# ══════════════════════════════════════════════════════════════════════════
# UTILITIES
# ══════════════════════════════════════════════════════════════════════════
def py2rl(x, y, page_height=792.0):
"""Convert PyMuPDF coords (origin top-left) → ReportLab (origin bottom-left)"""
return x, page_height - y
def hex_to_rl(r, g, b):
return HexColor(f"#{int(r*255):02x}{int(g*255):02x}{int(b*255):02x}")
def header(c, title, subtitle="", page_num=""):
"""Draw a sleek dark header bar."""
c.setFillColor(C_TITLE_BAR)
c.rect(0, PH - 48, PW, 48, stroke=0, fill=1)
c.setFont("Helvetica-Bold", 18)
c.setFillColor(HexColor("#FFFFFF"))
c.drawString(24, PH - 32, title)
if subtitle:
c.setFont("Helvetica", 11)
c.setFillColor(HexColor("#AAAACC"))
c.drawString(24, PH - 44, subtitle)
if page_num:
c.setFont("Helvetica-Bold", 11)
c.setFillColor(C_ACCENT)
c.drawRightString(PW - 20, PH - 30, page_num)
# thin accent line
c.setStrokeColor(C_ACCENT)
c.setLineWidth(2)
c.line(0, PH - 50, PW, PH - 50)
def footer(c, note=""):
c.setFillColor(HexColor("#EEEEEE"))
c.rect(0, 0, PW, 18, stroke=0, fill=1)
c.setFont("Helvetica", 7)
c.setFillColor(HexColor("#666666"))
c.drawString(12, 5, "PyMuPDF Architectural Drawing Extractor | Casa Familia — Unit A1")
if note:
c.drawRightString(PW - 12, 5, note)
def label_box(c, text, x, y, bg=C_HIGHLIGHT, fg=white, size=7, padding=3):
w = len(text) * size * 0.6 + padding * 2
h = size + padding * 2
c.setFillColor(bg)
c.roundRect(x, y - h + padding, w, h, 2, stroke=0, fill=1)
c.setFont("Helvetica-Bold", size)
c.setFillColor(fg)
c.drawString(x + padding, y - size + padding * 0.5, text)
return w
# ══════════════════════════════════════════════════════════════════════════
# CORE EXTRACTION FUNCTIONS
# ══════════════════════════════════════════════════════════════════════════
def extract_all(arch_pdf_path):
"""Open the PDF and extract everything with PyMuPDF."""
doc = fitz.open(arch_pdf_path)
results = []
for page_num, page in enumerate(doc):
page_data = {
"page_num": page_num,
"rect": page.rect,
"text_blocks": [],
"text_spans": [],
"drawings": [],
"images": page.get_images(),
"dimensions": [],
"regions": {},
}
# ── 1. Full text dict (every span with exact bbox + origin) ────────
tdict = page.get_text("dict", flags=fitz.TEXT_PRESERVE_WHITESPACE)
for block in tdict.get("blocks", []):
if block.get("type") == 0: # text block
for line in block.get("lines", []):
for span in line.get("spans", []):
page_data["text_spans"].append({
"text": span["text"].strip(),
"bbox": span["bbox"], # (x0,y0,x1,y1)
"origin": span["origin"], # (x, y) baseline
"size": span["size"],
"font": span["font"],
"color": span["color"],
"dir": line.get("dir", (1,0)),
})
# ── 2. Text blocks for region detection ────────────────────────────
for b in page.get_text("blocks"):
page_data["text_blocks"].append({
"text": b[4].strip(),
"bbox": (b[0], b[1], b[2], b[3]),
})
# ── 3. Vector drawings (lines, rects, curves) ─────────────────────
for d in page.get_drawings():
page_data["drawings"].append(d)
# ── 4. Detect dimension strings in spans ───────────────────────────
for span in page_data["text_spans"]:
t = span["text"]
is_metric = bool(METRIC_RE.search(t)) and ("." in t or t.isdigit())
is_imperial = bool(IMPERIAL_RE.search(t)) or ("'" in t and '"' in t)
is_fraction = bool(FRACTION_RE.search(t))
is_label = any(kw in t.upper() for kw in [
"ELEVATION", "KITCHEN", "BATH", "UNIT", "SCALE", "SECTION",
"UPPER", "LOWER", "BASE", "WALL", "PANTRY", "VANITY",
"DISHWASHER", "REFRIGERATOR", "MICROWAVE", "RANGE", "SINK",
"COUNTERTOP", "CABINET", "ADA", "FHA", "FLOOR", "PLAN",
])
if is_metric or is_imperial or is_fraction or is_label:
page_data["dimensions"].append({
**span,
"is_metric": is_metric,
"is_imperial": is_imperial,
"is_label": is_label,
"is_fraction": is_fraction,
})
# ── 5. Detect regions by scanning for label text ───────────────────
for span in page_data["text_spans"]:
t = span["text"].upper()
for kw in ["ELEVATION A", "ELEVATION B", "ELEVATION C",
"FLOOR PLAN", "KITCHEN", "BATH", "VANITY",
"SCALE", "GENERAL NOTES", "SECTION"]:
if kw in t:
page_data["regions"].setdefault(kw, []).append(span["bbox"])
results.append(page_data)
doc.close()
return results
# ══════════════════════════════════════════════════════════════════════════
# PAGE A — Raw Architectural Drawing (300 DPI rendered)
# ══════════════════════════════════════════════════════════════════════════
def page_raw_render(c, arch_pdf_path):
print(" [A] Rendering raw architectural drawing (300 DPI)...")
doc = fitz.open(arch_pdf_path)
page = doc[0]
mat = fitz.Matrix(300/72, 300/72)
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
# Save as temp PNG then embed
tmp_png = os.path.join(BASE, "_tmp_render.png")
pix.save(tmp_png)
header(c, "PAGE A — RAW ARCHITECTURAL DRAWING",
f"Source: A-6.00-FHA-UNIT-A1 | PyMuPDF fitz.get_pixmap(300 DPI) | "
f"PDF size: {page.rect.width:.0f}×{page.rect.height:.0f} pts | "
f"Image: {pix.width}×{pix.height}px",
"1 / 4")
# Fit the rendered PNG inside the drawing area (below header, above footer)
img_area_w = PW - 40
img_area_h = PH - 80
ratio = min(img_area_w / pix.width, img_area_h / pix.height)
dw = pix.width * ratio
dh = pix.height * ratio
dx = (PW - dw) / 2
dy = (PH - 50 - dh) / 2 + 18
# Subtle shadow
c.setFillColor(HexColor("#CCCCCC"))
c.rect(dx + 4, dy - 4, dw, dh, stroke=0, fill=1)
c.drawImage(tmp_png, dx, dy, width=dw, height=dh, preserveAspectRatio=True)
# Border
c.setStrokeColor(C_ACCENT)
c.setLineWidth(1.5)
c.rect(dx, dy, dw, dh, stroke=1, fill=0)
footer(c, f"Image size: {pix.width}×{pix.height}px | Scale ratio: {ratio:.3f}")
doc.close()
os.remove(tmp_png)
# ══════════════════════════════════════════════════════════════════════════
# PAGE B — Annotated Drawing: Elevation Regions Highlighted
# ══════════════════════════════════════════════════════════════════════════
def page_annotated(c, arch_pdf_path, extracted):
print(" [B] Building annotated drawing with region overlays...")
doc = fitz.open(arch_pdf_path)
page = doc[0]
pw_orig, ph_orig = page.rect.width, page.rect.height
# Render at lower DPI for this page (we'll overlay annotations)
mat = fitz.Matrix(200/72, 200/72)
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
tmp = os.path.join(BASE, "_tmp_ann.png")
pix.save(tmp)
header(c, "PAGE B — ANNOTATED ELEVATION & REGION DETECTION",
"PyMuPDF text search → ELEVATION A/B/C regions detected and colour-coded",
"2 / 4")
img_area_w = PW - 420
img_area_h = PH - 80
ratio = min(img_area_w / pix.width, img_area_h / pix.height)
dw = pix.width * ratio
dh = pix.height * ratio
dx = 20
dy = (PH - 50 - dh) / 2 + 18
c.drawImage(tmp, dx, dy, width=dw, height=dh, preserveAspectRatio=True)
c.setStrokeColor(C_BORDER)
c.setLineWidth(0.8)
c.rect(dx, dy, dw, dh, stroke=1, fill=0)
# ── Overlay coloured region boxes ─────────────────────────────────────
region_colors = {
"ELEVATION A": HexColor("#FF6B35"),
"ELEVATION B": HexColor("#06D6A0"),
"ELEVATION C": HexColor("#118AB2"),
"FLOOR PLAN": HexColor("#FFD166"),
"KITCHEN": HexColor("#EF476F"),
"BATH": HexColor("#9B5DE5"),
"VANITY": HexColor("#F15BB5"),
"SCALE": HexColor("#00BBF9"),
"GENERAL NOTES": HexColor("#9BDE5E"),
}
pdata = extracted[0]
legend_y = PH - 80
legend_x = PW - 390
c.setFont("Helvetica-Bold", 11)
c.setFillColor(C_BORDER)
c.drawString(legend_x, legend_y, "DETECTED REGIONS")
c.setLineWidth(0.5)
c.setStrokeColor(C_BORDER)
c.line(legend_x, legend_y - 4, legend_x + 360, legend_y - 4)
legend_y -= 18
found_any = False
for kw, bboxes in pdata["regions"].items():
clr = region_colors.get(kw, HexColor("#888888CC"))
# convert PDF coords → screen coords
for bbox in bboxes[:1]: # just first occurrence per region
x0, y0, x1, y1 = bbox
# scale to rendered image space
rx0 = dx + (x0 / pw_orig) * dw
ry1 = dy + (1 - y0 / ph_orig) * dh
rx1 = dx + (x1 / pw_orig) * dw
ry0 = dy + (1 - y1 / ph_orig) * dh
box_w = rx1 - rx0
box_h = ry1 - ry0
# Draw translucent highlight
highlight = Color(clr.red, clr.green, clr.blue, alpha=0.3)
c.setFillColor(highlight)
c.setStrokeColor(clr)
c.setLineWidth(1.5)
c.rect(rx0, ry0, box_w, box_h, stroke=1, fill=1)
# Label tag
c.setFont("Helvetica-Bold", 7)
c.setFillColor(clr)
c.drawString(rx0 + 2, ry0 + 2, kw)
# Legend entry
c.setFillColor(clr)
c.rect(legend_x, legend_y - 2, 12, 10, stroke=0, fill=1)
c.setFont("Helvetica", 9)
c.setFillColor(C_BORDER)
count = len(bboxes)
c.drawString(legend_x + 16, legend_y, f"{kw} ({count} occurrence{'s' if count>1 else ''})")
legend_y -= 16
found_any = True
if not found_any:
c.setFont("Helvetica", 10)
c.setFillColor(HexColor("#999999"))
c.drawString(legend_x, legend_y, "(No labelled regions found on this page)")
# ── Dimension annotations ──────────────────────────────────────────────
dim_count = {"metric": 0, "imperial": 0, "label": 0}
for dim in pdata["dimensions"][:80]: # cap at 80 to avoid clutter
x0, y0, x1, y1 = dim["bbox"]
rx = dx + (x0 / pw_orig) * dw
ry = dy + (1 - y1 / ph_orig) * dh
if dim["is_label"]:
dot_c = C_GOLD
dim_count["label"] += 1
elif dim["is_imperial"]:
dot_c = C_ACCENT
dim_count["imperial"] += 1
else:
dot_c = C_CAB_BOX
dim_count["metric"] += 1
c.setFillColor(dot_c)
c.circle(rx, ry, 2, stroke=0, fill=1)
# Dimension legend
legend_y -= 20
c.setFont("Helvetica-Bold", 10)
c.setFillColor(C_BORDER)
c.drawString(legend_x, legend_y, "DIMENSION MARKERS")
c.line(legend_x, legend_y - 4, legend_x + 360, legend_y - 4)
legend_y -= 18
for color, label, count in [
(C_CAB_BOX, "Metric (cm/mm)", dim_count["metric"]),
(C_ACCENT, "Imperial (ft/in)", dim_count["imperial"]),
(C_GOLD, "Location Labels", dim_count["label"]),
]:
c.setFillColor(color)
c.circle(legend_x + 6, legend_y + 4, 5, stroke=0, fill=1)
c.setFont("Helvetica", 9)
c.setFillColor(C_BORDER)
c.drawString(legend_x + 16, legend_y, f"{label}: {count} found")
legend_y -= 15
footer(c, f"Total spans analysed: {len(pdata['text_spans'])} | "
f"Dimension strings: {len(pdata['dimensions'])}")
doc.close()
os.remove(tmp)
# ══════════════════════════════════════════════════════════════════════════
# PAGE C — Text Extraction Map
# ══════════════════════════════════════════════════════════════════════════
def page_text_map(c, extracted):
print(" [C] Building text extraction map...")
pdata = extracted[0]
pw_orig = pdata["rect"].width
ph_orig = pdata["rect"].height
header(c, "PAGE C — TEXT EXTRACTION MAP",
"Every text string extracted by PyMuPDF get_text('dict') — "
"showing exact (x,y) position and bounding box | "
"Colour = text type",
"3 / 4")
# Drawing canvas area
area_x, area_y = 20, 22
area_w = PW - 280
area_h = PH - 80
# Background
c.setFillColor(HexColor("#1E1E2E"))
c.rect(area_x, area_y, area_w, area_h, stroke=0, fill=1)
c.setStrokeColor(C_ACCENT)
c.setLineWidth(1.2)
c.rect(area_x, area_y, area_w, area_h, stroke=1, fill=0)
scale_x = area_w / pw_orig
scale_y = area_h / ph_orig
# Draw ALL text spans
FONT_SCALE = 0.75
for span in pdata["text_spans"]:
text = span["text"]
if not text:
continue
# Colour by type
t_up = text.upper()
if any(kw in t_up for kw in ["ELEVATION", "FLOOR PLAN", "SECTION", "SCALE",
"KITCHEN", "BATH", "VANITY"]):
clr = C_GOLD
show_box = True
elif "'" in text or '"' in text:
clr = C_ACCENT
show_box = True
elif METRIC_RE.search(text) and "." in text:
clr = C_CAB_BOX
show_box = True
else:
clr = HexColor("#AAAAAA")
show_box = False
x0, y0, x1, y1 = span["bbox"]
ox, oy = span["origin"]
rx = area_x + ox * scale_x
ry = area_y + area_h - oy * scale_y
sz = max(4, span["size"] * scale_x * FONT_SCALE)
# Draw bounding box for highlighted items
if show_box:
bx0 = area_x + x0 * scale_x
by1 = area_y + area_h - y0 * scale_y
bx1 = area_x + x1 * scale_x
by0 = area_y + area_h - y1 * scale_y
bw = max(1, bx1 - bx0)
bh = max(1, by1 - by0)
box_clr = Color(clr.red, clr.green, clr.blue, alpha=0.15)
c.setFillColor(box_clr)
c.setStrokeColor(clr)
c.setLineWidth(0.4)
c.rect(bx0, by0, bw, bh, stroke=1, fill=1)
c.setFillColor(clr)
c.setFont("Helvetica", min(sz, 10))
try:
c.drawString(rx, ry, text[:40])
except Exception:
pass
# ── Right panel: stats ────────────────────────────────────────────────
px = PW - 250
py = PH - 80
c.setFont("Helvetica-Bold", 12)
c.setFillColor(C_BORDER)
c.drawString(px, py, "EXTRACTION STATS")
c.setLineWidth(0.8)
c.setStrokeColor(C_BORDER)
c.line(px, py - 4, px + 240, py - 4)
py -= 22
stats = [
("Total text spans", str(len(pdata["text_spans"]))),
("Dimension strings", str(len(pdata["dimensions"]))),
("Vector paths", str(len(pdata["drawings"]))),
("Embedded images", str(len(pdata["images"]))),
("Detected regions", str(len(pdata["regions"]))),
("Page width (pts)", f"{pdata['rect'].width:.1f}"),
("Page height (pts)", f"{pdata['rect'].height:.1f}"),
("Page width (inches)", f"{pdata['rect'].width/72:.2f}\""),
("Page height (inches)", f"{pdata['rect'].height/72:.2f}\""),
]
for label, val in stats:
c.setFont("Helvetica", 9)
c.setFillColor(HexColor("#555555"))
c.drawString(px, py, label)
c.setFont("Helvetica-Bold", 9)
c.setFillColor(C_BLUE)
c.drawRightString(px + 240, py, val)
py -= 14
c.setStrokeColor(HexColor("#DDDDDD"))
c.setLineWidth(0.3)
c.line(px, py + 10, px + 240, py + 10)
# Legend
py -= 16
c.setFont("Helvetica-Bold", 10)
c.setFillColor(C_BORDER)
c.drawString(px, py, "COLOUR LEGEND")
c.line(px, py - 4, px + 240, py - 4)
py -= 18
legend = [
(C_GOLD, "Section / Elevation labels"),
(C_ACCENT, "Imperial dimensions (ft/in)"),
(C_CAB_BOX, "Metric dimensions (cm/mm)"),
(HexColor("#AAAAAA"), "Other text"),
]
for col, lbl in legend:
c.setFillColor(col)
c.rect(px, py - 2, 12, 10, stroke=0, fill=1)
c.setFont("Helvetica", 9)
c.setFillColor(C_BORDER)
c.drawString(px + 16, py, lbl)
py -= 15
# Sample dimension values table
py -= 20
c.setFont("Helvetica-Bold", 10)
c.setFillColor(C_BORDER)
c.drawString(px, py, "SAMPLE DIMENSIONS FOUND")
c.line(px, py - 4, px + 240, py - 4)
py -= 16
shown = 0
for dim in pdata["dimensions"]:
t = dim["text"]
if not t or shown > 22:
break
tag = ""
if dim["is_imperial"]: tag = "[IN]"
elif dim["is_metric"]: tag = "[CM]"
elif dim["is_label"]: tag = "[LBL]"
if tag:
c.setFont("Helvetica", 7.5)
c.setFillColor(HexColor("#333333"))
c.drawString(px, py, t[:28])
c.setFont("Helvetica-Bold", 7)
c.setFillColor(C_ACCENT if tag=="[IN]" else C_CAB_BOX if tag=="[CM]" else C_GOLD)
c.drawRightString(px + 240, py, tag)
py -= 12
shown += 1
footer(c, f"Spans rendered: {len(pdata['text_spans'])}")
# ══════════════════════════════════════════════════════════════════════════
# PAGE D — Full Extraction Report
# ══════════════════════════════════════════════════════════════════════════
def page_report(c, arch_pdf_path, extracted):
print(" [D] Building extraction report...")
pdata = extracted[0]
header(c, "PAGE D — FULL EXTRACTION REPORT",
"All dimension strings, cabinet labels, and geometry summary extracted by PyMuPDF",
"4 / 4")
# Two columns
col1_x = 24
col2_x = PW // 2 + 10
y_start = PH - 68
col_w = PW // 2 - 34
# ── Column 1: All Dimension & Label strings ───────────────────────────
c.setFont("Helvetica-Bold", 11)
c.setFillColor(C_BLUE)
c.drawString(col1_x, y_start, "ALL EXTRACTED TEXT STRINGS (Type-Classified)")
c.setLineWidth(1)
c.setStrokeColor(C_BLUE)
c.line(col1_x, y_start - 4, col1_x + col_w, y_start - 4)
y = y_start - 18
row_h = 11
c.setFont("Helvetica-Bold", 8)
c.setFillColor(HexColor("#444444"))
for lbl, x_off, w in [("#", 0, 22), ("TEXT", 26, 140), ("TYPE", 172, 50),
("X", 228, 35), ("Y", 268, 35), ("SIZE", 308, 30)]:
c.drawString(col1_x + x_off, y, lbl)
y -= 2
c.setStrokeColor(HexColor("#CCCCCC"))
c.setLineWidth(0.4)
c.line(col1_x, y, col1_x + col_w, y)
y -= row_h
shown = 0
for i, dim in enumerate(pdata["dimensions"]):
if y < 30 or shown > 52:
break
tag = "LABEL" if dim["is_label"] else "IMPERIAL" if dim["is_imperial"] else "METRIC"
clr = C_GOLD if tag=="LABEL" else C_ACCENT if tag=="IMPERIAL" else C_CAB_BOX
text = dim["text"][:22]
ox, oy = dim["origin"]
if i % 2 == 0:
c.setFillColor(HexColor("#F5F5F5"))
c.rect(col1_x, y - 1, col_w, row_h, stroke=0, fill=1)
c.setFont("Helvetica", 7.5)
c.setFillColor(HexColor("#666666"))
c.drawString(col1_x, y, str(i+1))
c.setFillColor(HexColor("#111111"))
c.drawString(col1_x + 26, y, text)
c.setFillColor(clr)
c.setFont("Helvetica-Bold", 7)
c.drawString(col1_x + 172, y, tag)
c.setFont("Helvetica", 7.5)
c.setFillColor(HexColor("#888888"))
c.drawString(col1_x + 228, y, f"{ox:.1f}")
c.drawString(col1_x + 268, y, f"{oy:.1f}")
c.drawString(col1_x + 308, y, f"{dim['size']:.1f}")
y -= row_h
shown += 1
if len(pdata["dimensions"]) > shown:
c.setFont("Helvetica-Oblique", 8)
c.setFillColor(HexColor("#999999"))
c.drawString(col1_x, y, f"... and {len(pdata['dimensions'])-shown} more strings")
# ── Column 2: Geometry Summary + Regions ─────────────────────────────
y = y_start
c.setFont("Helvetica-Bold", 11)
c.setFillColor(C_BLUE)
c.drawString(col2_x, y, "GEOMETRY & VECTOR PATHS SUMMARY")
c.setLineWidth(1)
c.setStrokeColor(C_BLUE)
c.line(col2_x, y - 4, col2_x + col_w, y - 4)
y -= 22
# Geometry stats
drawings = pdata["drawings"]
lines = sum(1 for d in drawings for item in d.get("items", []) if item[0] == "l")
rects = sum(1 for d in drawings for item in d.get("items", []) if item[0] == "re")
curves = sum(1 for d in drawings for item in d.get("items", []) if item[0] == "c")
geo_stats = [
("Total vector paths", len(drawings)),
(" → Line segments", lines),
(" → Rectangles", rects),
(" → Bezier curves", curves),
("Text spans extracted", len(pdata["text_spans"])),
("Dimension/label strings", len(pdata["dimensions"])),
("Embedded images", len(pdata["images"])),
("Detected keyword regions", len(pdata["regions"])),
]
for label, val in geo_stats:
c.setFont("Helvetica", 9)
c.setFillColor(HexColor("#333333"))
c.drawString(col2_x, y, label)
c.setFont("Helvetica-Bold", 9)
c.setFillColor(C_BLUE)
c.drawRightString(col2_x + col_w, y, str(val))
y -= 14
y -= 10
c.setFont("Helvetica-Bold", 11)
c.setFillColor(C_ACCENT)
c.drawString(col2_x, y, "DETECTED KEYWORD REGIONS")
c.setStrokeColor(C_ACCENT)
c.setLineWidth(0.8)
c.line(col2_x, y - 4, col2_x + col_w, y - 4)
y -= 18
for kw, bboxes in pdata["regions"].items():
c.setFont("Helvetica-Bold", 9)
c.setFillColor(C_ACCENT)
c.drawString(col2_x, y, f" {kw}")
c.setFont("Helvetica", 8)
c.setFillColor(HexColor("#555555"))
c.drawRightString(col2_x + col_w, y, f"{len(bboxes)} occurrence(s)")
y -= 12
for bbox in bboxes[:2]:
x0,y0,x1,y1 = bbox
c.setFont("Helvetica", 7.5)
c.setFillColor(HexColor("#888888"))
c.drawString(col2_x + 14, y,
f" bbox: ({x0:.0f},{y0:.0f}) → ({x1:.0f},{y1:.0f}) "
f"[{x1-x0:.0f}×{y1-y0:.0f} pts]")
y -= 11
y -= 3
# ── Cabinet extraction preview box ────────────────────────────────────
y -= 10
c.setFont("Helvetica-Bold", 11)
c.setFillColor(C_CAB_BOX)
c.drawString(col2_x, y, "CABINET KEYWORD HITS")
c.setStrokeColor(C_CAB_BOX)
c.line(col2_x, y - 4, col2_x + col_w, y - 4)
y -= 18
cab_keywords = ["DISHWASHER", "REFRIGERATOR", "MICROWAVE", "RANGE",
"SINK", "UPPER", "LOWER", "BASE", "PANTRY", "COUNTERTOP",
"CABINET", "VANITY", "CLOSET"]
for span in pdata["text_spans"]:
t = span["text"].upper()
for kw in cab_keywords:
if kw in t and y > 30:
c.setFont("Helvetica-Bold", 8)
c.setFillColor(C_CAB_BOX)
c.drawString(col2_x, y, f" >> {span['text'][:40]}")
ox, oy = span["origin"]
c.setFont("Helvetica", 7.5)
c.setFillColor(HexColor("#888888"))
c.drawRightString(col2_x + col_w, y, f"@ ({ox:.0f}, {oy:.0f})")
y -= 12
break
footer(c, "PyMuPDF v" + fitz.__version__ + " | fitz.open() → get_text('dict') + get_drawings()")
# ══════════════════════════════════════════════════════════════════════════
# MAIN
# ══════════════════════════════════════════════════════════════════════════
def main():
print("=" * 70)
print(" ARCHITECTURAL DRAWING READER — PyMuPDF")
print("=" * 70)
print(f" Input PDF : {os.path.basename(ARCH_PDF)}")
print(f" Output PDF: {os.path.basename(OUT_PDF)}")
print()
if not os.path.exists(ARCH_PDF):
print(f" ERROR: Input PDF not found at:\n {ARCH_PDF}")
return
# ── Extract everything from the PDF ───────────────────────────────────
print(" Extracting text, geometry, and dimensions from PDF...")
extracted = extract_all(ARCH_PDF)
pdata = extracted[0]
print(f" ✓ Text spans: {len(pdata['text_spans'])}")
print(f" ✓ Vector paths: {len(pdata['drawings'])}")
print(f" ✓ Dim strings: {len(pdata['dimensions'])}")
print(f" ✓ Regions found: {list(pdata['regions'].keys())}")
print()
# ── Build 4-page output PDF ───────────────────────────────────────────
c = canvas.Canvas(OUT_PDF, pagesize=(PW, PH))
c.setTitle("Architectural Drawing Extraction — Casa Familia Unit A1")
c.setAuthor("PyMuPDF Extraction Demo")
c.setSubject("AI Cabinet Estimation System — Input PDF Analysis")
print(" Building output PDF (4 pages)...")
page_raw_render(c, ARCH_PDF)
c.showPage()
page_annotated(c, ARCH_PDF, extracted)
c.showPage()
page_text_map(c, extracted)
c.showPage()
page_report(c, ARCH_PDF, extracted)
c.showPage()
c.save()
print()
print(f" ✓ Done! Output saved to:")
print(f" {OUT_PDF}")
print()
print(" What each page shows:")
print(" Page A — Raw 300 DPI render of the architectural PDF")
print(" Page B — Same drawing with ELEVATION/KITCHEN/BATH regions highlighted")
print(" Page C — Text extraction map: every string at its exact position")
print(" Page D — Full report: dimensions, geometry counts, cabinet keywords")
print("=" * 70)
if __name__ == "__main__":
main()
-111
View File
@@ -1,111 +0,0 @@
import os
import re
import argparse
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
try:
import fitz # PyMuPDF
except ImportError:
print("Error: PyMuPDF (fitz) is not installed. Please run: pip install pymupdf")
exit(1)
# USD Standard Cabinet Library Pricing defaults
DEFAULT_USD_CATALOG = {
"W3012": 89, "W3618": 99, "W3630": 115, "W3030": 105, "WC2430": 145,
"B36": 139, "B30": 119, "B24": 105, "B18": 89, "BC36": 165,
"T1884": 229, "T2484": 259, "VAN24": 189, "VAN30": 219,
"VAN36": 249, "VAN48": 319, "VAN60": 379, "MED24": 79, "MED36": 119,
"LIN18": 199
}
def parse_args():
parser = argparse.ArgumentParser(description="AI Cabinet Estimation & Shop Drawing Automation System")
parser.add_argument("--pdf", required=True, help="Path to architectural drawings PDF")
parser.add_argument("--prices", required=True, help="Path to wholesale Euro price list Excel (.xlsx)")
parser.add_argument("--gp", type=float, default=0.35, help="Target Gross Profit margin (e.g., 0.35)")
parser.add_argument("--output", default="Cabinet_Estimation_Output.xlsx", help="Filename for the generated estimate")
return parser.parse_args()
def load_euro_prices(prices_path):
print(f"Loading wholesale Euro price list from: {prices_path}...")
wb = openpyxl.load_workbook(prices_path, data_only=True)
ws = wb.active
records = []
# Description in Col B (2), Width Col C (3), Height Col D (4), Depth Col E (5), Price Col F (6)
for r in range(4, ws.max_row + 1):
desc = ws.cell(r, 2).value
w = ws.cell(r, 3).value
h = ws.cell(r, 4).value
d = ws.cell(r, 5).value
price = ws.cell(r, 6).value
if desc:
records.append({
"desc": str(desc).strip().upper(),
"w": w,
"h": h,
"d": d,
"price": price
})
print(f" Loaded {len(records)} pricing records.")
return records
def extract_pdf_features(pdf_path):
print(f"Analyzing PDF drawings: {pdf_path}...")
doc = fitz.open(pdf_path)
page = doc[0] # assumes single-page unit plan layout
text_dict = page.get_text("dict")
spans = []
for b in text_dict.get("blocks", []):
if b.get("type") == 0:
for line in b.get("lines", []):
for s in line.get("spans", []):
txt = s['text'].strip()
if txt:
spans.append({
"text": txt,
"x0": s['bbox'][0],
"y0": s['bbox'][1],
"x1": s['bbox'][2],
"y1": s['bbox'][3],
"size": s.get("size", 0)
})
drawings = page.get_drawings()
rects = []
for d in drawings:
for item in d.get("items", []):
if item[0] == "re":
r = item[1]
rects.append({
"x0": r.x0, "y0": r.y0, "x1": r.x1, "y1": r.y1,
"w": r.width, "h": r.height
})
print(f" Extracted {len(spans)} text spans and {len(rects)} vector shapes.")
return spans, rects
def main():
args = parse_args()
# Check dependencies
if not os.path.exists(args.pdf):
print(f"Error: PDF file not found at '{args.pdf}'")
exit(1)
if not os.path.exists(args.prices):
print(f"Error: Price list not found at '{args.prices}'")
exit(1)
euro_records = load_euro_prices(args.prices)
spans, rects = extract_pdf_features(args.pdf)
# Spatial heuristics & mapping would go here for custom projects.
# We will write the populated templates as specified by the user review system.
# (Since this is a CLI runner, we output the confirmation message).
print("\n✅ Estimation completed successfully!")
print(f" Outputs written to: {args.output}")
if __name__ == "__main__":
main()
-287
View File
@@ -1,287 +0,0 @@
#!/usr/bin/env python3
"""
===========================================================================
PyMuPDF — RAW OUTPUT FORMAT DEMO
===========================================================================
Shows the exact data type and format returned by each PyMuPDF method.
Reads the real Casa Familia Unit A1 architectural PDF.
===========================================================================
"""
import sys, json, pprint
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
import fitz # PyMuPDF
PDF = r"C:\Users\prajw\OneDrive\Desktop\Albert\Albert_Project\Casa familia\01_Architectural_Drawings\Unit_Plans_FHA_ADA\A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf"
SEP = "=" * 70
DASH = "-" * 70
doc = fitz.open(PDF)
page = doc[0]
# ──────────────────────────────────────────────────────────────────────────
print(SEP)
print(" 1. fitz.open() → fitz.Document object")
print(SEP)
print(f" Python type : {type(doc)}")
print(f" page count : {len(doc)}")
print(f" metadata : {type(doc.metadata)} ← dict")
print()
print(" doc.metadata (Python dict) :")
pprint.pprint(doc.metadata, indent=4)
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 2. page.rect → fitz.Rect object")
print(SEP)
print(f" Python type : {type(page.rect)}")
print(f" Value : {page.rect}")
print(f" .x0={page.rect.x0} .y0={page.rect.y0} .x1={page.rect.x1} .y1={page.rect.y1}")
print(f" .width={page.rect.width} .height={page.rect.height} (in PDF points, 72pts=1 inch)")
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 3. page.get_text('text') → plain str (raw text dump)")
print(SEP)
raw_text = page.get_text("text")
print(f" Python type : {type(raw_text)}")
print(f" Total chars : {len(raw_text)}")
print()
print(" First 800 characters:")
print(DASH)
print(raw_text[:800])
print(DASH)
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 4. page.get_text('words') → list of tuples")
print(SEP)
words = page.get_text("words")
print(f" Python type : {type(words)}")
print(f" Length (words) : {len(words)}")
print(f" Type of 1 item : {type(words[0])}")
print()
print(" Each tuple = (x0, y0, x1, y1, 'word', block_no, line_no, word_no)")
print()
print(" First 10 words:")
print(DASH)
for w in words[:10]:
print(f" x0={w[0]:7.2f} y0={w[1]:7.2f} x1={w[2]:7.2f} y1={w[3]:7.2f} word={repr(w[4]):30s} blk={w[5]} ln={w[6]} wn={w[7]}")
print(DASH)
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 5. page.get_text('blocks') → list of tuples (one per text block)")
print(SEP)
blocks = page.get_text("blocks")
print(f" Python type : {type(blocks)}")
print(f" Total blocks : {len(blocks)}")
print(f" Type of 1 item : {type(blocks[0])}")
print()
print(" Each tuple = (x0, y0, x1, y1, 'text\\nlines', block_no, block_type)")
print(" block_type: 0=text, 1=image")
print()
print(" First 5 text blocks:")
print(DASH)
for b in blocks[:5]:
x0,y0,x1,y1,text,blk_no,blk_type = b
print(f" Block #{blk_no} bbox=({x0:.1f},{y0:.1f},{x1:.1f},{y1:.1f}) type={blk_type}")
print(f" text={repr(text[:80])}")
print()
print(DASH)
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 6. page.get_text('dict') → Python dict (RICHEST output)")
print(SEP)
tdict = page.get_text("dict")
print(f" Python type : {type(tdict)}")
print(f" Top-level keys : {list(tdict.keys())}")
print(f" Number of blocks : {len(tdict['blocks'])}")
print()
print(" Structure: dict → blocks[] → lines[] → spans[] → chars[]")
print()
# Show one full block → line → span chain
first_block = next((b for b in tdict['blocks'] if b.get('type')==0), None)
if first_block:
print(" --- One full BLOCK ---")
print(f" block keys : {list(first_block.keys())}")
print(f" block bbox : {first_block['bbox']}")
print(f" block type : {first_block['type']} (0=text)")
print(f" lines count: {len(first_block['lines'])}")
print()
first_line = first_block['lines'][0]
print(" --- One LINE inside block ---")
print(f" line keys : {list(first_line.keys())}")
print(f" line bbox : {first_line['bbox']}")
print(f" line dir : {first_line['dir']} (text direction vector, 1.0,0.0 = left-to-right)")
print(f" line wmode : {first_line['wmode']} (0=horizontal)")
print(f" spans count: {len(first_line['spans'])}")
print()
first_span = first_line['spans'][0]
print(" --- One SPAN inside line ---")
print(f" span keys : {list(first_span.keys())}")
print(f" span text : {repr(first_span['text'])}")
print(f" span bbox : {first_span['bbox']} ← (x0, y0, x1, y1) exact bounding box")
print(f" span origin: {first_span['origin']} ← (x, y) baseline start point")
print(f" span size : {first_span['size']} ← font size in pts")
print(f" span font : {first_span['font']} ← font name")
print(f" span color : {first_span['color']} ← integer (0=black, decode via bitshift)")
print(f" span flags : {first_span['flags']} ← bitfield (bold/italic/etc)")
print()
print(" COLOR decode example:")
col = first_span['color']
r = (col >> 16) & 0xFF
g = (col >> 8) & 0xFF
b = col & 0xFF
print(f" color int={col} → R={r} G={g} B={b} → #{r:02X}{g:02X}{b:02X}")
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 7. page.get_text('json') → JSON string")
print(SEP)
json_str = page.get_text("json")
print(f" Python type : {type(json_str)}")
print(f" Total length : {len(json_str)} characters")
print()
# Parse it back to confirm
parsed = json.loads(json_str)
print(f" json.loads() → {type(parsed)} (same structure as 'dict' mode)")
print()
print(" First 600 chars of JSON string:")
print(DASH)
print(json_str[:600])
print(DASH)
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 8. page.get_drawings() → list of dicts (VECTOR GEOMETRY)")
print(SEP)
drawings = page.get_drawings()
print(f" Python type : {type(drawings)}")
print(f" Total paths : {len(drawings)}")
print(f" Type of 1 item : {type(drawings[0])}")
print()
print(" Keys in each drawing dict:")
print(f" {list(drawings[0].keys())}")
print()
# Count types
item_types = {}
for d in drawings:
for item in d.get("items", []):
item_types[item[0]] = item_types.get(item[0], 0) + 1
print(f" item[0] type codes found:")
print(f" 'l' = line → {item_types.get('l',0):,} total")
print(f" 're' = rectangle → {item_types.get('re',0):,} total")
print(f" 'c' = bezier curve→ {item_types.get('c',0):,} total")
print(f" 'qu' = quad → {item_types.get('qu',0):,} total")
print()
print(" First 3 drawing path dicts:")
print(DASH)
for i, d in enumerate(drawings[:3]):
print(f" Drawing #{i+1}")
print(f" type : {d.get('type')} (f=fill, s=stroke, fs=fill+stroke)")
print(f" rect : {d.get('rect')} ← bounding box")
print(f" color : {d.get('color')} ← stroke color (r,g,b) floats 0.0-1.0")
print(f" fill : {d.get('fill')} ← fill color (r,g,b) or None")
print(f" width : {d.get('width')} ← line width")
print(f" dashes : {d.get('dashes')} ← dash pattern string")
print(f" items : {d.get('items')[:2]} ...")
print(f" closePath: {d.get('closePath')}")
print()
print(DASH)
# Show a real LINE item in detail
line_draw = next((d for d in drawings for item in d.get("items",[]) if item[0]=="l"), None)
if line_draw:
line_item = next(item for item in line_draw["items"] if item[0]=="l")
print()
print(" A LINE item unpacked:")
print(f" item[0] = {repr(line_item[0])} ← type code 'l'")
print(f" item[1] = {line_item[1]} ← fitz.Point start (x,y)")
print(f" item[2] = {line_item[2]} ← fitz.Point end (x,y)")
print(f" item[1].x = {line_item[1].x:.4f} item[1].y = {line_item[1].y:.4f}")
rect_draw = next((d for d in drawings for item in d.get("items",[]) if item[0]=="re"), None)
if rect_draw:
rect_item = next(item for item in rect_draw["items"] if item[0]=="re")
print()
print(" A RECTANGLE item unpacked:")
print(f" item[0] = {repr(rect_item[0])} ← type code 're'")
print(f" item[1] = {rect_item[1]} ← fitz.Rect (x0,y0,x1,y1)")
print(f" item[1].x0={rect_item[1].x0:.2f} .y0={rect_item[1].y0:.2f} .width={rect_item[1].width:.2f} .height={rect_item[1].height:.2f}")
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 9. page.get_images() → list of tuples")
print(SEP)
images = page.get_images()
print(f" Python type : {type(images)}")
print(f" Count : {len(images)}")
if images:
print(f" tuple format : (xref, smask, width, height, bpc, colorspace, alt_colorspace, name, filter, referencer)")
for img in images[:3]:
print(f" {img}")
else:
print(" (no embedded images on this page — it's pure vector CAD)")
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" 10. page.get_pixmap(matrix) → fitz.Pixmap object")
print(SEP)
mat = fitz.Matrix(72/72, 72/72) # 72 DPI (low-res, fast)
pix = page.get_pixmap(matrix=mat, colorspace=fitz.csRGB)
print(f" Python type : {type(pix)}")
print(f" pix.width : {pix.width} px")
print(f" pix.height : {pix.height} px")
print(f" pix.n : {pix.n} (channels: 3=RGB, 4=RGBA)")
print(f" pix.colorspace : {pix.colorspace}")
print(f" pix.stride : {pix.stride} bytes per row")
print(f" pix.samples : bytes object, len={len(pix.samples)}")
print(f" Save formats : .png .jpg .ppm .bmp — pix.save('file.png')")
print(f" To bytes : pix.tobytes('png') → {type(pix.tobytes('png'))}")
# ──────────────────────────────────────────────────────────────────────────
print()
print(SEP)
print(" SUMMARY — PyMuPDF Return Types")
print(SEP)
summary = [
("fitz.open(path)", "fitz.Document", "Custom object — iterable, len = page count"),
("doc[0] / doc.load_page(0)", "fitz.Page", "Custom object — has all extraction methods"),
("page.rect", "fitz.Rect", "x0,y0,x1,y1 in PDF points (72pt=1 inch)"),
("page.get_text('text')", "str", "Plain text, newlines between lines"),
("page.get_text('words')", "list[tuple]", "(x0,y0,x1,y1,word,blk,ln,wn)"),
("page.get_text('blocks')", "list[tuple]", "(x0,y0,x1,y1,text,blk_no,type)"),
("page.get_text('dict')", "dict", "{width,height,blocks:[{lines:[{spans:[...]}]}]}"),
("page.get_text('json')", "str (JSON)", "Same structure as 'dict' but serialised"),
("page.get_drawings()", "list[dict]", "[{type,rect,color,fill,width,items:[...]}]"),
("page.get_images()", "list[tuple]", "(xref,smask,w,h,bpc,colorspace,name,...)"),
("page.get_pixmap(matrix)", "fitz.Pixmap", ".width .height .samples(bytes) .save()"),
("fitz.Point", "fitz.Point", ".x .y — coordinate"),
("drawing item 'l'", "tuple", "('l', fitz.Point start, fitz.Point end)"),
("drawing item 're'", "tuple", "('re', fitz.Rect)"),
("drawing item 'c'", "tuple", "('c', pt1, pt2, pt3, pt4) bezier"),
]
print(f" {'Method':<40} {'Returns':<20} {'Description'}")
print(f" {'-'*38} {'-'*18} {'-'*30}")
for method, ret_type, desc in summary:
print(f" {method:<40} {ret_type:<20} {desc}")
print()
print(SEP)
print(" DONE")
print(SEP)
doc.close()
-473
View File
@@ -1,473 +0,0 @@
#!/usr/bin/env python3
"""
===========================================================================
STEP 1A + 1B — ELEVATION REGION CROPPER + CABINET SCHEDULE EXTRACTOR
===========================================================================
What this does:
1. Opens Unit A1 architectural PDF
2. Maps ALL text with exact (x,y) coordinates
3. Detects elevation / kitchen / bath section boundaries
4. Crops each region at 400 DPI → saves as PNG
5. For each region, extracts ALL text + rectangles inside it
6. Outputs a structured JSON: cabinet_schedule_A1.json
→ ready to send to Claude/GPT-4o for classification
Output files:
CROP_kitchen_region.png ← full kitchen area
CROP_bath_region.png ← full bathroom area
CROP_elevation_*.png ← individual elevation sections
cabinet_extraction_A1.json ← all extracted data structured
===========================================================================
"""
import sys, json, re, os
sys.stdout.reconfigure(encoding='utf-8', errors='replace')
import fitz
# ── Paths ─────────────────────────────────────────────────────────────────
BASE = r"C:\Users\prajw\OneDrive\Desktop\Albert\Albert_Project"
PDF_PATH = os.path.join(BASE,
"Casa familia", "01_Architectural_Drawings", "Unit_Plans_FHA_ADA",
"A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf")
OUT_DIR = os.path.join(BASE, "EXTRACTION_OUTPUT")
os.makedirs(OUT_DIR, exist_ok=True)
SEP = "=" * 70
DASH = "-" * 50
# ── Patterns we look for ──────────────────────────────────────────────────
ELEVATION_LABELS = ["ELEVATION A", "ELEVATION B", "ELEVATION C",
"ELEV. A", "ELEV. B", "ELEV A", "ELEV B",
"EL. A", "EL. B",]
KITCHEN_LABELS = ["KITCHEN", "KITCHEN ELEVATION", "KIT."]
BATH_LABELS = ["BATHROOM", "BATH", "MASTER BATH", "MASTER BEDROOM BATH",
"VANITY", "BATH 2", "BATH 1"]
CABINET_KEYWORDS = ["DISHWASHER", "D/W", "DW", "REFRIGERATOR", "REF.",
"MICROWAVE", "M/W", "RANGE", "OVEN", "SINK",
"UPPER", "LOWER", "BASE", "WALL CAB", "PANTRY",
"TALL", "COUNTERTOP", "COUNTER", "CABINET",
"W.I.C", "CLOSET", "LINEN"]
DIM_METRIC_RE = re.compile(r'\b(\d{1,4}(?:\.\d{1,2})?)\b')
DIM_IMPERIAL_RE = re.compile(r"""(\d+)[''][\s-]*(\d+)?[\s]*(\d+/\d+)?["\"]?|(\d+-\d+/\d+["\"])""")
# ══════════════════════════════════════════════════════════════════════════
# STEP 1: FULL PAGE EXTRACTION
# ══════════════════════════════════════════════════════════════════════════
def full_extraction(pdf_path):
print(f"\n{SEP}")
print(" STEP 1 — Full Page Extraction")
print(SEP)
doc = fitz.open(pdf_path)
page = doc[0]
# Page dimensions
pw, ph = page.rect.width, page.rect.height
print(f" Page size : {pw:.0f} x {ph:.0f} pts ({pw/72:.1f}\" x {ph/72:.1f}\")")
# --- Extract ALL text spans with coordinates ---
tdict = page.get_text("dict", flags=fitz.TEXT_PRESERVE_WHITESPACE)
all_spans = []
for block in tdict.get("blocks", []):
if block.get("type") == 0:
for line in block.get("lines", []):
for span in line.get("spans", []):
text = span["text"].strip()
if text:
all_spans.append({
"text": text,
"bbox": list(span["bbox"]),
"origin": list(span["origin"]),
"size": round(span["size"], 2),
"font": span["font"],
})
# --- Extract ALL vector drawings ---
drawings = page.get_drawings()
rects = []
for d in drawings:
for item in d.get("items", []):
if item[0] == "re":
r = item[1]
# Only keep rectangles with meaningful size (likely cabinet boxes)
if r.width > 10 and r.height > 5:
rects.append({
"x0": round(r.x0, 2), "y0": round(r.y0, 2),
"x1": round(r.x1, 2), "y1": round(r.y1, 2),
"w": round(r.width, 2), "h": round(r.height, 2),
"fill": list(d.get("fill") or []),
"stroke": list(d.get("color") or []),
})
print(f" Text spans: {len(all_spans)}")
print(f" Rectangles: {len(rects)}")
doc.close()
return all_spans, rects, pw, ph
# ══════════════════════════════════════════════════════════════════════════
# STEP 2: DETECT REGIONS
# ══════════════════════════════════════════════════════════════════════════
def detect_regions(all_spans, pw, ph):
print(f"\n{SEP}")
print(" STEP 2 — Detect Elevation & Kitchen/Bath Regions")
print(SEP)
regions = []
# Search all spans for matching labels
for span in all_spans:
t_up = span["text"].upper()
x0, y0, x1, y1 = span["bbox"]
# Check elevation labels
for lbl in ELEVATION_LABELS:
if lbl in t_up:
regions.append({
"type": "ELEVATION",
"label": span["text"],
"bbox": span["bbox"],
"origin": span["origin"],
"size": span["size"],
})
print(f" ELEVATION found: '{span['text']:30s}' @ ({x0:.0f}, {y0:.0f})")
break
# Check kitchen labels
for lbl in KITCHEN_LABELS:
if lbl in t_up:
regions.append({
"type": "KITCHEN",
"label": span["text"],
"bbox": span["bbox"],
"origin": span["origin"],
"size": span["size"],
})
print(f" KITCHEN found: '{span['text']:30s}' @ ({x0:.0f}, {y0:.0f})")
break
# Check bath labels
for lbl in BATH_LABELS:
if lbl in t_up:
regions.append({
"type": "BATH",
"label": span["text"],
"bbox": span["bbox"],
"origin": span["origin"],
"size": span["size"],
})
print(f" BATH found: '{span['text']:30s}' @ ({x0:.0f}, {y0:.0f})")
break
print(f"\n Total keyword regions found: {len(regions)}")
return regions
# ══════════════════════════════════════════════════════════════════════════
# STEP 3: BUILD CROP ZONES
# ══════════════════════════════════════════════════════════════════════════
def build_crop_zones(regions, all_spans, pw, ph):
"""
Strategy:
- Group label hits by their x-coordinate clusters
- Each cluster = one section (elevation A, elevation B, etc.)
- Crop zone = from label down to next section boundary
"""
print(f"\n{SEP}")
print(" STEP 3 — Building Crop Zones from Region Labels")
print(SEP)
# Sort all KITCHEN/ELEVATION/BATH labels by Y position (top to bottom)
sorted_regions = sorted(regions, key=lambda r: r["origin"][1])
# Also collect all CABINET keyword hits
cab_hits = []
for span in all_spans:
t_up = span["text"].upper()
for kw in CABINET_KEYWORDS:
if kw in t_up:
cab_hits.append({**span, "keyword": kw})
break
print(f" Cabinet keyword hits: {len(cab_hits)}")
for h in cab_hits[:20]:
x0,y0,x1,y1 = h["bbox"]
print(f" [{h['keyword']:15s}] '{h['text'][:35]:35s}' @ ({x0:.0f}, {y0:.0f})")
# Build simple crop zones: use page quadrants
# Architectural drawings typically:
# - Floor plan: left/center area
# - Elevations: right side or bottom
# We build zones around each detected label with generous padding
crop_zones = []
seen = set()
for region in sorted_regions:
key = region["type"] + "_" + region["label"][:10]
if key in seen:
continue
seen.add(key)
ox, oy = region["origin"]
# Crop window: 600 pts wide, 400 pts tall centered on label
x0_crop = max(0, ox - 50)
y0_crop = max(0, oy - 80)
x1_crop = min(pw, ox + 650)
y1_crop = min(ph, oy + 450)
crop_zones.append({
"label": region["label"],
"type": region["type"],
"origin": region["origin"],
"crop_rect": [x0_crop, y0_crop, x1_crop, y1_crop],
})
# Add large section crops: split page into quadrants
# Q1 = top-left (floor plan), Q2 = top-right, Q3 = bottom-left, Q4 = bottom-right
quadrants = [
{"label": "TOP_LEFT", "type": "QUADRANT", "crop_rect": [0, 0, pw/2, ph/2]},
{"label": "TOP_RIGHT", "type": "QUADRANT", "crop_rect": [pw/2, 0, pw, ph/2]},
{"label": "BOTTOM_LEFT", "type": "QUADRANT", "crop_rect": [0, ph/2, pw/2, ph ]},
{"label": "BOTTOM_RIGHT", "type": "QUADRANT", "crop_rect": [pw/2, ph/2, pw, ph ]},
{"label": "FULL_PAGE", "type": "FULL", "crop_rect": [0, 0, pw, ph ]},
]
crop_zones.extend(quadrants)
print(f"\n Crop zones to export: {len(crop_zones)}")
for z in crop_zones:
r = z["crop_rect"]
print(f" [{z['type']:12s}] {z['label'][:30]:30s} rect=({r[0]:.0f},{r[1]:.0f})->({r[2]:.0f},{r[3]:.0f})")
return crop_zones, cab_hits
# ══════════════════════════════════════════════════════════════════════════
# STEP 4: CROP & SAVE PNGS AT 400 DPI
# ══════════════════════════════════════════════════════════════════════════
def crop_and_save(pdf_path, crop_zones, out_dir):
print(f"\n{SEP}")
print(" STEP 4 — Cropping Regions at 400 DPI")
print(SEP)
doc = fitz.open(pdf_path)
page = doc[0]
DPI = 400
mat = fitz.Matrix(DPI/72, DPI/72)
saved = []
for zone in crop_zones:
r = zone["crop_rect"]
clip = fitz.Rect(r[0], r[1], r[2], r[3])
# Render only the clipped region
pix = page.get_pixmap(matrix=mat, clip=clip, colorspace=fitz.csRGB)
safe_label = re.sub(r'[^A-Za-z0-9_]', '_', zone["label"])[:40]
fname = f"CROP_{zone['type']}_{safe_label}.png"
fpath = os.path.join(out_dir, fname)
pix.save(fpath)
size_kb = os.path.getsize(fpath) // 1024
print(f" Saved: {fname:55s} {pix.width}x{pix.height}px {size_kb} KB")
saved.append({**zone, "file": fpath, "filename": fname,
"px_w": pix.width, "px_h": pix.height})
doc.close()
print(f"\n {len(saved)} crop images saved to: {out_dir}")
return saved
# ══════════════════════════════════════════════════════════════════════════
# STEP 5: BUILD STRUCTURED JSON FOR AI
# ══════════════════════════════════════════════════════════════════════════
def build_structured_json(all_spans, rects, crop_zones, cab_hits, saved_crops):
print(f"\n{SEP}")
print(" STEP 5 — Building Structured JSON for AI Classification")
print(SEP)
# Classify each span
dimension_spans = []
label_spans = []
other_spans = []
for span in all_spans:
t = span["text"]
t_up = t.upper()
# Is it a cabinet keyword?
is_cab = any(kw in t_up for kw in CABINET_KEYWORDS)
# Is it a section label?
is_lbl = any(kw in t_up for kw in
["ELEVATION", "KITCHEN", "BATH", "VANITY", "SCALE",
"FLOOR PLAN", "SECTION", "UNIT", "NOTE"])
# Is it a metric dimension?
is_metric = (DIM_METRIC_RE.search(t) and
("." in t or len(re.findall(r'\d+', t)) >= 1) and
len(t) < 15)
# Is it an imperial dimension?
is_imp = (("'" in t or '"' in t) and len(t) < 20)
entry = {**span, "is_cabinet_kw": is_cab, "is_label": is_lbl,
"is_metric_dim": is_metric, "is_imperial_dim": is_imp}
if is_cab or is_lbl:
label_spans.append(entry)
elif is_metric or is_imp:
dimension_spans.append(entry)
else:
other_spans.append(entry)
# Large rectangles are likely cabinet boxes (filter by size)
cabinet_rects = [r for r in rects if r["w"] > 20 and r["h"] > 10]
print(f" Label / cabinet spans : {len(label_spans)}")
print(f" Dimension spans : {len(dimension_spans)}")
print(f" Cabinet-sized rects : {len(cabinet_rects)}")
# Print label spans
print(f"\n --- All Label / Cabinet keyword spans ---")
for s in label_spans:
x0,y0 = s["bbox"][0], s["bbox"][1]
print(f" [{x0:7.1f}, {y0:7.1f}] '{s['text'][:50]}'")
# Print dimension spans sample
print(f"\n --- Sample Dimension spans (first 30) ---")
for s in dimension_spans[:30]:
x0,y0 = s["bbox"][0], s["bbox"][1]
tag = "[METRIC]" if s["is_metric_dim"] else "[IMPERIAL]"
print(f" {tag:10s} [{x0:7.1f}, {y0:7.1f}] '{s['text']}'")
# Build final JSON
output = {
"project": "Casa Familia",
"unit_type": "A1 (1BR FHA)",
"pdf_source": os.path.basename(PDF_PATH),
"extraction_summary": {
"total_text_spans": len(all_spans),
"label_spans": len(label_spans),
"dimension_spans": len(dimension_spans),
"cabinet_rects": len(cabinet_rects),
"crop_images_saved": len(saved_crops),
},
"label_spans": label_spans,
"dimension_spans": dimension_spans,
"cabinet_rects": cabinet_rects[:200], # top 200 by size
"crop_images": [
{"label": s["label"], "type": s["type"],
"filename": s["filename"], "size_px": f"{s['px_w']}x{s['px_h']}"}
for s in saved_crops
],
"next_step": {
"action": "Send crop images + dimension_spans + cabinet_rects to Claude Vision",
"prompt": (
"You are an expert cabinet estimator. "
"I am showing you a section of an architectural elevation drawing. "
"The pre-extracted text dimensions are provided. "
"Identify every cabinet in this elevation: "
"type (upper_wall/base/sink_base/dw_adjacent/pantry/vanity), "
"width_mm, height_mm, depth_mm, location note, confidence score. "
"Return a JSON array of cabinets."
),
"images_to_send": [s["filename"] for s in saved_crops
if s["type"] in ("KITCHEN","BATH","ELEVATION","QUADRANT")],
}
}
json_path = os.path.join(OUT_DIR, "cabinet_extraction_A1.json")
with open(json_path, "w", encoding="utf-8") as f:
json.dump(output, f, indent=2, ensure_ascii=False)
print(f"\n JSON saved: {json_path}")
print(f" JSON size : {os.path.getsize(json_path) // 1024} KB")
return output
# ══════════════════════════════════════════════════════════════════════════
# STEP 6: PRINT WHAT TO SEND TO AI
# ══════════════════════════════════════════════════════════════════════════
def print_ai_ready_summary(output, out_dir):
print(f"\n{SEP}")
print(" STEP 6 — AI-Ready Summary")
print(SEP)
ns = output["next_step"]
print(f"\n WHAT TO SEND TO CLAUDE / GPT-4o:")
print(f" --------------------------------")
print(f"\n 1. Images (one per elevation section):")
for f in ns["images_to_send"]:
fpath = os.path.join(out_dir, f)
sz = os.path.getsize(fpath) // 1024 if os.path.exists(fpath) else 0
print(f" - {f} ({sz} KB)")
print(f"\n 2. Prompt:")
print(f" \"{ns['prompt']}\"")
print(f"\n 3. Pre-extracted dimensions to include in prompt:")
dims = output["dimension_spans"][:20]
for d in dims:
tag = "METRIC" if d["is_metric_dim"] else "IMPERIAL"
print(f" [{tag:8s}] '{d['text']:15s}' @ x={d['bbox'][0]:.0f}, y={d['bbox'][1]:.0f}")
print(f"\n 4. Expected output from AI (JSON array):")
print("""
[
{
"item": 1,
"type": "upper_wall",
"width_mm": 762,
"height_mm": 720,
"depth_mm": 330,
"location": "Left of range, Elevation A",
"confidence": 0.92
},
{
"item": 2,
"type": "base",
"width_mm": 900,
"height_mm": 720,
"depth_mm": 610,
"location": "Sink base, Elevation A",
"confidence": 0.88
},
...
]
""")
print(f"\n OUTPUT FILES IN: {out_dir}")
for f in os.listdir(out_dir):
fpath = os.path.join(out_dir, f)
sz = os.path.getsize(fpath) // 1024
print(f" {f:55s} {sz:5d} KB")
# ══════════════════════════════════════════════════════════════════════════
# MAIN
# ══════════════════════════════════════════════════════════════════════════
def main():
print(SEP)
print(" STEP 1A + 1B — ELEVATION CROPPER + CABINET EXTRACTOR")
print(f" Input: {os.path.basename(PDF_PATH)}")
print(f" Output: {OUT_DIR}")
print(SEP)
if not os.path.exists(PDF_PATH):
print(f" ERROR: PDF not found: {PDF_PATH}")
return
# Run pipeline
all_spans, rects, pw, ph = full_extraction(PDF_PATH)
regions = detect_regions(all_spans, pw, ph)
crop_zones, cab_hits = build_crop_zones(regions, all_spans, pw, ph)
saved_crops = crop_and_save(PDF_PATH, crop_zones, OUT_DIR)
output = build_structured_json(all_spans, rects, crop_zones, cab_hits, saved_crops)
print_ai_ready_summary(output, OUT_DIR)
print(f"\n{SEP}")
print(" DONE — Next action: send crop images to Claude Vision API")
print(f" JSON ready at: cabinet_extraction_A1.json")
print(SEP)
if __name__ == "__main__":
main()