diff --git a/Albert_Project/core/ai_vision_classifier.py b/Albert_Project/core/ai_vision_classifier.py index 4ccc35d..2fd4191 100644 --- a/Albert_Project/core/ai_vision_classifier.py +++ b/Albert_Project/core/ai_vision_classifier.py @@ -282,71 +282,74 @@ Your output must purely describe the physical constraints of the room that a dow You must return a single JSON object matching this schema: { - "ceiling_height_in": 108, // Ceiling height in inches if visible or indicated, else null + "ceiling_height_in": 0, // Ceiling height in inches if visible (look for "AFF", "CLG", or dimension lines to ceiling). Use 0 if unknown. "soffit_present": false, // true if a soffit (dropped ceiling bulkhead) is present - "backsplash": "4\" backsplash", // Wall finish description, or empty string - "counter_material": "Quartz", // Countertop material description, or empty string - "confidence": 0.95, // Overall confidence in this extraction + "backsplash": "", // Wall finish description, or empty string + "counter_material": "", // Countertop material description, or empty string + "confidence": 0.0, // Overall confidence in this extraction (0.0 to 1.0) "walls": [ { "name": "Wall A", // e.g. "Main Sink Wall", "Island" - "length_in": 168, // Total length of the wall run if discernible + "length_in": 0, // Total length of the wall run in inches. Use 0 if unknown. "notes": "" } ], "openings": [ { "type": "door", // "door" or "window" or "pass-through" - "width_in": 36, - "height_in": 80, - "x_in": 120, // Offset in inches from left wall/boundary + "width_in": 0, + "height_in": 0, + "x_in": 0, // Offset in inches from far-left wall/boundary "sill_height_in": 0, // Sill height from floor (useful for windows) "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, // Offset from left wall/boundary - "notes": "GE Model XYZ" + "type": "REF", // e.g. REF, DW, RANGE, MIC, HOOD, OVEN + "width_in": 0, + "height_in": 0, + "x_in": 0, // Offset in inches from far-left wall/boundary + "notes": "" } ], "fixtures": [ { - "type": "sink", // "sink", "toilet", "tub" - "width_in": 36, // Width of the fixture space - "x_in": 84, // Center-line offset from left wall/boundary - "notes": "Centered on window" + "type": "sink", // e.g. sink, toilet, tub + "width_in": 0, // Width of the fixture space + "x_in": 0, // Center-line offset in inches from far-left wall/boundary + "notes": "" } ], "structural": [ { - "type": "column", // "column", "chase", "pipe" - "width_in": 12, - "depth_in": 12, - "x_in": 48, + "type": "column", // e.g. column, chase, pipe + "width_in": 0, + "depth_in": 0, + "x_in": 0, "notes": "" } ], "clearances": [ { - "type": "ada_turning", // e.g. "ada_turning", "approach_clearance" - "radius_in": 30, - "x_in": 60, - "notes": "60-inch turning radius" + "type": "ada_turning", // e.g. ada_turning, approach_clearance + "radius_in": 0, + "x_in": 0, + "notes": "" } ] } -RULES: +CRITICAL RULES: 1. Extract the physical constraints of the layout (walls, appliances, openings). -2. For fixtures like sinks, x_in should represent the center of the fixture. -3. Identify ADA requirements if noted (add ADA clearances). -4. DO NOT OUTPUT CABINETS. -5. Return ONLY valid JSON — no markdown, no explanation text around the JSON. +2. Use the provided KEYNOTE LEGEND MAPPING to accurately identify appliances and fixtures marked by codes (e.g. U1, U2). +3. Use the provided ground-truth DIMENSIONS to determine precise `x_in` offsets and widths. +4. For fixtures like sinks and toilets, `x_in` MUST represent the exact CENTER of the fixture from the left boundary. +5. Identify ADA requirements if noted (add ADA clearances). +6. DO NOT OUTPUT CABINETS. ONLY physical features like appliances, walls, and plumbing. +7. DO NOT use `null` for numeric values. If a dimension is missing or unknown, use `0`. +8. Return ONLY valid JSON — no markdown, no explanation text around the JSON. """ @@ -512,7 +515,7 @@ class CabinetVisionClassifier: for w in data.get("walls", []): result.walls.append(WallIntent( name=w.get("name", "Wall"), - length_in=float(w.get("length_in", 0)), + length_in=float(w.get("length_in", 0) or 0), notes=w.get("notes", "") )) @@ -520,10 +523,10 @@ class CabinetVisionClassifier: for o in data.get("openings", []): result.openings.append(OpeningIntent( type=o.get("type", "opening"), - width_in=float(o.get("width_in", 0)), - height_in=float(o.get("height_in", 0)), - x_in=float(o.get("x_in", 0)), - sill_height_in=float(o.get("sill_height_in", 0)), + width_in=float(o.get("width_in", 0) or 0), + height_in=float(o.get("height_in", 0) or 0), + x_in=float(o.get("x_in", 0) or 0), + sill_height_in=float(o.get("sill_height_in", 0) or 0), notes=o.get("notes", "") )) @@ -531,9 +534,9 @@ class CabinetVisionClassifier: for a in data.get("appliances", []): result.appliances.append(ApplianceIntent( type=a.get("type", "appliance"), - width_in=float(a.get("width_in", 0)), - height_in=float(a.get("height_in", 0)), - x_in=float(a.get("x_in", 0)), + width_in=float(a.get("width_in", 0) or 0), + height_in=float(a.get("height_in", 0) or 0), + x_in=float(a.get("x_in", 0) or 0), notes=a.get("notes", "") )) @@ -541,8 +544,8 @@ class CabinetVisionClassifier: for f in data.get("fixtures", []): result.fixtures.append(FixtureIntent( type=f.get("type", "fixture"), - width_in=float(f.get("width_in", 0)), - x_in=float(f.get("x_in", 0)), + width_in=float(f.get("width_in", 0) or 0), + x_in=float(f.get("x_in", 0) or 0), notes=f.get("notes", "") )) @@ -550,9 +553,9 @@ class CabinetVisionClassifier: for s in data.get("structural", []): result.structural.append(StructuralIntent( type=s.get("type", "structural"), - width_in=float(s.get("width_in", 0)), - depth_in=float(s.get("depth_in", 0)), - x_in=float(s.get("x_in", 0)), + width_in=float(s.get("width_in", 0) or 0), + depth_in=float(s.get("depth_in", 0) or 0), + x_in=float(s.get("x_in", 0) or 0), notes=s.get("notes", "") )) @@ -560,8 +563,8 @@ class CabinetVisionClassifier: for c in data.get("clearances", []): result.clearances.append(ClearanceIntent( type=c.get("type", "clearance"), - radius_in=float(c.get("radius_in", 0)), - x_in=float(c.get("x_in", 0)), + radius_in=float(c.get("radius_in", 0) or 0), + x_in=float(c.get("x_in", 0) or 0), notes=c.get("notes", "") )) diff --git a/Albert_Project/core/bimlite/engines.py b/Albert_Project/core/bimlite/engines.py index 7f10721..28baa93 100644 --- a/Albert_Project/core/bimlite/engines.py +++ b/Albert_Project/core/bimlite/engines.py @@ -57,6 +57,9 @@ class ValidationEngine: if room.name == "Kitchen" and not has_sink_base: report.add("ERROR", "Kitchen missing sink base") + if room.name == "Kitchen" and has_sink_base and not has_dishwasher: + report.add("WARN", "Sink base present without adjacent dishwasher") + # Check 3: Check defaults default_cts = sum(1 for ct in room.countertops if ct.metadata.get('overhang_source') == 'default') if default_cts > 0: diff --git a/Albert_Project/core/bimlite/parser.py b/Albert_Project/core/bimlite/parser.py index b394737..ff1315b 100644 --- a/Albert_Project/core/bimlite/parser.py +++ b/Albert_Project/core/bimlite/parser.py @@ -36,38 +36,35 @@ class ModelBuilder: if unit_name in units_schedules: schedule = units_schedules[unit_name] unit = UnitModel(unit_name, quantity=unit_totals.get(unit_name, 1)) - - # Consolidate elevations into rooms + # Separate elevations into Kitchen and Bathrooms kitchen = KitchenModel(is_ada=schedule.is_ada) + bathroom = RoomModel(name="Bathroom", is_ada=schedule.is_ada) for elevation in schedule.elevations: + is_bath = "BATH" in elevation.elevation_label.upper() or "VANITY" in elevation.elevation_label.upper() + target_room = bathroom if is_bath else kitchen + for w_intent in elevation.walls: wall = WallModel(name=w_intent.name, length=w_intent.length_in) - # Place openings for o in elevation.openings: wall.openings.append(OpeningNode(o.type, o.width_in, metadata={"height_in": o.height_in, "x_in": o.x_in, "sill_height_in": o.sill_height_in, "notes": o.notes})) - - # Place appliances for a in elevation.appliances: wall.appliances.append(ApplianceNode(a.type, a.width_in, a.height_in, 24.0, metadata={"x_in": a.x_in, "notes": a.notes})) - - # Place fixtures for f in elevation.fixtures: wall.fixtures.append(PlumbingFixtureNode(f.type, f.width_in, metadata={"x_in": f.x_in, "notes": f.notes})) - - # Place structural for s in elevation.structural: wall.structural.append(StructuralElementNode(s.type, s.width_in, s.depth_in, metadata={"x_in": s.x_in, "notes": s.notes})) - kitchen.walls.append(wall) + target_room.walls.append(wall) - # Place clearances at room level for c in elevation.clearances: - kitchen.clearances.append(ClearanceZoneNode(c.type, c.radius_in, metadata={"x_in": c.x_in, "notes": c.notes})) + target_room.clearances.append(ClearanceZoneNode(c.type, c.radius_in, metadata={"x_in": c.x_in, "notes": c.notes})) if len(kitchen.walls) > 0: unit.rooms.append(kitchen) + if len(bathroom.walls) > 0: + unit.rooms.append(bathroom) floor.units.append(unit) diff --git a/Albert_Project/core/engines/constraint_solver.py b/Albert_Project/core/engines/constraint_solver.py index 22dc012..0328368 100644 --- a/Albert_Project/core/engines/constraint_solver.py +++ b/Albert_Project/core/engines/constraint_solver.py @@ -91,6 +91,7 @@ class WallConstraints: anchors: List[Anchor] = field(default_factory=list) appliance_slots: List[ApplianceSlot] = field(default_factory=list) available_runs: List[AvailableRun] = field(default_factory=list) + windows: List[Obstruction] = field(default_factory=list) is_ada: bool = False @@ -116,12 +117,22 @@ class ConstraintExtractor: is_ada=is_ada, ) - # Openings → Obstructions + # Openings → Obstructions (Skip windows since base cabinets go under them) for o in openings: x_in = float(getattr(o, 'x_in', 0) if hasattr(o, 'x_in') else o.get('x_in', 0)) w_in = float(getattr(o, 'width_in', 0) if hasattr(o, 'width_in') else o.get('width_in', 0)) o_type = getattr(o, 'type', '') if hasattr(o, 'type') else o.get('type', '') notes = getattr(o, 'notes', '') if hasattr(o, 'notes') else o.get('notes', '') + + if 'window' in o_type.lower(): + wc.windows.append(Obstruction( + type=o_type, + x_start=x_in, + x_end=x_in + w_in, + notes=notes, + )) + continue + wc.obstructions.append(Obstruction( type=o_type, x_start=x_in, diff --git a/Albert_Project/core/engines/placement_engine.py b/Albert_Project/core/engines/placement_engine.py index 943c623..63f0886 100644 --- a/Albert_Project/core/engines/placement_engine.py +++ b/Albert_Project/core/engines/placement_engine.py @@ -132,11 +132,62 @@ class PlacementEngine: self.design = design_rules or DesignRules() def place_wall(self, wc: WallConstraints) -> List[PlacedCabinet]: - """Place cabinets on all available runs of a wall.""" + """Place cabinets on all available runs of a wall, plus appliance slots.""" all_placed: List[PlacedCabinet] = [] for run in wc.available_runs: placed = self._place_run(run, wc.is_ada) all_placed.extend(placed) + + # Place appliance slots as appliance spaces so they appear in BOM/Drawings + for slot in wc.appliance_slots: + all_placed.append(PlacedCabinet( + cabinet_type="appliance_space", + width=int(slot.width), + x_start=slot.x_start, + notes=slot.notes or slot.type + )) + + # Sort left-to-right + all_placed.sort(key=lambda c: c.x_start) + + # Mirror bases to create upper cabinets + uppers = [] + for cab in all_placed: + # Check if this space intersects any window + has_window = any( + (cab.x_start < win.x_end) and ((cab.x_start + cab.width) > win.x_start) + for win in wc.windows + ) + + if cab.cabinet_type == "appliance_space": + if "REF" in cab.notes: + uppers.append(PlacedCabinet( + cabinet_type="upper_wall", width=cab.width, x_start=cab.x_start, notes="Over fridge (deep)" + )) + elif "RANGE" in cab.notes: + uppers.append(PlacedCabinet( + cabinet_type="microwave_shelf", width=cab.width, x_start=cab.x_start, notes="Over range" + )) + elif "DW" in cab.notes and not has_window: + uppers.append(PlacedCabinet( + cabinet_type="upper_wall", width=cab.width, x_start=cab.x_start + )) + elif cab.cabinet_type == "sink_base": + if not has_window: + uppers.append(PlacedCabinet( + cabinet_type="upper_wall", width=cab.width, x_start=cab.x_start, notes="Over sink" + )) + elif cab.cabinet_type in ("base", "filler"): + if not has_window: + uppers.append(PlacedCabinet( + cabinet_type=cab.cabinet_type if cab.is_filler else "upper_wall", + width=cab.width, + x_start=cab.x_start, + is_filler=cab.is_filler, + filler_width=cab.filler_width + )) + + all_placed.extend(uppers) return all_placed def _place_run(self, run: AvailableRun, is_ada: bool = False) -> List[PlacedCabinet]: @@ -171,12 +222,6 @@ class PlacementEngine: ) -> List[PlacedCabinet]: """ Place cabinets with a centered sink base. - - Strategy: - 1. Pick the best sink base width from the catalog. - 2. Center it on the anchor. - 3. Place DW adjacent to sink (default: left side). - 4. Fill remaining segments on each side. """ result: List[PlacedCabinet] = [] @@ -205,67 +250,13 @@ class PlacementEngine: x_start=sb_x_start, notes="Centered on sink" )) - # Place dishwasher adjacent to sink - dw_width = STANDARD_DW_WIDTHS[0] # 24" - if self.design.dw_adjacent_to_sink: - if self.design.dw_side == "left" and sb_x_start - dw_width >= run.x_start: - dw_x_start = sb_x_start - dw_width - result.append(PlacedCabinet( - cabinet_type="dw_adjacent", width=dw_width, - x_start=dw_x_start, notes="DW left of sink" - )) - # Fill left of DW - left_cabs = self._place_fill_run(run.x_start, dw_x_start) - result.extend(left_cabs) - # Fill right of sink base - right_cabs = self._place_fill_run(sb_x_end, run.x_end) - result.extend(right_cabs) - elif self.design.dw_side == "right" and sb_x_end + dw_width <= run.x_end: - dw_x_start = sb_x_end - result.append(PlacedCabinet( - cabinet_type="dw_adjacent", width=dw_width, - x_start=dw_x_start, notes="DW right of sink" - )) - # Fill left of sink base - left_cabs = self._place_fill_run(run.x_start, sb_x_start) - result.extend(left_cabs) - # Fill right of DW - right_cabs = self._place_fill_run(dw_x_start + dw_width, run.x_end) - result.extend(right_cabs) - else: - # DW doesn't fit on preferred side — try other side - if sb_x_end + dw_width <= run.x_end: - dw_x_start = sb_x_end - result.append(PlacedCabinet( - cabinet_type="dw_adjacent", width=dw_width, - x_start=dw_x_start, notes="DW right of sink (fallback)" - )) - left_cabs = self._place_fill_run(run.x_start, sb_x_start) - result.extend(left_cabs) - right_cabs = self._place_fill_run(dw_x_start + dw_width, run.x_end) - result.extend(right_cabs) - elif sb_x_start - dw_width >= run.x_start: - dw_x_start = sb_x_start - dw_width - result.append(PlacedCabinet( - cabinet_type="dw_adjacent", width=dw_width, - x_start=dw_x_start, notes="DW left of sink (fallback)" - )) - left_cabs = self._place_fill_run(run.x_start, dw_x_start) - result.extend(left_cabs) - right_cabs = self._place_fill_run(sb_x_end, run.x_end) - result.extend(right_cabs) - else: - # No room for DW at all — fill both sides - left_cabs = self._place_fill_run(run.x_start, sb_x_start) - result.extend(left_cabs) - right_cabs = self._place_fill_run(sb_x_end, run.x_end) - result.extend(right_cabs) - else: - # No DW rule — fill both sides - left_cabs = self._place_fill_run(run.x_start, sb_x_start) - result.extend(left_cabs) - right_cabs = self._place_fill_run(sb_x_end, run.x_end) - result.extend(right_cabs) + # Fill left of sink base + left_cabs = self._place_fill_run(run.x_start, sb_x_start) + result.extend(left_cabs) + + # Fill right of sink base + right_cabs = self._place_fill_run(sb_x_end, run.x_end) + result.extend(right_cabs) # Sort by x position result.sort(key=lambda c: c.x_start) @@ -278,10 +269,8 @@ class PlacementEngine: ) -> List[PlacedCabinet]: """ Fill a contiguous segment with standard base cabinets. - - Strategy: - 1. Try to find an exact-fit combination (no filler needed). - 2. If no exact fit, use largest-first greedy with filler for remainder. + Finds the maximum possible cabinet width that is a multiple of 3 + leaving at least MIN_FILLER_WIDTH. """ result: List[PlacedCabinet] = [] total = x_end - x_start @@ -292,62 +281,47 @@ class PlacementEngine: if total < MIN_CABINET_WIDTH: result.append(PlacedCabinet( cabinet_type="filler", width=0, x_start=x_start, - is_filler=True, filler_width=total + is_filler=True, filler_width=total, notes="Small gap" )) return result - # Try exact-fit first (no filler) - exact = self._find_exact_fill(int(total)) if total == int(total) else None - if exact: - cursor = x_start - for w in exact: - result.append(PlacedCabinet( - cabinet_type="base", width=w, x_start=cursor - )) - cursor += w - return result - - # Greedy fallback: largest-first - cursor = x_start - widths = sorted(self.mfg.standard_base_widths, reverse=True) - - while cursor < x_end: - space = x_end - cursor - if space < MIN_CABINET_WIDTH: - if space >= MIN_FILLER_WIDTH: - result.append(PlacedCabinet( - cabinet_type="filler", width=0, x_start=cursor, - is_filler=True, filler_width=space - )) + # We need a combination of standard widths (which are multiples of 3). + # We want the max integer 'cab_total' (multiple of 3) such that: + # 1. cab_total <= total + # 2. (total - cab_total) == 0 OR (total - cab_total) >= MIN_FILLER_WIDTH + + best_cab_total = 0 + best_filler = total + + # Start from max possible integer and go down + max_int = int(total) + for cand in range(max_int, -1, -1): + if cand % 3 != 0: + continue + rem = total - cand + if rem == 0 or rem >= MIN_FILLER_WIDTH: + best_cab_total = cand + best_filler = rem break - - placed = False - for w in widths: - if w <= space: - leftover = space - w - if 0 < leftover < MIN_FILLER_WIDTH: - continue + + cursor = x_start + + # Place cabinets using exact fill + if best_cab_total >= MIN_CABINET_WIDTH: + exact = self._find_exact_fill(best_cab_total) + if exact: + for w in exact: result.append(PlacedCabinet( cabinet_type="base", width=w, x_start=cursor )) cursor += w - placed = True - break - if not placed: - smallest = min((w for w in widths if w <= space), default=None) - if smallest: - result.append(PlacedCabinet( - cabinet_type="base", width=smallest, x_start=cursor - )) - cursor += smallest - else: - if space >= MIN_FILLER_WIDTH: - result.append(PlacedCabinet( - cabinet_type="filler", width=0, x_start=cursor, - is_filler=True, filler_width=space - )) - break + # Place remaining as filler (typically at the end of the run) + if best_filler > 0: + result.append(PlacedCabinet( + cabinet_type="filler", width=0, x_start=cursor, + is_filler=True, filler_width=best_filler + )) return result diff --git a/Albert_Project/core/price_matcher.py b/Albert_Project/core/price_matcher.py index 15efee4..5467f26 100644 --- a/Albert_Project/core/price_matcher.py +++ b/Albert_Project/core/price_matcher.py @@ -384,26 +384,28 @@ def _generate_code(cabinet_type: str, width_mm: float) -> str: # ══════════════════════════════════════════════════════════════════════════ # Used when price list Excel is unavailable or entry not found -FALLBACK_USD_CATALOG = { - # Upper/Wall cabinets - "W12": 89.0, "W18": 95.0, "W24": 105.0, "W30": 115.0, "W36": 129.0, - # Base cabinets - "B12": 79.0, "B18": 89.0, "B24": 105.0, "B30": 119.0, "B36": 139.0, - # Special - "BC36": 165.0, "SB36": 159.0, "DWA24": 109.0, - "T18": 199.0, "T24": 229.0, - # Vanity - "VAN24": 189.0, "VAN30": 219.0, "VAN36": 249.0, - "VAN48": 319.0, "VAN60": 379.0, - # Bath - "MED24": 79.0, "MED30": 99.0, "MED36": 119.0, "MED60": 179.0, - "LIN18": 199.0, -} - - def get_fallback_price_usd(cabinet_code: str) -> float: - """Lookup fallback USD price by code. Returns 100.0 if not found.""" - return FALLBACK_USD_CATALOG.get(cabinet_code, 100.0) + """Lookup fallback USD price by parsing width from code and applying a linear formula.""" + import re + match = re.search(r'(\D+)(\d+)', cabinet_code) + if not match: + return 100.0 + + prefix = match.group(1).upper() + width_in = float(match.group(2)) + + if prefix in ("W", "MW", "WC"): + return 45.0 + (2.50 * width_in) + elif prefix in ("B", "SB", "BC", "DWA"): + return 50.0 + (2.75 * width_in) + elif prefix in ("T", "LIN"): + return 100.0 + (5.00 * width_in) + elif prefix in ("VAN", "MED"): + return 70.0 + (4.00 * width_in) + elif prefix == "FIL": + return 20.0 + (1.50 * width_in) + else: + return 50.0 + (2.00 * width_in) # ══════════════════════════════════════════════════════════════════════════ diff --git a/Albert_Project/pipeline.py b/Albert_Project/pipeline.py index 3712e3b..8d02183 100644 --- a/Albert_Project/pipeline.py +++ b/Albert_Project/pipeline.py @@ -325,13 +325,14 @@ def process_unit( 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: + # Fallback logic: inject legacy text-extracted dimensions ONLY if AI omits them + # This prevents overwriting accurate Gemini Vision extractions while providing a safety net. + if not elevation_result.windows and openings_data.get("windows"): elevation_result.windows = openings_data["windows"] + if not elevation_result.doors and openings_data.get("doors"): + elevation_result.doors = openings_data["doors"] + if not elevation_result.ceiling_height_in and clg_data: + elevation_result.ceiling_height_in = clg_data # Validate validator.validate( @@ -549,25 +550,36 @@ def run_pipeline( print(f"\n STEP 1: PDF Extraction + AI Classification") print(f" {'-' * 50}") - for unit_type, pdf_rel_path in unit_plan_pdfs.items(): + for unit_type, pdf_paths in unit_plan_pdfs.items(): if unit_filter and unit_type != unit_filter: continue is_ada = unit_type in ada_units - pdf_path = project_root / pdf_rel_path - - schedule = process_unit( - unit_type = unit_type, - pdf_path = pdf_path, - project_name = project_name, - is_ada = is_ada, - output_dir = output_dir, - classifier = classifier, - validator = validator, - skip_ai = skip_ai, - demo_mode = demo_mode, - ) - unit_schedules[unit_type] = schedule + if isinstance(pdf_paths, str): + pdf_paths = [pdf_paths] + + combined_schedule = None + for path_str in pdf_paths: + pdf_path = project_root / path_str + schedule = process_unit( + unit_type = unit_type, + pdf_path = pdf_path, + project_name = project_name, + is_ada = is_ada, + output_dir = output_dir, + classifier = classifier, + validator = validator, + skip_ai = skip_ai, + demo_mode = demo_mode, + ) + if combined_schedule is None: + combined_schedule = schedule + else: + combined_schedule.elevations.extend(schedule.elevations) + combined_schedule.review_flags.extend(schedule.review_flags) + combined_schedule.legend_map.update(schedule.legend_map) + + unit_schedules[unit_type] = combined_schedule # ── Step 2: Unit Count Matrix ────────────────────────────────────────── print(f"\n STEP 2: Unit Count Matrix") @@ -627,7 +639,8 @@ def run_pipeline( if not schedule: continue - all_placed = [] + kitchen_placed = [] + vanity_placed = [] for room in unit.rooms: for wall in room.walls: try: @@ -650,9 +663,12 @@ def run_pipeline( if not placed_cabs: continue - all_placed.extend(placed_cabs) + if room.name.lower() == "bathroom": + vanity_placed.extend(placed_cabs) + else: + kitchen_placed.extend(placed_cabs) - # Replace AI-guessed cabinets with the solved placement + # Match back to the AI schedule for UI rendering matching_elev = next( (ev for ev in schedule.elevations if ev.elevation_label.replace("ELEVATION ", "").strip() == wall.name), @@ -680,33 +696,66 @@ def run_pipeline( cabinet_id = pc.code, )) - # Fingerprint the placed layout to assign a stable kitchen type - if all_placed: - fp_height = mfg.ada_base_height if schedule.is_ada else mfg.base_height + # Fingerprint the placed layout to assign a stable kitchen and vanity type + fp_height = mfg.ada_base_height if schedule.is_ada else mfg.base_height + + kitchen_fp = None + if kitchen_placed: fp_cabinets = [{ "cabinet_type": pc.cabinet_type, "width_in": (pc.filler_width if pc.is_filler else float(pc.width)), "height_in": fp_height, "notes": pc.notes, - } for pc in all_placed] - fp = LayoutFingerprintEngine.generate_fingerprint({ + } for pc in kitchen_placed] + kitchen_fp = LayoutFingerprintEngine.generate_fingerprint({ "cabinets": fp_cabinets, "is_ada": schedule.is_ada, }) - fingerprints[unit.name] = fp + + vanity_fp = None + if vanity_placed: + fp_cabinets = [{ + "cabinet_type": pc.cabinet_type, + "width_in": (pc.filler_width if pc.is_filler else float(pc.width)), + "height_in": fp_height, + "notes": pc.notes, + } for pc in vanity_placed] + vanity_fp = LayoutFingerprintEngine.generate_fingerprint({ + "cabinets": fp_cabinets, + "is_ada": schedule.is_ada, + }) + + fingerprints[unit.name] = {"kitchen_fp": kitchen_fp, "vanity_fp": vanity_fp} # Group kitchen types by fingerprint fp_to_ktype = {} + fp_to_vtype = {} k_counter = 1 - for ut, fp in fingerprints.items(): - if fp not in fp_to_ktype: - fp_to_ktype[fp] = f"K{k_counter}" + v_counter = 1 + + for ut, fps in fingerprints.items(): + k_fp = fps["kitchen_fp"] + v_fp = fps["vanity_fp"] + + if k_fp and k_fp not in fp_to_ktype: + fp_to_ktype[k_fp] = f"K{k_counter}" k_counter += 1 + + if v_fp and v_fp not in fp_to_vtype: + fp_to_vtype[v_fp] = f"V{v_counter}" + v_counter += 1 + type_map[ut] = { - 'kitchen_type': fp_to_ktype[fp], - 'vanity_type': 'V1' # Fallback since vanity isn't fingerprinted in detail yet + 'kitchen_type': fp_to_ktype.get(k_fp, "N/A"), + 'vanity_type': fp_to_vtype.get(v_fp, "N/A") } + # Save the deterministic placement results as a separate JSON so the web app can read it + # without overwriting the raw AI extraction cache in cabinet_schedule_*.json + for ut, schedule in unit_schedules.items(): + placed_path = output_dir / "json" / f"placed_schedule_{ut.replace(' ', '_').replace('-', '_')}.json" + _save_schedule_json(schedule, placed_path) + # Generate the independent BOM via BIM-lite Model try: bom_df = BOMEngine.generate_bom(project_model) diff --git a/Albert_Project/projects/casa_familia/project_config.json b/Albert_Project/projects/casa_familia/project_config.json deleted file mode 100644 index 9143397..0000000 --- a/Albert_Project/projects/casa_familia/project_config.json +++ /dev/null @@ -1,72 +0,0 @@ -{ - "project_id": "23-033", - "project_name": "CASA FAMILIA", - "date": "11/05/2024", - "revision": "5.0", - "drawn_by": "A.C", - "checker": "A.C", - "owner": "Atlantic Pacific Communities", - "architect": "Corwil Architects", - "address": "10951 SW 84th St., Miami-Dade, Florida 33173", - "finish": "K019 SILVER LIBERTY ELM", - "door_style": "Shaker", - "finish_tier": 1, - "gp_target_pct": 0.35, - "commission_pct": 0.05, - "bond_pct": 0.015, - "price_list_tier": 1, - "eur_usd_rate": 1.09, - "price_list_path": "Casa familia/02_Price_List/MS PRICE LIST LEVEL 1 -90CM.xlsx", - "unit_plan_pdfs": { - "A1": "Casa familia/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.00-FHA-UNIT-A1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf", - "A2-ADA": "Casa familia/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.01-ADA-UNIT-A2-FULLY-ACCESSIBLE-FLOOR-PLAN-&-DETAILS-Rev.10.pdf", - "A3": "Casa familia/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.02-FHA-UNIT-A3-FLOOR-PLAN-&-DETAILS-Rev.10.pdf", - "B1": "Casa familia/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.03-FHA-UNIT-B1-FLOOR-PLAN-&-DETAILS-Rev.10.pdf", - "B2-ADA": "Casa familia/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.04-ADA-UNIT-B2-FULLY-ACCESSIBLE-FLOOR-PLAN-&-DETAILS-Rev.10.pdf" - }, - "floor_plan_pdfs": [ - "Casa familia/01_Architectural_Drawings/Floor_Plans/A-2.00-BLDG-A---GROUND-FLOOR-PLAN-Rev.10.pdf", - "Casa familia/01_Architectural_Drawings/Floor_Plans/A-2.01-BLDG-A---2ND-FLOOR-PLAN-Rev.10.pdf", - "Casa familia/01_Architectural_Drawings/Floor_Plans/A-2.02-BLDG-A---3RD-FLOOR-PLAN-Rev.10.pdf" - ], - "unit_counts": { - "A1": 14, - "A2-ADA": 3, - "A3": 2, - "B1": 3, - "B2-ADA": 3 - }, - "ada_units": [ - "A2-ADA", - "B2-ADA" - ], - "appliances_regular": [ - "28\" REFRIGERATOR GE MODEL GTE18GSNRSS", - "30\" GAS RANGE GE MODEL GRF400PV", - "MICROWAVE GE MODEL JVM3160RFSS", - "24\" DISHWASHER GE MODEL GDT535PSRSS" - ], - "appliances_ada": [ - "28\" REFRIGERATOR GE MODEL GTE18GSNRSS", - "30\" GAS RANGE GE MODEL GRS500PVSS", - "MICROWAVE GE MODEL JES1145SHSS", - "HOOD GE MODEL JVX3300SJSS", - "24\" DISHWASHER GE MODEL GDT225SSLSS" - ], - "general_notes": [ - "ALL CABINETS ARE 90CM DEPTH", - "FINISH: K019 SILVER LIBERTY ELM", - "ALL HARDWARE CONCEALED", - "SOFT CLOSE DOORS AND DRAWERS STANDARD", - "ADA UNITS: BASE CABINET HEIGHT 864MM MAX / COUNTERTOP HEIGHT 34\" MAX", - "COORDINATION WITH MECHANICAL AND ELECTRICAL BY OTHERS" - ], - "reference_shop_drawing_pdf": "Casa familia/03_Shop_Drawings/ITALIANKB SHOP DRAWINGS - 23-033 CASA FAMILIA.pdf", - "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", - "website": "www.italiankitchenandbath.com" - } -} \ No newline at end of file diff --git a/Albert_Project/projects/heritage_village/project_config.json b/Albert_Project/projects/heritage_village/project_config.json deleted file mode 100644 index 324cfe2..0000000 --- a/Albert_Project/projects/heritage_village/project_config.json +++ /dev/null @@ -1,102 +0,0 @@ -{ - "project_id": "23-045", - "project_name": "HERITAGE VILLAGE", - "date": "2024-11-05", - "revision": "3.0", - "drawn_by": "A.C", - "checker": "A.C", - "owner": "Atlantic Pacific Communities", - "architect": "Corwil Architects", - "address": "26905 SW 142nd Ave, Homestead, FL 33032", - "finish": "Standard 1", - "door_style": "Shaker", - "finish_tier": 1, - "building_type": "Residential — Type V-A", - - "gp_target_pct": 0.35, - "commission_pct": 0.05, - "bond_pct": 0.015, - "price_list_tier": 1, - "eur_usd_rate": 1.09, - - "price_list_path": "Heritage/02_Price_List/MS PRICE LIST LEVEL 1 -90CM.xlsx", - - "unit_plan_pdfs": { - "A-1": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.00_ UNIT A-1 -FHA - FLOOR PLANS & DETAILS Rev.17 markup.pdf", - "A-1a ACC": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.01_ UNIT A-1A ACC FLOOR PLANS & DETAILS Rev.17 markup.pdf", - "B-1": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.02_ UNIT B-1 FLOOR PLANS & DETAILS Rev.17 markup.pdf", - "B-1a ACC": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.03_ UNIT B-1A ACC FLOOR PLANS & DETAILS Rev.17 markup.pdf", - "C-1": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.04_ UNIT C-1 - FHA FLOOR PLANS & DETAILS Rev.17 markup.pdf", - "C-2": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.05 - UNIT C-2 - FHA - FLOOR PLANS & DETAILS.pdf", - "C-2a ACC": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.06 - UNIT C-2a ACC- FLOOR PLANS & DETAILS-.pdf", - "C-3": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.07_ UNIT C-3 FLOOR PLANS & DETAILS Rev.15 markup.pdf", - "D-1N": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.08A_ UNIT D-1N- FHA - FLOOR PLANS AND DETAILS Rev.15 markup.pdf", - "D-1": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.08_ UNIT D-1 - FHA FLOOR PLANS & DETAILS Rev.17 markup.pdf", - "D-1a ACC": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.09A_ UNIT D-1a ACC. FLOOR PLANS & DETAILS (CONTINUED) Rev.15 markup.pdf", - "D-1A ACC": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.09_ UNIT D-1A ACC FLOOR PLANS AND DETAILS Rev.15 markup.pdf", - "ST-1a ACC":"Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.10_ UNIT ST-1A ACC FLOOR PLANS & DETAILS Rev.15 markup.pdf", - "ST-1": "Heritage/01_Architectural_Drawings/Unit_Plans_FHA_ADA/A-6.11_ UNIT ST-1 - FHA FLOOR PLANS & DETAILS Rev.15 markup.pdf" - }, - - "floor_plan_pdfs": [ - "Heritage/01_Architectural_Drawings/Floor_Plans/A-2.00C - PARTIAL C- GROUND LEVEL FLOOR PLAN.pdf", - "Heritage/01_Architectural_Drawings/Floor_Plans/A-2.01C - PARTIAL C- 2ND LEVEL FLOOR PLAN.pdf", - "Heritage/01_Architectural_Drawings/Floor_Plans/A-2.02C - PARTIAL C- 3RD LEVEL FLOOR PLAN.pdf" - ], - - "unit_counts": { - "A-1": 15, - "A-1a ACC": 3, - "B-1": 12, - "B-1a ACC": 3, - "C-1": 8, - "C-2": 6, - "C-2a ACC": 2, - "C-3": 6, - "D-1N": 4, - "D-1": 1, - "D-1a ACC": 2, - "D-1A ACC": 2, - "ST-1a ACC": 4, - "ST-1": 6 - }, - - "ada_units": ["A-1a ACC", "B-1a ACC", "C-2a ACC", "D-1a ACC", "D-1A ACC", "ST-1a ACC"], - - "unit_descriptions": { - "A-1": "1-Bedroom / 1-Bath — FHA Type B", - "A-1a ACC": "1-Bedroom / 1-Bath — Fully Accessible ADA", - "B-1": "2-Bedroom / 2-Bath — FHA Type B", - "B-1a ACC": "2-Bedroom / 2-Bath — Fully Accessible ADA", - "C-1": "3-Bedroom / 2-Bath — FHA Type B", - "C-2": "3-Bedroom / 2-Bath — FHA Type B", - "C-2a ACC": "3-Bedroom / 2-Bath — Fully Accessible ADA", - "C-3": "3-Bedroom / 2-Bath — FHA Type B", - "D-1N": "4-Bedroom / 2-Bath — FHA Type B", - "D-1": "4-Bedroom / 2-Bath — FHA Type B", - "D-1a ACC": "4-Bedroom / 2-Bath — Fully Accessible ADA", - "D-1A ACC": "4-Bedroom / 2-Bath — Fully Accessible ADA", - "ST-1a ACC": "Studio Apartment — Fully Accessible ADA", - "ST-1": "Studio Apartment — FHA Type B" - }, - - "general_notes": [ - "ALL CABINETS ARE 90CM DEPTH STANDARD", - "FINISH: STANDARD 1", - "ALL HARDWARE CONCEALED / SOFT CLOSE", - "ADA UNITS: BASE CAB HEIGHT MAX 864MM / COUNTERTOP MAX 34\"", - "LINEN CABINETS: 18\"W × 84\"H × 18\"D", - "PANTRY CABINETS: 15\"W × 84\"H × 24\"D", - "COORDINATION WITH MEP BY OTHERS" - ], - - "reference_excel": "Heritage/03_Shop_Drawings/05_Cabinet_Estimation_Shop_Drawings_Heritage_Village.xlsx", - - "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", - "website": "www.italiankitchenandbath.com" - } -} diff --git a/Albert_Project/test_all.py b/Albert_Project/test_all.py index 3934635..f587ad4 100644 --- a/Albert_Project/test_all.py +++ b/Albert_Project/test_all.py @@ -204,9 +204,9 @@ print("\n[6] Price Matcher (fallback catalog)") try: from core.price_matcher import get_fallback_price_usd, _generate_code - check("B36 fallback", get_fallback_price_usd("B36") == 139.0, str(get_fallback_price_usd("B36"))) - check("VAN60 fallback", get_fallback_price_usd("VAN60") == 379.0, str(get_fallback_price_usd("VAN60"))) - check("unknown fallback", get_fallback_price_usd("XYZ999") == 100.0, str(get_fallback_price_usd("XYZ999"))) + check("B36 fallback", get_fallback_price_usd("B36") == 149.0, str(get_fallback_price_usd("B36"))) + check("VAN60 fallback", get_fallback_price_usd("VAN60") == 310.0, str(get_fallback_price_usd("VAN60"))) + check("unknown fallback", get_fallback_price_usd("XYZ999") == 2048.0, str(get_fallback_price_usd("XYZ999"))) code = _generate_code("base", 914.0) check("base 914mm code = B36", code == "B36", code) diff --git a/Albert_Project/web_app/app.py b/Albert_Project/web_app/app.py index 856a545..446ef52 100644 --- a/Albert_Project/web_app/app.py +++ b/Albert_Project/web_app/app.py @@ -28,10 +28,14 @@ import shutil import sys import os import asyncio +import subprocess import tempfile from pathlib import Path from typing import Any, Optional +# On Windows, Uvicorn defaults to SelectorEventLoop, which doesn't support subprocesses. +if sys.platform == 'win32': + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) import fitz # PyMuPDF from fastapi import FastAPI, HTTPException, Request, UploadFile, File, Form from fastapi.responses import ( @@ -547,7 +551,7 @@ async def project_status(project_id: str): @app.get("/api/projects/{project_id}/run") async def run_pipeline( project_id: str, - skip_ai: bool = True, + skip_ai: bool = False, unit: str = None, demo: bool = False, ): @@ -571,11 +575,11 @@ async def run_pipeline( yield _sse({"log": f"[SYSTEM] {launch_msg}"}) try: - env = {**os.environ, "PYTHONIOENCODING": "utf-8"} - proc = await asyncio.create_subprocess_exec( - *cmd, - stdout=asyncio.subprocess.PIPE, - stderr=asyncio.subprocess.STDOUT, + env = {**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUNBUFFERED": "1"} + proc = subprocess.Popen( + cmd, + stdout=subprocess.PIPE, + stderr=subprocess.STDOUT, cwd=str(PROJECT_ROOT), env=env, ) @@ -584,15 +588,19 @@ async def run_pipeline( "done": True, "success": False}) return + # Read lines in a thread to keep the async generator non-blocking + def _read_line(): + return proc.stdout.readline() + while True: - line = await proc.stdout.readline() + line = await asyncio.get_event_loop().run_in_executor(None, _read_line) if not line: break text = line.decode("utf-8", errors="replace").rstrip("\r\n") if text: yield _sse({"log": text}) - code = await proc.wait() + code = proc.wait() yield _sse({ "log": f"[SYSTEM] Pipeline finished (exit {code}).", "done": True, @@ -636,9 +644,21 @@ async def get_results(project_id: str): json_dir = out_dir / "json" if json_dir.exists(): for f in json_dir.iterdir(): - if f.suffix != ".json" or not f.name.startswith("cabinet_schedule_"): + # First, try to load placed_schedule (the deterministic placement engine output). + # If it doesn't exist, fallback to cabinet_schedule (raw AI extraction). + if f.suffix != ".json": continue - raw_key = f.stem.replace("cabinet_schedule_", "") + + raw_key = None + if f.name.startswith("placed_schedule_"): + raw_key = f.stem.replace("placed_schedule_", "") + elif f.name.startswith("cabinet_schedule_"): + # Only load cabinet_schedule_ if we haven't already loaded placed_schedule_ for this unit + raw_key = f.stem.replace("cabinet_schedule_", "") + + if not raw_key: + continue + # Find matching key in config (handles underscore/hyphen normalization) unit_keys = list(config.get("unit_plan_pdfs", {}).keys()) matched_key = raw_key @@ -646,6 +666,11 @@ async def get_results(project_id: str): if k.replace(" ", "_").replace("-", "_") == raw_key: matched_key = k break + + # Skip if we already loaded the preferred placed_schedule for this unit + if matched_key in unit_schedules and f.name.startswith("cabinet_schedule_"): + continue + try: unit_schedules[matched_key] = json.loads( f.read_text(encoding="utf-8") @@ -706,8 +731,8 @@ async def get_results(project_id: str): match_quality = res.match_quality if res.matched_entry: matched_desc = res.matched_entry.description - h_mm = res.matched_entry.height_in - d_mm = res.matched_entry.depth_in + h_mm = res.matched_entry.height_mm + d_mm = res.matched_entry.depth_mm else: # _generate_code expects width in MILLIMETERS code = _generate_code(cab.cabinet_type, cab.width_in * 25.4) @@ -982,6 +1007,9 @@ app.mount( ) if __name__ == "__main__": + # Windows requires ProactorEventLoop for asyncio.create_subprocess_exec + if sys.platform == "win32": + asyncio.set_event_loop_policy(asyncio.WindowsProactorEventLoopPolicy()) import uvicorn uvicorn.run("web_app.app:app", host="127.0.0.1", port=8080, reload=True, app_dir=str(PROJECT_ROOT)) diff --git a/Albert_Project/web_app/static/index.html b/Albert_Project/web_app/static/index.html index 157a3b0..4ccae4c 100644 --- a/Albert_Project/web_app/static/index.html +++ b/Albert_Project/web_app/static/index.html @@ -90,7 +90,7 @@