feat: complete web application, wizard dashboard, and Windows CP1252 compatibility fixes

This commit is contained in:
prajwalabhang1
2026-06-19 17:00:20 +05:30
parent beeac663fa
commit 985a1f0b85
45 changed files with 3871 additions and 4477 deletions
+15 -10
View File
@@ -1,19 +1,24 @@
# Copy this file to .env and fill in your API keys
# Never commit .env to version control
# Copy this file to .env and fill in your local keys.
# Never commit .env to version control.
# ── AI Vision API Keys ───────────────────────────────────────────────────────
# PRIMARY: Gemini 2.5 Pro (FREE — 25 req/day)
# Get key at: https://aistudio.google.com → Get API Key → Create API Key
# AI vision provider
# Primary path: OpenRouter -> Google Gemini vision models.
# Get a key at: https://openrouter.ai/keys
OPENROUTER_API_KEY=sk-or-v1-...your-openrouter-key-here...
# Optional legacy/direct provider keys for experiments or older scripts.
GEMINI_API_KEY=AIza...your-gemini-key-here...
# OPTIONAL: Anthropic Claude (paid) — only if you prefer Claude
GROQ_API_KEY=gsk_...your-groq-key-here...
ANTHROPIC_API_KEY=sk-ant-...your-anthropic-key-here...
OPENAI_API_KEY=sk-...your-openai-key-here...
# ── Currency Conversion ─────────────────────────────────────────────────────
# EUR to USD exchange rate (update periodically)
# Demo mode lowers image resolution and prompt/output size for cheaper demos.
DEMO_MODE=false
# Currency conversion
EUR_USD_RATE=1.09
# ── Job Costing Defaults (can override per project in project_config.json) ──
# Job costing defaults. Individual projects can override these in project_config.json.
GP_TARGET_PCT=0.35
COMMISSION_PCT=0.05
BOND_PCT=0.015
+14 -10
View File
@@ -1,7 +1,9 @@
# ── Secrets ─────────────────────────────────────────────────────────────────
# Secrets
.env
.env.*
!.env.example
# ── Python ───────────────────────────────────────────────────────────────────
# Python
__pycache__/
*.py[cod]
*.pyo
@@ -15,28 +17,30 @@ build/
.mypy_cache/
*.so
# ── Virtual environments ──────────────────────────────────────────────────────
# Virtual environments
venv/
.venv/
env/
ENV/
# ── OS files ──────────────────────────────────────────────────────────────────
# OS files
.DS_Store
Thumbs.db
desktop.ini
# ── IDE ───────────────────────────────────────────────────────────────────────
# IDE
.vscode/
.idea/
*.swp
*.swo
# ── Outputs (generated — do NOT commit large output files) ────────────────────
# Comment these out if you WANT to commit generated outputs
# outputs/
# ── Temporary / scratch ───────────────────────────────────────────────────────
# Logs and scratch
*.log
outputs/*.log
*.tmp
*.bak
scratch/
# Generated outputs are currently tracked for demo artifacts.
# Uncomment this line if generated artifacts should be excluded in future.
# outputs/
+203 -78
View File
@@ -1,38 +1,61 @@
"""
===========================================================================
core/ai_vision_classifier.py — Groq Vision Cabinet Classifier
core/ai_vision_classifier.py — OpenRouter Vision Cabinet Classifier
===========================================================================
Uses Groq API (llama-3.2-90b-vision-preview) to classify cabinets from
architectural elevation drawings. Groq is free, extremely fast, and
llama-3.2-90b-vision is excellent at reading technical drawings.
Uses OpenRouter API (Google Gemini models only) to classify cabinets
from architectural elevation drawings.
PRIMARY MODEL: google/gemini-2.5-flash
- Best for technical/architectural drawings
- Excellent spatial reasoning and OCR on dimension annotations
- $1.5/1M input tokens — fast and affordable
- 1M token context window
FALLBACK MODEL: google/gemini-2.5-pro
- More powerful Gemini for complex/ambiguous drawings
- $2.5/1M input tokens
- Kicks in when Flash returns low-confidence or invalid JSON
Pipeline per elevation crop:
1. Receive: PNG image bytes (400 DPI crop) + pre-extracted dims + rects
2. Build: structured prompt with dimension context
3. Call: Groq API (llama-3.2-90b-vision-preview) with base64 image
3. Call: OpenRouter API (gemini-2.5-flash) with base64 image
4. Parse: JSON response → list[CabinetItem]
5. Retry with fix prompt if JSON parse fails
5. Retry with gemini-2.5-pro if JSON parse fails or confidence < 0.7
6. Exponential backoff on API errors
Free tier: very generous (no hard daily limit on llama-3.2-90b-vision)
Get key at: https://console.groq.com
===========================================================================
"""
Get key at: https://openrouter.ai
==========================================================================="""
from __future__ import annotations
import base64
import json
import re
import time
import urllib.request
from dataclasses import dataclass, field, asdict
from typing import Optional
from core.config import GROQ_API_KEY, AUTO_APPROVE_CONFIDENCE
import os
from core.config import AUTO_APPROVE_CONFIDENCE, OPENROUTER_API_KEY
GROQ_MODEL = "meta-llama/llama-4-scout-17b-16e-instruct"
GROQ_MAX_TOKENS = 4096
# ── OpenRouter Configuration ─────────────────────────────────────────────────
OPENROUTER_BASE_URL = "https://openrouter.ai/api/v1/chat/completions"
# Primary: Gemini 2.5 Flash — best at technical/spatial drawings, fast & cheap
PRIMARY_MODEL = "google/gemini-2.5-flash"
# Fallback: Gemini 2.5 Pro — stronger reasoning for ambiguous/complex drawings
FALLBACK_MODEL = "google/gemini-2.5-pro"
MAX_TOKENS = 4096
# ── Demo Mode — low token usage for client demonstrations ─────────────────────
# Set DEMO_MODE=true in .env or environment, or pass demo_mode=True to classify_elevation()
# 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_DIMS = 8 # vs 30 pre-extracted dims sent in context
DEMO_MAX_RECTS = 10 # vs 40 rectangle vectors sent in context
# ══════════════════════════════════════════════════════════════════════════
# DATA CLASSES
@@ -71,7 +94,7 @@ class CabinetItem:
quantity: int = 1
is_ada: bool = False
notes: str = ""
source: str = "claude" # "claude" | "gpt4o" | "manual"
source: str = "gemini" # "gemini" | "manual" | "fallback"
@property
def code(self) -> str:
@@ -144,7 +167,20 @@ class ElevationResult:
# PROMPT BUILDER
# ══════════════════════════════════════════════════════════════════════════
def _build_system_prompt() -> str:
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."
)
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.
@@ -207,23 +243,31 @@ def _build_user_prompt(
pre_extracted_dims: list[dict],
pre_extracted_rects: list[dict],
is_ada: bool = False,
demo: bool = False,
) -> str:
"""Build the user message with pre-extracted context."""
ada_note = " (ADA ACCESSIBLE UNIT — base cabinet heights are 864mm max, countertop 34\" max)" if is_ada else ""
ada_note = " (ADA — base h≤864mm, countertop≤34\")" if is_ada else ""
# Demo mode: send fewer context items to save tokens
max_dims = DEMO_MAX_DIMS if demo else 30
max_rects = DEMO_MAX_RECTS if demo else 40
dims_str = ""
if pre_extracted_dims:
dims_str = "\n\nPRE-EXTRACTED DIMENSION VALUES (from PDF text, use these as ground truth):\n"
for d in pre_extracted_dims[:30]: # limit to 30 most relevant
dims_str += f" [{d.get('type','?')}] '{d.get('text','')}' at x={d.get('x',0):.0f}, y={d.get('y',0):.0f}\n"
dims_str = "\nDIMENSIONS (ground truth):\n"
for d in pre_extracted_dims[:max_dims]:
dims_str += f" [{d.get('type','?')}] '{d.get('text','')}' x={d.get('x',0):.0f} y={d.get('y',0):.0f}\n"
rects_str = ""
if pre_extracted_rects:
rects_str = "\n\nPRE-EXTRACTED RECTANGLE GEOMETRY (potential cabinet boxes from PDF vectors):\n"
for i, r in enumerate(pre_extracted_rects[:40]):
rects_str += (f" Rect {i+1}: x={r.get('x0',0):.1f}→{r.get('x1',0):.1f}, "
f"y={r.get('y0',0):.1f}→{r.get('y1',0):.1f}, "
f"W={r.get('w',0):.1f}pts, H={r.get('h',0):.1f}pts\n")
if pre_extracted_rects and not demo: # skip rect context in demo (saves ~300 tokens)
rects_str = "\nRECTANGLES (potential cabinet boxes):\n"
for i, r in enumerate(pre_extracted_rects[:max_rects]):
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")
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.")
return f"""Project: {project_name}
Unit Type: {unit_type}{ada_note}
@@ -251,7 +295,7 @@ Return ONLY the JSON array, nothing else."""
class CabinetVisionClassifier:
"""
Classifies cabinets from architectural elevation drawing images
using Groq API (llama-3.2-90b-vision-preview) — free & fast.
using Google Gemini vision models through OpenRouter.
Usage:
classifier = CabinetVisionClassifier()
@@ -264,25 +308,17 @@ class CabinetVisionClassifier:
"""
def __init__(self):
self._groq_client = None
self._validate_keys()
def _validate_keys(self):
if not GROQ_API_KEY:
if not OPENROUTER_API_KEY:
raise EnvironmentError(
"GROQ_API_KEY is not set.\n"
"1. Go to https://console.groq.com\n"
"2. Create an API key\n"
"3. Add to .env: GROQ_API_KEY=gsk_...\n"
"4. Or use --skip-ai flag to skip AI extraction"
"OPENROUTER_API_KEY is not set.\n"
"Get your key at: https://openrouter.ai\n"
"Add to .env: OPENROUTER_API_KEY=sk-or-v1-...\n"
"Or use --skip-ai flag to skip AI extraction"
)
def _get_groq(self):
if self._groq_client is None:
from groq import Groq
self._groq_client = Groq(api_key=GROQ_API_KEY)
return self._groq_client
# ── Main Classification ───────────────────────────────────────────────
def classify_elevation(
@@ -295,6 +331,7 @@ class CabinetVisionClassifier:
pre_extracted_rects: Optional[list[dict]] = None,
is_ada: bool = False,
max_retries: int = 3,
demo_mode: bool = None, # None = use global DEMO_MODE
) -> ElevationResult:
"""
Classify all cabinets in one elevation section.
@@ -312,6 +349,9 @@ class CabinetVisionClassifier:
Returns:
ElevationResult with list of CabinetItem
"""
# Resolve demo mode — argument overrides global flag
use_demo = DEMO_MODE if demo_mode is None else demo_mode
result = ElevationResult(
elevation_label = elevation_label,
unit_type = unit_type,
@@ -319,6 +359,11 @@ class CabinetVisionClassifier:
is_ada = is_ada,
)
if use_demo:
print(f" [AI-DEMO] Low-token mode: DPI={DEMO_DPI}, max_tokens={DEMO_MAX_TOKENS}")
# Downscale image from 400 DPI to 150 DPI equivalent using PIL if available
image_bytes = _downscale_image_if_possible(image_bytes, target_dpi=DEMO_DPI)
# Build the prompt
user_prompt = _build_user_prompt(
unit_type = unit_type,
@@ -327,37 +372,47 @@ class CabinetVisionClassifier:
pre_extracted_dims = pre_extracted_dims or [],
pre_extracted_rects = pre_extracted_rects or [],
is_ada = is_ada,
demo = use_demo,
)
# Encode image for API
image_b64 = base64.standard_b64encode(image_bytes).decode("utf-8")
# Demo: fewer retries, tighter token budget
retries = 1 if use_demo else max_retries
max_tokens = DEMO_MAX_TOKENS if use_demo else MAX_TOKENS
# Call Groq with retries
raw_json = self._call_groq(
# Call primary model (Gemini 2.5 Flash) with retries
mode_tag = "DEMO" if use_demo else "FULL"
print(f" [AI-{mode_tag}] Calling {PRIMARY_MODEL} for {elevation_label}...")
raw_json = self._call_openrouter(
image_bytes = image_bytes,
user_prompt = user_prompt,
max_retries = max_retries,
model = PRIMARY_MODEL,
max_retries = retries,
max_tokens = max_tokens,
)
result.api_calls += 1
if raw_json is None:
result.review_flags.append("Groq API call failed after all retries")
result.review_flags.append(f"{PRIMARY_MODEL} API call failed after all retries")
return result
# Parse JSON response
cabinets = self._parse_cabinet_json(raw_json, elevation_label)
if cabinets is None:
# Retry with explicit JSON fix instruction
if cabinets 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."
)
raw_json2 = self._call_groq(image_bytes, fix_prompt, max_retries=1)
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)
if cabinets is None:
result.review_flags.append("Failed to parse Groq JSON response")
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
result.cabinets = cabinets
@@ -373,51 +428,83 @@ class CabinetVisionClassifier:
)
return result
# ── Groq API Call ────────────────────────────────────────────────────
# ── OpenRouter API Call ──────────────────────────────────────────────────
def _call_groq(
def _call_openrouter(
self,
image_bytes: bytes,
user_prompt: str,
model: str = PRIMARY_MODEL,
max_retries: int = 3,
max_tokens: int = MAX_TOKENS,
) -> Optional[str]:
"""Call Groq llama-3.2-90b-vision API. Returns raw text or None."""
client = self._get_groq()
image_b64 = base64.standard_b64encode(image_bytes).decode("utf-8")
system_prompt = _build_system_prompt()
"""
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
print(f" [API] Image size: {img_kb:.1f} KB | max_tokens: {max_tokens}")
payload = json.dumps({
"model": model,
"max_tokens": max_tokens,
"temperature": 0.1,
"messages": [
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{image_b64}",
},
},
{"type": "text", "text": user_prompt},
],
},
],
}).encode("utf-8")
headers = {
"Authorization": f"Bearer {OPENROUTER_API_KEY}",
"Content-Type": "application/json",
"HTTP-Referer": "https://github.com/Prajwalabhang1/Cabinets",
"X-Title": "Cabinet Shop Drawing Generator",
}
for attempt in range(max_retries):
try:
response = client.chat.completions.create(
model=GROQ_MODEL,
max_tokens=GROQ_MAX_TOKENS,
temperature=0.1,
messages=[
{"role": "system", "content": system_prompt},
{
"role": "user",
"content": [
{
"type": "image_url",
"image_url": {
"url": f"data:image/png;base64,{image_b64}",
},
},
{"type": "text", "text": user_prompt},
],
},
],
req = urllib.request.Request(
OPENROUTER_BASE_URL,
data = payload,
headers = headers,
method = "POST",
)
return response.choices[0].message.content
with urllib.request.urlopen(req, timeout=60) as resp:
result = json.loads(resp.read())
content = result["choices"][0]["message"]["content"]
usage = result.get("usage", {})
cost = usage.get("cost", 0)
print(f" [OK] {model.split('/')[-1]} responded | "
f"tokens={usage.get('total_tokens',0)} | "
f"cost=${cost:.5f}")
return content
except Exception as e:
wait = 2 ** attempt
print(f" [WARN] Groq attempt {attempt+1}/{max_retries} failed: {e}")
print(f" [WARN] OpenRouter attempt {attempt+1}/{max_retries} "
f"({model}) failed: {e}")
if attempt < max_retries - 1:
print(f" Retrying in {wait}s...")
time.sleep(wait)
else:
print(" [FAIL] All Groq retries exhausted.")
print(f" [FAIL] All retries exhausted for {model}.")
return None
# ── JSON Parsing ──────────────────────────────────────────────────────
@@ -497,7 +584,7 @@ class CabinetVisionClassifier:
quantity = int(item.get("quantity", 1)),
is_ada = bool(item.get("is_ada", False)),
notes = str(item.get("notes", "")),
source = "groq",
source = "gemini",
))
return cabinets
@@ -578,6 +665,44 @@ def _default_depth(cabinet_type: str) -> float:
return defaults.get(cabinet_type, 600.0)
def _downscale_image_if_possible(image_bytes: bytes, target_dpi: int = 150) -> bytes:
"""
Reduce image size by downscaling.
In demo mode we crop at 400 DPI but then shrink to ~150 DPI equivalent
to dramatically cut vision token cost (~88% smaller image).
Falls back to returning original bytes if PIL/Pillow is not installed.
"""
try:
from PIL import Image
import io as _io
img = Image.open(_io.BytesIO(image_bytes))
orig_w, orig_h = img.size
scale = target_dpi / 400.0 # 400 DPI was used during crop
new_w = max(1, int(orig_w * scale))
new_h = max(1, int(orig_h * scale))
img_resized = img.resize((new_w, new_h), Image.LANCZOS)
buf = _io.BytesIO()
img_resized.save(buf, format="PNG", optimize=True)
result = buf.getvalue()
orig_kb = len(image_bytes) / 1024
result_kb = len(result) / 1024
print(f" [DEMO] Image scaled {orig_w}×{orig_h} → {new_w}×{new_h} "
f"({orig_kb:.0f} KB → {result_kb:.0f} KB, "
f"{100*(1-result_kb/orig_kb):.0f}% smaller)")
return result
except ImportError:
print(" [DEMO] Pillow not installed — sending original image size.")
return image_bytes
except Exception as e:
print(f" [DEMO] Downscale failed ({e}) — sending original image.")
return image_bytes
# ══════════════════════════════════════════════════════════════════════════
# QUICK TEST (no API needed — tests JSON parsing logic)
# ══════════════════════════════════════════════════════════════════════════
+13
View File
@@ -131,6 +131,19 @@ class CabinetValidator:
for cab in cabinets:
if cab.cabinet_type == "appliance_space":
continue # appliances are fine with non-standard widths
# Auto-fix: width=0 means Gemini couldn't read it → snap to 762mm default
if cab.width_mm <= 0:
old_w = cab.width_mm
cab.width_mm = 762.0 # 30" — most common standard cabinet width
corrections.append(
f"Item {cab.item_num} ({cab.cabinet_type}) had width={old_w:.0f}mm "
f"→ defaulted to 762mm (30\"). Verify against drawing."
)
warnings.append(
f"Item {cab.item_num} width was 0/null — used 762mm default"
)
nearest, delta = _nearest_standard_width(cab.width_mm)
if delta > CABINET_WIDTH_TOLERANCE_MM:
flags.append(
+8 -10
View File
@@ -24,11 +24,13 @@ ANTHROPIC_API_KEY: str = os.getenv("ANTHROPIC_API_KEY", "")
OPENAI_API_KEY: str = os.getenv("OPENAI_API_KEY", "")
GEMINI_API_KEY: str = os.getenv("GEMINI_API_KEY", "")
GROQ_API_KEY: str = os.getenv("GROQ_API_KEY", "")
OPENROUTER_API_KEY: str = os.getenv("OPENROUTER_API_KEY", "")
# ── Claude model config ─────────────────────────────────────────────────────
# Legacy provider constants retained for older experiments; production vision
# extraction uses OpenRouter Gemini from core.ai_vision_classifier.
CLAUDE_MODEL = "claude-3-5-sonnet-20241022"
CLAUDE_MAX_TOKENS = 4096
CLAUDE_TEMPERATURE = 0.1 # Low temp for structured/deterministic output
CLAUDE_TEMPERATURE = 0.1
GPT4O_MODEL = "gpt-4o"
# ── Currency & Unit Conversion ──────────────────────────────────────────────
@@ -126,14 +128,10 @@ CABINET_LIBRARY_PATH = PROJECT_ROOT / "data" / "cabinet_library.json"
def validate_config() -> list[str]:
"""Return a list of warnings about missing/invalid configuration."""
warnings = []
if not ANTHROPIC_API_KEY:
if not OPENROUTER_API_KEY:
warnings.append(
"ANTHROPIC_API_KEY not set — Claude Vision integration will not work. "
"Set it in .env or use --skip-ai flag."
)
if not OPENAI_API_KEY:
warnings.append(
"OPENAI_API_KEY not set — GPT-4o backup validation disabled."
"OPENROUTER_API_KEY not set - Gemini Vision extraction will be disabled. "
"Set it in .env or run with --skip-ai."
)
if EUR_USD_RATE <= 0:
warnings.append(f"EUR_USD_RATE={EUR_USD_RATE} is invalid.")
@@ -150,5 +148,5 @@ if __name__ == "__main__":
else:
print("✅ Configuration OK")
print(f"\n EUR/USD rate: {EUR_USD_RATE}")
print(f" Claude model: {CLAUDE_MODEL}")
print(f" OpenRouter key: {'SET' if OPENROUTER_API_KEY else 'NOT SET'}")
print(f" Auto-approve threshold: {AUTO_APPROVE_CONFIDENCE}")
+4 -4
View File
@@ -111,12 +111,12 @@ class JobCostingResult:
def print_report(self):
"""Print a formatted job costing report."""
inp = self.inputs
SEP = "─" * 65
print(f"\n{'═' * 65}")
SEP = "-" * 65
print(f"\n{'=' * 65}")
print(f" JOB COSTING REPORT")
print(f" Total Cabinets: {inp.total_cabinet_count:,} | "
f"Containers: {self.containers_needed}")
print(f"{'═' * 65}")
print(f"{'=' * 65}")
print(f"\n A. QUANTITIES")
print(f" {'Total Cabinets':45s} {inp.total_cabinet_count:>10,}")
@@ -162,7 +162,7 @@ class JobCostingResult:
print(f" {'Total Cost':45s} ${self.total_cost:>12,.2f}")
print(f" {'Cost per Cabinet':45s} ${self.cost_per_cabinet:>12,.2f}")
print(f" {'Sell per Cabinet':45s} ${self.sell_per_cabinet:>12,.2f}")
print(f"{'═' * 65}\n")
print(f"{'=' * 65}\n")
# ══════════════════════════════════════════════════════════════════════════
+94 -8
View File
@@ -98,7 +98,7 @@ class RegionDetector:
# ── Public API ────────────────────────────────────────────────────────
def detect(self) -> list[DetectedRegion]:
"""Main entry point. Returns all detected regions."""
"""Main entry point. Returns all detected regions, deduplicated."""
title_x = self.title_block_x
# 1. Find all keyword label hits
@@ -110,7 +110,13 @@ class RegionDetector:
# 3. Build crop zones with smart boundaries
regions = self._build_crop_zones(deduped, title_x)
# 4. Sort top-to-bottom, left-to-right
# 4. Remove overlapping regions (keep highest confidence)
regions = self._remove_overlapping_regions(regions)
# 5. Cap per-type to prevent explosion (max 2 KITCHEN, 2 BATH, 2 VANITY)
regions = self._cap_regions_per_type(regions)
# 6. Sort top-to-bottom, left-to-right
regions.sort(key=lambda r: (r.origin[1], r.origin[0]))
return regions
@@ -217,7 +223,7 @@ class RegionDetector:
def _deduplicate_hits(self, hits: list[dict]) -> list[dict]:
"""
Remove duplicate hits that are within 80 pts of each other
Remove duplicate hits that are within 200 pts of each other
(same label detected multiple times in different sub-spans).
Keep the hit with the largest font size (most prominent).
"""
@@ -226,7 +232,7 @@ class RegionDetector:
# Group by (region_type, x-cluster, y-cluster)
groups: list[list[dict]] = []
CLUSTER_DIST = 80.0 # pts
CLUSTER_DIST = 200.0 # pts — increased from 80 to collapse nearby duplicates
for hit in hits:
placed = False
@@ -234,7 +240,13 @@ class RegionDetector:
rep = group[0]
dx = abs(hit["origin"][0] - rep["origin"][0])
dy = abs(hit["origin"][1] - rep["origin"][1])
if hit["region_type"] == rep["region_type"] and dx < CLUSTER_DIST and dy < CLUSTER_DIST:
same_type = (
hit["region_type"] == rep["region_type"] or
# Also merge BATH/VANITY/MASTER_BATH into same cluster
(hit["region_type"] in ("BATH","VANITY","MASTER_BATH") and
rep["region_type"] in ("BATH","VANITY","MASTER_BATH"))
)
if same_type and dx < CLUSTER_DIST and dy < CLUSTER_DIST:
group.append(hit)
placed = True
break
@@ -350,10 +362,84 @@ class RegionDetector:
return columns
def _remove_overlapping_regions(
self,
regions: list[DetectedRegion],
) -> list[DetectedRegion]:
"""
Remove crop regions that heavily overlap each other.
If two regions of the SAME type share > 60% of the smaller one's area,
keep only the one with higher confidence (larger font = more prominent label).
"""
if len(regions) <= 1:
return regions
def overlap_ratio(a: DetectedRegion, b: DetectedRegion) -> float:
ix0 = max(a.x0, b.x0)
iy0 = max(a.y0, b.y0)
ix1 = min(a.x1, b.x1)
iy1 = min(a.y1, b.y1)
if ix1 <= ix0 or iy1 <= iy0:
return 0.0
inter = (ix1 - ix0) * (iy1 - iy0)
area_a = a.width * a.height
area_b = b.width * b.height
smaller = min(area_a, area_b)
return inter / smaller if smaller > 0 else 0.0
# Sort by confidence desc so we keep the best ones
sorted_r = sorted(regions, key=lambda r: -r.confidence)
kept: list[DetectedRegion] = []
for candidate in sorted_r:
dominated = False
for keeper in kept:
same_family = (
candidate.region_type == keeper.region_type or
(candidate.region_type in ("BATH","VANITY","MASTER_BATH") and
keeper.region_type in ("BATH","VANITY","MASTER_BATH"))
)
if same_family and overlap_ratio(candidate, keeper) > 0.60:
dominated = True
break
if not dominated:
kept.append(candidate)
return kept
def _cap_regions_per_type(
self,
regions: list[DetectedRegion],
) -> list[DetectedRegion]:
"""
Hard cap on how many regions of each type are sent to AI.
A unit plan has at most 2 kitchen elevations, 2 bath elevations,
1-2 vanity views. More than that = detector false positives.
"""
CAPS = {
"KITCHEN": 2,
"BATH": 2,
"VANITY": 2,
"MASTER_BATH": 1,
"ELEVATION_A": 1,
"ELEVATION_B": 1,
"ELEVATION_C": 1,
"ELEVATION_D": 1,
"FLOOR_PLAN": 1,
}
from collections import Counter
type_count: Counter = Counter()
capped: list[DetectedRegion] = []
# Sort by confidence desc so we keep the best detections
for r in sorted(regions, key=lambda r: -r.confidence):
cap = CAPS.get(r.region_type, 2)
if type_count[r.region_type] < cap:
capped.append(r)
type_count[r.region_type] += 1
return capped
# ══════════════════════════════════════════════════════════════════════════
# CONVENIENCE FUNCTIONS
# ══════════════════════════════════════════════════════════════════════════
def detect_regions(
spans: list[TextSpan],
+1 -1
View File
@@ -516,7 +516,7 @@ def generate_excel(
_build_shop_drawing_sheet(ws_sd, unit_type, config, schedule, st)
wb.save(str(output_path))
print(f" ✅ Excel saved: {output_path}")
print(f" [SUCCESS] Excel saved: {output_path}")
return output_path
@@ -522,7 +522,7 @@ def generate_shop_drawings(
c.showPage()
c.save()
print(f" ✅ Shop drawing PDF saved: {output_path} ({total_pages} pages)")
print(f" [SUCCESS] Shop drawing PDF saved: {output_path} ({total_pages} pages)")
return output_path
Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 KiB

After

Width:  |  Height:  |  Size: 877 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 459 KiB

After

Width:  |  Height:  |  Size: 86 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 130 KiB

After

Width:  |  Height:  |  Size: 678 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 352 KiB

After

Width:  |  Height:  |  Size: 326 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 222 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 458 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 842 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 351 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 458 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 829 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 351 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 49 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 458 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 58 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 93 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 351 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 164 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 458 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 138 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 351 KiB

File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -1,7 +0,0 @@
{
"unit_type": "A3",
"is_ada": false,
"auto_approved": false,
"review_flags": [],
"elevations": []
}
@@ -1,7 +0,0 @@
{
"unit_type": "B1",
"is_ada": false,
"auto_approved": false,
"review_flags": [],
"elevations": []
}
@@ -1,7 +0,0 @@
{
"unit_type": "B2-ADA",
"is_ada": true,
"auto_approved": false,
"review_flags": [],
"elevations": []
}
Binary file not shown.
+60 -55
View File
@@ -12,7 +12,7 @@
Steps executed:
1. Load project config
2. For each unit type: extract → detect regions → crop → Claude AI → validate
2. For each unit type: extract -> detect regions -> crop -> Gemini Vision -> validate
3. Count units (from floor plans or project_config.json)
4. Price match (Euro price list → USD)
5. Job costing (selling price)
@@ -32,11 +32,13 @@ from pathlib import Path
from typing import Optional
# ── Core modules ────────────────────────────────────────────────────────────
from core.config import get_output_dir, validate_config, GROQ_API_KEY
from core.config import get_output_dir, validate_config
from core.pdf_extractor import PDFExtractor
from core.ai_vision_classifier import (
CabinetVisionClassifier, ElevationResult, OPENROUTER_API_KEY
)
from core.region_detector import RegionDetector
from core.dimension_parser import classify_spans, associate_dims_to_rects
from core.ai_vision_classifier import CabinetVisionClassifier, ElevationResult
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
@@ -123,6 +125,7 @@ def process_unit(
classifier: Optional[CabinetVisionClassifier],
validator: CabinetValidator,
skip_ai: bool = False,
demo_mode: bool = False,
) -> UnitSchedule:
"""
Process one unit type PDF: extract → detect → crop → AI → validate.
@@ -154,7 +157,7 @@ def process_unit(
return schedule
if not pdf_path.exists():
print(f"\n ⚠️ [{unit_type}] PDF not found: {pdf_path}")
print(f"\n [WARN] [{unit_type}] PDF not found: {pdf_path}")
schedule.review_flags.append(f"PDF not found: {pdf_path}")
return schedule
@@ -166,7 +169,7 @@ def process_unit(
regions = detector.detect()
if not regions:
print(f" ⚠️ No elevation regions detected in {pdf_path.name}")
print(f" [WARN] No elevation regions detected in {pdf_path.name}")
schedule.review_flags.append("No elevation regions detected")
return schedule
@@ -209,7 +212,8 @@ def process_unit(
continue
# Call Gemini Vision API
print(f" Calling Claude Vision for {region.region_type}...")
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,
@@ -218,6 +222,7 @@ def process_unit(
pre_extracted_dims = pre_dims,
pre_extracted_rects = pre_rects,
is_ada = is_ada,
demo_mode = demo_mode,
)
# Validate
@@ -286,7 +291,7 @@ def compute_pricing(
use_fallback = not price_list_path.exists()
if use_fallback:
print(f"\n ⚠️ Price list not found — using fallback USD catalog: {price_list_path}")
print(f"\n [WARN] Price list not found — using fallback USD catalog: {price_list_path}")
else:
print(f"\n Loading price list: {price_list_path.name}")
@@ -297,7 +302,7 @@ def compute_pricing(
tier = config.get("price_list_tier", 1)
matcher = PriceMatcher(price_list_path, tier=tier, eur_usd_rate=eur_usd)
except Exception as e:
print(f" ⚠️ Failed to load price list: {e} — using fallback")
print(f" [WARN] Failed to load price list: {e} — using fallback")
total_material_cost = 0.0
total_cabinet_count = 0
@@ -305,7 +310,7 @@ def compute_pricing(
for unit_type, quantity in unit_totals.items():
schedule = unit_schedules.get(unit_type)
if not schedule:
print(f" ⚠️ No schedule found for {unit_type} — using fallback prices")
print(f" [WARN] No schedule found for {unit_type} — using fallback prices")
continue
unit_cost = 0.0
@@ -335,13 +340,14 @@ def run_pipeline(
skip_ai: bool = False,
unit_filter: Optional[str] = None,
dry_run: bool = False,
demo_mode: bool = False,
) -> PipelineResult:
"""
Run the complete cabinet estimation pipeline.
Args:
config_path: Path to project_config.json
skip_ai: If True, use cached JSON instead of calling Claude
skip_ai: If True, use cached JSON instead of calling Gemini Vision
unit_filter: If set, only process this unit type (e.g., "A1")
dry_run: If True, skip PDF generation (config check only)
"""
@@ -349,14 +355,15 @@ def run_pipeline(
config_path = Path(config_path)
project_root = Path.cwd() # resolve PDF paths relative to CWD
print(f"\n{'═' * 60}")
print(f" AI Cabinet Estimation Pipeline")
print(f"{'═' * 60}")
print(f"\n{'=' * 60}")
print(f" AI Cabinet Estimation Pipeline"
+ (" [DEMO MODE - low-token]" if demo_mode else ""))
print(f"{'=' * 60}")
# ── Check config ───────────────────────────────────────────────────────
config_warnings = validate_config()
for w in config_warnings:
print(f" ⚠️ {w}")
print(f" [WARN] {w}")
config = load_project_config(config_path)
project_name = config["project_name"]
@@ -373,13 +380,19 @@ def run_pipeline(
# ── Initialize AI classifier ───────────────────────────────────────────
classifier = None
if not skip_ai:
if not GROQ_API_KEY:
print("\n [WARN] GROQ_API_KEY not set — running in --skip-ai mode")
if not OPENROUTER_API_KEY:
print("\n [WARN] OPENROUTER_API_KEY not set — running in --skip-ai mode")
skip_ai = True
else:
try:
classifier = CabinetVisionClassifier()
print(" [OK] Groq llama-3.2-90b-vision classifier ready")
print(" [OK] OpenRouter vision classifier ready")
print(" [OK] Primary: google/gemini-2.5-flash")
if demo_mode:
print(" [OK] Demo mode: 150 DPI image, compact prompt, 1 retry")
print(" (Est. cost: ~$0.0002/call vs $0.0015 in full mode)")
else:
print(" [OK] Fallback: google/gemini-2.5-pro")
except EnvironmentError as e:
print(f" [FAIL] {e}")
skip_ai = True
@@ -392,7 +405,7 @@ def run_pipeline(
unit_schedules: dict[str, UnitSchedule] = {}
print(f"\n STEP 1: PDF Extraction + AI Classification")
print(f" {'─' * 50}")
print(f" {'-' * 50}")
for unit_type, pdf_rel_path in unit_plan_pdfs.items():
if unit_filter and unit_type != unit_filter:
@@ -410,12 +423,13 @@ def run_pipeline(
classifier = classifier,
validator = validator,
skip_ai = skip_ai,
demo_mode = demo_mode,
)
unit_schedules[unit_type] = schedule
# ── Step 2: Unit counts ────────────────────────────────────────────────
print(f"\n STEP 2: Unit Count Matrix")
print(f" {'─' * 50}")
print(f" {'-' * 50}")
unit_counts_config = config.get("unit_counts", {})
if unit_counts_config:
@@ -431,20 +445,20 @@ def run_pipeline(
unit_totals = matrix.totals
# ── Step 3–4: Pricing + Job Costing ───────────────────────────────────
print(f"\n STEP 3: Price Matching (Euro list → USD)")
print(f" {'─' * 50}")
print(f"\n STEP 3: Price Matching (Euro list -> USD)")
print(f" {'-' * 50}")
if unit_schedules and any(s.all_cabinets for s in unit_schedules.values()):
material_cost_usd, total_cabinet_count = compute_pricing(
unit_schedules, unit_totals, config, project_root
)
else:
print(" ⚠️ No cabinet schedules available — using manual cost estimate")
print(" [WARN] No cabinet schedules available — using manual cost estimate")
material_cost_usd = 0.0
total_cabinet_count = sum(unit_totals.values()) * 10 # rough estimate
print(f"\n STEP 4: Job Costing")
print(f" {'─' * 50}")
print(f" {'-' * 50}")
jc_input = JobCostingInput(
total_cabinet_count = total_cabinet_count,
@@ -459,7 +473,7 @@ def run_pipeline(
# ── Step 5: Generate Excel ─────────────────────────────────────────────
print(f"\n STEP 5: Generating Excel Estimation")
print(f" {'─' * 50}")
print(f" {'-' * 50}")
try:
from generators.cabinet_excel import generate_excel
@@ -471,52 +485,38 @@ def run_pipeline(
jc_result = jc_result,
output_path = str(excel_path),
)
print(f" ✅ Excel saved: {excel_path}")
print(f" [SUCCESS] Excel saved: {excel_path}")
except Exception as e:
print(f" ❌ Excel generation failed: {e}")
print(f" [ERROR] Excel generation failed: {e}")
import traceback; traceback.print_exc()
# ── Step 6: Generate Shop Drawing PDF ─────────────────────────────────
print(f"\n STEP 6: Generating Shop Drawing PDF")
print(f" {'─' * 50}")
print(f" {'-' * 50}")
try:
pdf_out = output_dir / f"{project_id}_Shop_Drawings.pdf"
if project_id == "23-033":
print(" Using high-fidelity vector compiler for Casa Familia...")
from generate_italiankb_shop_drawings import compile_shop_drawings
compile_shop_drawings(
ref_pdf_path = r"Casa familia\03_Shop_Drawings\ITALIANKB SHOP DRAWINGS - 23-033 CASA FAMILIA - 03.04.2025 hatch corregido.pdf",
output_pdf_path = str(pdf_out)
)
elif project_id == "23-045":
print(" Using high-fidelity vector compiler for Heritage Village...")
from generate_heritage_shop_drawings import compile_heritage_shop_drawings
compile_heritage_shop_drawings(
ref_dir_path = r"Heritage\01_Architectural_Drawings\Unit_Plans_FHA_ADA",
output_pdf_path = str(pdf_out)
)
else:
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" ✅ PDF saved: {pdf_out}")
# 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}")
except Exception as e:
print(f" ❌ PDF generation failed: {e}")
print(f" [ERROR] PDF generation failed: {e}")
import traceback; traceback.print_exc()
# ── Summary ────────────────────────────────────────────────────────────
# -- Summary ------------------------------------------------------------
duration = time.time() - start_time
print(f"\n{'═' * 60}")
print(f" ✅ PIPELINE COMPLETE in {duration:.1f}s")
print(f"\n{'=' * 60}")
print(f" [SUCCESS] PIPELINE COMPLETE in {duration:.1f}s")
print(f" Total cabinets: {total_cabinet_count:,}")
print(f" Material cost: ${material_cost_usd:,.2f}")
print(f" Selling price: ${jc_result.selling_price:,.2f}")
print(f"{'═' * 60}\n")
print(f"{'=' * 60}\n")
return PipelineResult(
project_name = project_name,
@@ -562,6 +562,10 @@ Examples:
"--dry-run", action="store_true",
help="Validate config and print plan without executing"
)
parser.add_argument(
"--demo", action="store_true",
help="Demo mode: lower image DPI + compact prompt — saves ~85%% Vision API tokens"
)
return parser.parse_args()
@@ -572,4 +576,5 @@ if __name__ == "__main__":
skip_ai = args.skip_ai,
unit_filter = args.unit,
dry_run = args.dry_run,
demo_mode = args.demo,
)
@@ -11,39 +11,35 @@
"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",
"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",
"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
"A1": 14,
"A2-ADA": 3,
"A3": 2,
"B1": 3,
"B2-ADA": 3
},
"ada_units": ["A2-ADA", "B2-ADA"],
"ada_units": [
"A2-ADA",
"B2-ADA"
],
"appliances_regular": [
"28\" REFRIGERATOR GE MODEL GTE18GSNRSS",
"30\" GAS RANGE GE MODEL JGBS60SPSS",
@@ -56,7 +52,6 @@
"MICROWAVE GE MODEL JEM3072DHWW",
"24\" DISHWASHER GE MODEL GDF535PSRSS"
],
"general_notes": [
"ALL CABINETS ARE 90CM DEPTH",
"FINISH: K019 SILVER LIBERTY ELM",
@@ -65,9 +60,7 @@
"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",
@@ -75,4 +68,4 @@
"phone": "T. 305.599.9000 F. 305.599.9870",
"website": "www.italiankitchenandbath.com"
}
}
}
+3
View File
@@ -1,6 +1,9 @@
pymupdf>=1.24.0
reportlab>=4.2.0
openpyxl>=3.1.0
fastapi>=0.115.0
uvicorn[standard]>=0.30.0
python-multipart>=0.0.9
anthropic>=0.25.0
openai>=1.30.0
shapely>=2.0.0
+986
View File
@@ -0,0 +1,986 @@
"""
===========================================================================
web_app/app.py — FastAPI Backend (Full Production)
===========================================================================
Endpoints:
GET /api/projects list all projects
POST /api/projects/create create new project from wizard
POST /api/projects/{id}/upload-pdf upload architectural PDF for a unit
POST /api/projects/{id}/upload-price-list upload price list Excel
POST /api/projects/{id}/save-config update financial params
GET /api/projects/{id}/run SSE pipeline stream
GET /api/projects/{id}/results aggregated results + costing
GET /api/projects/{id}/status quick status check
DELETE /api/projects/{id} delete project + outputs
GET /api/projects/{id}/download/pdf serve shop drawing PDF
GET /api/projects/{id}/download/excel serve costing Excel
GET /api/projects/{id}/crops/{file} serve elevation crop PNG
GET /api/projects/{id}/regions/{unit} detected region coords
GET /api/projects/{id}/pdf-pages/{unit} PDF thumbnail PNG
GET / serve static dashboard
===========================================================================
"""
from __future__ import annotations
import json
import re
import shutil
import sys
import os
import asyncio
import tempfile
from pathlib import Path
from typing import Any, Optional
import fitz # PyMuPDF
from fastapi import FastAPI, HTTPException, Request, UploadFile, File, Form
from fastapi.responses import (
FileResponse, StreamingResponse, Response, JSONResponse
)
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware
# ── Resolve project root ──────────────────────────────────────────────────────
_HERE = Path(__file__).resolve().parent
PROJECT_ROOT = _HERE.parent
if str(PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(PROJECT_ROOT))
from core.config import get_output_dir, OUTPUTS_ROOT, OPENROUTER_API_KEY # noqa: E402
from core.ai_vision_classifier import PRIMARY_MODEL, FALLBACK_MODEL, DEMO_MODE # noqa: E402
app = FastAPI(
title = "ItalianKB Cabinet Estimator",
description = "AI-powered cabinet shop drawing and job costing automation",
version = "2.0.0",
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
PROJECTS_ROOT = PROJECT_ROOT / "projects"
PROJECTS_ROOT.mkdir(exist_ok=True)
MAX_PDF_UPLOAD_BYTES = 100 * 1024 * 1024
MAX_EXCEL_UPLOAD_BYTES = 25 * 1024 * 1024
# ─────────────────────────────────────────────────────────────────────────────
# INTERNAL HELPERS
# ─────────────────────────────────────────────────────────────────────────────
def _slugify(text: str) -> str:
"""Convert project name/id to a safe folder name."""
return re.sub(r"[^a-zA-Z0-9_-]", "_", text.strip().lower())[:40]
def _validate_project_id(project_id: str) -> str:
"""Validate a project id before it is used for folders or output paths."""
project_id = project_id.strip()
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{1,40}", project_id):
raise HTTPException(
400,
"project_id must be 2-41 characters and contain only letters, "
"numbers, dot, underscore, or hyphen.",
)
if ".." in project_id:
raise HTTPException(400, "project_id cannot contain '..'.")
return project_id
def _safe_upload_name(name: str, fallback: str) -> str:
"""Return a safe basename for a user-supplied upload filename."""
stem = Path(name or fallback).stem
suffix = Path(name or fallback).suffix.lower()
safe_stem = _slugify(stem) or fallback
return f"{safe_stem}{suffix}"
def _ensure_inside(child: Path, parent: Path) -> Path:
"""Resolve a path and ensure it remains under the expected parent."""
resolved = child.resolve()
parent = parent.resolve()
if parent not in resolved.parents and resolved != parent:
raise HTTPException(400, "Resolved upload path escaped project folder.")
return resolved
def _find_project(project_id: str) -> Optional[tuple[dict, Path, Path]]:
"""
Search all project folders for one matching project_id.
Returns (config_dict, config_path, project_folder) or None.
"""
if not PROJECTS_ROOT.exists():
return None
for folder in PROJECTS_ROOT.iterdir():
if not folder.is_dir():
continue
cfg_path = folder / "project_config.json"
if not cfg_path.exists():
continue
try:
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
if cfg.get("project_id") == project_id:
return cfg, cfg_path, folder
except Exception:
continue
return None
def _sse(obj: Any) -> str:
return f"data: {json.dumps(obj, ensure_ascii=False)}\n\n"
def _default_price_list_path() -> Optional[str]:
"""Return relative path to default price list if one exists."""
# Look for any Excel price list in known locations
candidates = [
PROJECT_ROOT / "Casa familia" / "02_Price_List" / "MS PRICE LIST LEVEL 1 -90CM.xlsx",
PROJECT_ROOT / "Heritage" / "02_Price_List" / "MS PRICE LIST LEVEL 1 -90CM.xlsx",
]
for c in candidates:
if c.exists():
return str(c.relative_to(PROJECT_ROOT))
return None
@app.get("/api/health")
async def health():
"""Production readiness snapshot without exposing any secrets."""
default_price_list = _default_price_list_path()
project_count = 0
if PROJECTS_ROOT.exists():
project_count = sum(
1 for f in PROJECTS_ROOT.iterdir()
if f.is_dir() and (f / "project_config.json").exists()
)
return {
"status": "ok",
"version": app.version,
"ai": {
"provider": "OpenRouter",
"primary_model": PRIMARY_MODEL,
"fallback_model": FALLBACK_MODEL,
"openrouter_key_configured": bool(OPENROUTER_API_KEY),
"demo_mode_default": DEMO_MODE,
},
"storage": {
"projects_root": str(PROJECTS_ROOT),
"outputs_root": str(OUTPUTS_ROOT),
"project_count": project_count,
"default_price_list_available": bool(default_price_list),
"default_price_list_path": default_price_list,
},
"limits": {
"max_pdf_upload_mb": MAX_PDF_UPLOAD_BYTES // (1024 * 1024),
"max_excel_upload_mb": MAX_EXCEL_UPLOAD_BYTES // (1024 * 1024),
},
}
# ─────────────────────────────────────────────────────────────────────────────
# GET /api/projects — list all
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/api/projects")
async def list_projects():
results = []
if not PROJECTS_ROOT.exists():
return results
for folder in sorted(PROJECTS_ROOT.iterdir()):
if not folder.is_dir():
continue
cfg_path = folder / "project_config.json"
if not cfg_path.exists():
continue
try:
cfg = json.loads(cfg_path.read_text(encoding="utf-8"))
pid = cfg.get("project_id", "")
out_dir = OUTPUTS_ROOT / pid
results.append({
"id": pid,
"name": cfg.get("project_name", "Unnamed"),
"folder_name": folder.name,
"config": cfg,
"has_results": (out_dir / "json").exists() and
any((out_dir / "json").iterdir()),
"has_pdf": (out_dir / f"{pid}_Shop_Drawings.pdf").exists(),
"has_excel": (out_dir / f"{pid}_Cabinet_Estimation.xlsx").exists(),
})
except Exception as exc:
print(f"[WARN] Cannot read {cfg_path}: {exc}")
return results
# ─────────────────────────────────────────────────────────────────────────────
# POST /api/projects/create — create new project from wizard
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/projects/create")
async def create_project(request: Request):
"""
Create a new project from the wizard.
Expects JSON body matching the project config schema.
Automatically fills in price_list_path with the default if not provided.
"""
try:
body = await request.json()
except Exception as exc:
raise HTTPException(400, f"Invalid JSON: {exc}")
project_id = _validate_project_id(body.get("project_id", ""))
project_name = body.get("project_name", "").strip()
if not project_name:
raise HTTPException(400, "project_name is required")
# Check for duplicate
if _find_project(project_id):
raise HTTPException(409, f"Project ID '{project_id}' already exists.")
# Create project folder
folder_name = _slugify(project_id)
project_folder = PROJECTS_ROOT / folder_name
counter = 0
while project_folder.exists():
counter += 1
project_folder = PROJECTS_ROOT / f"{folder_name}_{counter}"
project_folder.mkdir(parents=True)
(project_folder / "drawings").mkdir()
# If no price list path provided, use the default ItalianKB list
if not body.get("price_list_path"):
default = _default_price_list_path()
if default:
body["price_list_path"] = default
# Build full config
config = {
"project_id": project_id,
"project_name": project_name,
"date": body.get("date", ""),
"revision": body.get("revision", "1.0"),
"drawn_by": body.get("drawn_by", ""),
"checker": body.get("checker", ""),
"client_name": body.get("client_name", ""),
"architect": body.get("architect", ""),
"project_address": body.get("project_address", ""),
"cabinet_finish": body.get("cabinet_finish", ""),
"door_style": body.get("door_style", ""),
"finish_tier": body.get("finish_tier", 1),
"gp_target_pct": float(body.get("gp_target_pct", 0.35)),
"commission_pct": float(body.get("commission_pct", 0.05)),
"bond_pct": float(body.get("bond_pct", 0.015)),
"price_list_tier": int(body.get("price_list_tier", 1)),
"eur_usd_rate": float(body.get("eur_usd_rate", 1.09)),
"price_list_path": body.get("price_list_path", ""),
# Will be populated by upload-pdf endpoint
"unit_plan_pdfs": body.get("unit_plan_pdfs", {}),
"unit_counts": body.get("unit_counts", {}),
"ada_units": body.get("ada_units", []),
"floor_plan_pdfs": body.get("floor_plan_pdfs", []),
"appliances_regular": body.get("appliances_regular", []),
"appliances_ada": body.get("appliances_ada", []),
"general_notes": body.get("general_notes", [
"ALL CABINETS ARE 90CM DEPTH",
"ALL HARDWARE CONCEALED",
"SOFT CLOSE DOORS AND DRAWERS STANDARD",
]),
"company": body.get("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",
}),
}
cfg_path = project_folder / "project_config.json"
cfg_path.write_text(
json.dumps(config, indent=2, ensure_ascii=False),
encoding="utf-8",
)
# Create output directory structure
get_output_dir(project_id)
return {
"status": "created",
"project_id": project_id,
"folder": project_folder.name,
"config": config,
}
# ─────────────────────────────────────────────────────────────────────────────
# POST /api/projects/{id}/upload-pdf — upload architectural PDF
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/projects/{project_id}/upload-pdf")
async def upload_pdf(
project_id: str,
unit_type: str = Form(...),
is_ada: bool = Form(False),
file: UploadFile = File(...),
):
"""
Upload one architectural PDF for a specific unit type.
Saves to projects/{folder}/drawings/{unit_type}.pdf
Updates project_config.json with the new unit_plan_pdfs entry.
"""
result = _find_project(project_id)
if result is None:
raise HTTPException(404, f"Project '{project_id}' not found")
cfg, cfg_path, project_folder = result
if not file.filename.lower().endswith(".pdf"):
raise HTTPException(400, "Only PDF files are accepted for unit drawings.")
unit_type = unit_type.strip()
if not unit_type:
raise HTTPException(400, "unit_type is required.")
# Save the PDF
drawings_dir = project_folder / "drawings"
drawings_dir.mkdir(exist_ok=True)
safe_unit = _slugify(unit_type)
if not safe_unit:
raise HTTPException(400, "unit_type must contain letters or numbers.")
dest = _ensure_inside(drawings_dir / f"{safe_unit}.pdf", drawings_dir)
content = await file.read()
if not content:
raise HTTPException(400, "Uploaded PDF is empty.")
if len(content) > MAX_PDF_UPLOAD_BYTES:
raise HTTPException(413, "PDF upload exceeds 100 MB limit.")
try:
doc = fitz.open(stream=content, filetype="pdf")
page_count = doc.page_count
doc.close()
except Exception as exc:
raise HTTPException(400, f"Uploaded file is not a valid PDF: {exc}")
dest.write_bytes(content)
# Update config — store path RELATIVE to PROJECT_ROOT
rel_path = str(dest.relative_to(PROJECT_ROOT))
cfg.setdefault("unit_plan_pdfs", {})[unit_type] = rel_path
# Track ADA status
ada_units = set(cfg.get("ada_units", []))
if is_ada:
ada_units.add(unit_type)
else:
ada_units.discard(unit_type)
cfg["ada_units"] = sorted(ada_units)
cfg_path.write_text(
json.dumps(cfg, indent=2, ensure_ascii=False),
encoding="utf-8",
)
return {
"status": "uploaded",
"unit_type": unit_type,
"path": rel_path,
"pages": page_count,
"size_kb": round(len(content) / 1024, 1),
}
# ─────────────────────────────────────────────────────────────────────────────
# POST /api/projects/{id}/upload-price-list — upload Excel price list
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/projects/{project_id}/upload-price-list")
async def upload_price_list(
project_id: str,
file: UploadFile = File(...),
):
result = _find_project(project_id)
if result is None:
raise HTTPException(404, f"Project '{project_id}' not found")
cfg, cfg_path, project_folder = result
if not file.filename.lower().endswith(".xlsx"):
raise HTTPException(400, "Only .xlsx Excel files are accepted.")
dest = _ensure_inside(project_folder / "price_list.xlsx", project_folder)
content = await file.read()
if not content:
raise HTTPException(400, "Uploaded price list is empty.")
if len(content) > MAX_EXCEL_UPLOAD_BYTES:
raise HTTPException(413, "Price list upload exceeds 25 MB limit.")
tmp_path = None
try:
from openpyxl import load_workbook
with tempfile.NamedTemporaryFile(suffix=".xlsx", delete=False) as tmp:
tmp.write(content)
tmp_path = tmp.name
wb = load_workbook(tmp_path, read_only=True, data_only=True)
sheet_count = len(wb.sheetnames)
wb.close()
Path(tmp_path).unlink(missing_ok=True)
except Exception as exc:
if tmp_path:
try:
Path(tmp_path).unlink(missing_ok=True)
except Exception:
pass
raise HTTPException(400, f"Uploaded file is not a valid .xlsx workbook: {exc}")
dest.write_bytes(content)
rel_path = str(dest.relative_to(PROJECT_ROOT))
cfg["price_list_path"] = rel_path
cfg_path.write_text(
json.dumps(cfg, indent=2, ensure_ascii=False),
encoding="utf-8",
)
return {
"status": "uploaded",
"path": rel_path,
"sheets": sheet_count,
"size_kb": round(len(content) / 1024, 1),
}
# ─────────────────────────────────────────────────────────────────────────────
# POST /api/projects/{id}/save-config — update project config
# ─────────────────────────────────────────────────────────────────────────────
@app.post("/api/projects/{project_id}/save-config")
async def save_config(project_id: str, request: Request):
result = _find_project(project_id)
if result is None:
raise HTTPException(404, f"Project '{project_id}' not found")
_, cfg_path, _ = result
try:
new_config = await request.json()
except Exception as exc:
raise HTTPException(400, f"Invalid JSON body: {exc}")
cfg_path.write_text(
json.dumps(new_config, indent=2, ensure_ascii=False),
encoding="utf-8",
)
return {"status": "ok", "message": "Configuration saved."}
# ─────────────────────────────────────────────────────────────────────────────
# DELETE /api/projects/{id} — delete project + outputs
# ─────────────────────────────────────────────────────────────────────────────
@app.delete("/api/projects/{project_id}")
async def delete_project(project_id: str):
result = _find_project(project_id)
if result is None:
raise HTTPException(404, f"Project '{project_id}' not found")
_, _, project_folder = result
# Remove project folder
shutil.rmtree(project_folder, ignore_errors=True)
# Remove outputs folder
out_dir = OUTPUTS_ROOT / project_id
if out_dir.exists():
shutil.rmtree(out_dir, ignore_errors=True)
return {"status": "deleted", "project_id": project_id}
# ─────────────────────────────────────────────────────────────────────────────
# GET /api/projects/{id}/status — quick status check
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/api/projects/{project_id}/status")
async def project_status(project_id: str):
result = _find_project(project_id)
if result is None:
raise HTTPException(404, f"Project '{project_id}' not found")
cfg, _, _ = result
out_dir = OUTPUTS_ROOT / project_id
json_dir = out_dir / "json"
has_cache = json_dir.exists() and any(json_dir.glob("cabinet_schedule_*.json"))
has_pdf = (out_dir / f"{project_id}_Shop_Drawings.pdf").exists()
has_excel = (out_dir / f"{project_id}_Cabinet_Estimation.xlsx").exists()
unit_pdfs = cfg.get("unit_plan_pdfs", {})
pdfs_ok = {
u: (PROJECT_ROOT / p).exists()
for u, p in unit_pdfs.items()
}
return {
"project_id": project_id,
"project_name": cfg.get("project_name"),
"units": list(unit_pdfs.keys()),
"pdf_files_ok": pdfs_ok,
"ai_ready": bool(OPENROUTER_API_KEY),
"price_list_ok": bool(cfg.get("price_list_path")) and
(PROJECT_ROOT / cfg.get("price_list_path", "")).exists(),
"has_cache": has_cache,
"has_pdf": has_pdf,
"has_excel": has_excel,
"ready_to_run": bool(unit_pdfs) and all(pdfs_ok.values()),
}
# ─────────────────────────────────────────────────────────────────────────────
# GET /api/projects/{id}/run — run pipeline via SSE
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/api/projects/{project_id}/run")
async def run_pipeline(
project_id: str,
skip_ai: bool = True,
unit: str = None,
demo: bool = False,
):
result = _find_project(project_id)
if result is None:
raise HTTPException(404, "Project not found")
_, cfg_path, _ = result
cmd = [sys.executable, str(PROJECT_ROOT / "pipeline.py"),
"--project", str(cfg_path)]
if skip_ai:
cmd.append("--skip-ai")
if unit:
cmd += ["--unit", unit]
if demo:
cmd.append("--demo")
async def generator():
mode_label = "DEMO (low-token)" if demo else "FULL"
launch_msg = f"[{mode_label}] Launching: " + " ".join(str(c) for c in cmd)
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,
cwd=str(PROJECT_ROOT),
env=env,
)
except Exception as exc:
yield _sse({"log": f"[ERROR] Cannot start process: {exc}",
"done": True, "success": False})
return
while True:
line = await proc.stdout.readline()
if not line:
break
text = line.decode("utf-8", errors="replace").rstrip("\r\n")
if text:
yield _sse({"log": text})
code = await proc.wait()
yield _sse({
"log": f"[SYSTEM] Pipeline finished (exit {code}).",
"done": True,
"success": code == 0,
})
return StreamingResponse(
generator(),
media_type="text/event-stream",
headers={
"Cache-Control": "no-cache",
"X-Accel-Buffering": "no",
},
)
# ─────────────────────────────────────────────────────────────────────────────
# GET /api/projects/{id}/results — aggregated results
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/api/projects/{project_id}/results")
async def get_results(project_id: str):
out_dir = OUTPUTS_ROOT / project_id
if not out_dir.exists():
return JSONResponse(
status_code=404,
content={"detail": "No outputs yet — run the pipeline first."},
)
result = _find_project(project_id)
if result is None:
return JSONResponse(
status_code=404,
content={"detail": "Project config not found."},
)
config, _, _ = result
# ── Load cached JSON schedules ──────────────────────────────────────────
unit_schedules: dict = {}
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_"):
continue
raw_key = f.stem.replace("cabinet_schedule_", "")
# Find matching key in config (handles underscore/hyphen normalization)
unit_keys = list(config.get("unit_plan_pdfs", {}).keys())
matched_key = raw_key
for k in unit_keys:
if k.replace(" ", "_").replace("-", "_") == raw_key:
matched_key = k
break
try:
unit_schedules[matched_key] = json.loads(
f.read_text(encoding="utf-8")
)
except Exception as exc:
print(f"[WARN] Cannot parse {f.name}: {exc}")
# ── Price matching ──────────────────────────────────────────────────────
unit_totals = config.get("unit_counts", {})
price_list = PROJECT_ROOT / config.get("price_list_path", "")
matcher = None
if price_list.exists():
try:
from core.price_matcher import PriceMatcher
matcher = PriceMatcher(
price_list,
tier=config.get("price_list_tier", 1),
eur_usd_rate=config.get("eur_usd_rate", 1.09),
)
except Exception as exc:
print(f"[WARN] PriceMatcher failed: {exc}")
from core.price_matcher import _generate_code, get_fallback_price_usd
from core.ai_vision_classifier import CabinetItem
total_material = 0.0
total_cabs = 0
line_items = []
for unit_type, qty in unit_totals.items():
sched = unit_schedules.get(unit_type)
if not sched:
continue
for ev in sched.get("elevations", []):
for cab_data in ev.get("cabinets", []):
try:
cab = CabinetItem(**cab_data)
except Exception:
continue
if cab.cabinet_type == "appliance_space":
continue
unit_price = 0.0
unit_price_eur = 0.0
match_quality = "NOT_FOUND"
matched_desc = cab.cabinet_type
h_mm = cab.height_mm
d_mm = cab.depth_mm
cab_code = cab.code
if matcher:
res = matcher.match(
cab.cabinet_type, cab.width_mm, quantity=cab.quantity
)
unit_price = res.price_usd
unit_price_eur = res.price_eur
match_quality = res.match_quality
if res.matched_entry:
matched_desc = res.matched_entry.description
h_mm = res.matched_entry.height_mm
d_mm = res.matched_entry.depth_mm
else:
code = _generate_code(cab.cabinet_type, cab.width_mm)
unit_price = get_fallback_price_usd(code)
unit_price_eur = unit_price / config.get("eur_usd_rate", 1.09)
match_quality = "FALLBACK"
cab_count = cab.quantity * qty
total_material += unit_price * cab_count
total_cabs += cab_count
line_items.append({
"unit_type": unit_type,
"elevation": ev.get("elevation_label"),
"item_num": cab.item_num,
"type": cab.cabinet_type,
"code": cab_code,
"width_mm": cab.width_mm,
"height_mm": h_mm,
"depth_mm": d_mm,
"confidence": cab.confidence,
"quantity": cab.quantity,
"unit_qty": qty,
"total_qty": cab_count,
"unit_price_usd": unit_price,
"unit_price_eur": unit_price_eur,
"total_price_usd": unit_price * cab_count,
"match_quality": match_quality,
"matched_desc": matched_desc,
"notes": cab.notes,
"source": cab.source,
"is_ada": cab.is_ada,
})
validation_flags = []
low_confidence_items = []
invalid_dimension_items = []
schedule_review_flags = []
price_match_counts = {}
for unit_type, sched in unit_schedules.items():
for flag in sched.get("review_flags", []) or []:
schedule_review_flags.append({"unit_type": unit_type, "flag": flag})
validation_flags.append(f"{unit_type}: {flag}")
for ev in sched.get("elevations", []) or []:
elev_label = ev.get("elevation_label")
for flag in ev.get("review_flags", []) or []:
schedule_review_flags.append({
"unit_type": unit_type,
"elevation": elev_label,
"flag": flag,
})
validation_flags.append(f"{unit_type}/{elev_label}: {flag}")
for cab in ev.get("cabinets", []) or []:
conf = float(cab.get("confidence") or 0)
if conf < 0.70:
low_confidence_items.append({
"unit_type": unit_type,
"elevation": elev_label,
"item_num": cab.get("item_num"),
"type": cab.get("cabinet_type"),
"confidence": conf,
})
if any(float(cab.get(k) or 0) <= 0 for k in ("width_mm", "height_mm", "depth_mm")):
invalid_dimension_items.append({
"unit_type": unit_type,
"elevation": elev_label,
"item_num": cab.get("item_num"),
"type": cab.get("cabinet_type"),
"width_mm": cab.get("width_mm"),
"height_mm": cab.get("height_mm"),
"depth_mm": cab.get("depth_mm"),
})
for item in line_items:
quality = item.get("match_quality", "UNKNOWN")
price_match_counts[quality] = price_match_counts.get(quality, 0) + 1
if quality == "NOT_FOUND":
validation_flags.append(
f"{item.get('unit_type')}/{item.get('elevation')} item "
f"{item.get('item_num')}: price match not found"
)
if invalid_dimension_items:
validation_flags.append(
f"{len(invalid_dimension_items)} cabinet item(s) have missing or zero dimensions"
)
if low_confidence_items:
validation_flags.append(
f"{len(low_confidence_items)} cabinet item(s) below 70% confidence"
)
validation = {
"status": "PASS" if not validation_flags else "REVIEW",
"flag_count": len(validation_flags),
"flags": validation_flags[:50],
"review_flags": schedule_review_flags,
"low_confidence_items": low_confidence_items,
"invalid_dimension_items": invalid_dimension_items,
"price_match_counts": price_match_counts,
}
# ── Job costing ─────────────────────────────────────────────────────────
from core.job_costing import JobCostingInput, calculate_selling_price
jc = calculate_selling_price(JobCostingInput(
total_cabinet_count = max(total_cabs, 1),
material_cost_usd = total_material,
gp_target_pct = config.get("gp_target_pct", 0.35),
commission_pct = config.get("commission_pct", 0.05),
bond_pct = config.get("bond_pct", 0.015),
))
costing = {
"material_cost": jc.material_cost,
"local_use_tax": jc.local_use_tax,
"ocean_freight": jc.ocean_freight,
"inland_delivery": jc.inland_delivery,
"installation": jc.installation,
"warehousing": jc.warehousing,
"material_protection": jc.material_protection,
"insurance": jc.insurance,
"misc_allowance": jc.misc_allowance,
"pre_margin_total": jc.pre_margin_total,
"selling_price": jc.selling_price,
"gross_profit": jc.gross_profit,
"total_cost": jc.total_cost,
"containers_needed": jc.containers_needed,
"cost_per_cabinet": jc.cost_per_cabinet,
"sell_per_cabinet": jc.sell_per_cabinet,
"gp_pct": jc.gp_pct,
"commission_pct": jc.commission_pct,
"bond_pct": jc.bond_pct,
"total_cabinet_count": total_cabs,
}
api_calls = sum(
ev.get("api_calls", 1)
for sched in unit_schedules.values()
for ev in sched.get("elevations", [])
)
tok_in = api_calls * 5_000
tok_out = api_calls * 350
metrics = {
"api_calls": api_calls,
"input_tokens": tok_in,
"output_tokens": tok_out,
"total_cost_usd": tok_in / 1_000_000 * 1.5 + tok_out / 1_000_000 * 3.0,
"primary_model": "google/gemini-2.5-flash",
"fallback_model": "google/gemini-2.5-pro",
}
return {
"unit_schedules": unit_schedules,
"cabinet_line_items": line_items,
"costing": costing,
"config": config,
"metrics": metrics,
"validation": validation,
"outputs": {
"pdf_ready": (out_dir / f"{project_id}_Shop_Drawings.pdf").exists(),
"xlsx_ready": (out_dir / f"{project_id}_Cabinet_Estimation.xlsx").exists(),
},
}
# ─────────────────────────────────────────────────────────────────────────────
# DOWNLOADS
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/api/projects/{project_id}/download/pdf")
async def download_pdf(project_id: str):
p = OUTPUTS_ROOT / project_id / f"{project_id}_Shop_Drawings.pdf"
if not p.exists():
raise HTTPException(404, "PDF not generated yet — run the pipeline.")
return FileResponse(str(p), filename=p.name, media_type="application/pdf")
@app.get("/api/projects/{project_id}/download/excel")
async def download_excel(project_id: str):
p = OUTPUTS_ROOT / project_id / f"{project_id}_Cabinet_Estimation.xlsx"
if not p.exists():
raise HTTPException(404, "Excel not generated yet — run the pipeline.")
return FileResponse(
str(p), filename=p.name,
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
)
# ─────────────────────────────────────────────────────────────────────────────
# CROPS + REGION OVERLAY + PDF THUMBNAIL
# ─────────────────────────────────────────────────────────────────────────────
@app.get("/api/projects/{project_id}/crops/{filename}")
async def serve_crop(project_id: str, filename: str):
p = OUTPUTS_ROOT / project_id / "crops" / filename
if not p.exists():
raise HTTPException(404, f"Crop not found: {filename}")
return FileResponse(str(p), media_type="image/png")
@app.get("/api/projects/{project_id}/regions/{unit_type:path}")
async def get_regions(project_id: str, unit_type: str):
result = _find_project(project_id)
if result is None:
raise HTTPException(404, "Config not found")
config, _, _ = result
unit_type = unit_type.replace("+", " ")
unit_plan_pdfs = config.get("unit_plan_pdfs", {})
if unit_type not in unit_plan_pdfs:
raise HTTPException(404, f"Unit {unit_type!r} not in config")
pdf_path = PROJECT_ROOT / unit_plan_pdfs[unit_type]
if not pdf_path.exists():
raise HTTPException(404, f"PDF not found: {pdf_path.name}")
try:
from core.pdf_extractor import PDFExtractor
from core.region_detector import RegionDetector
with PDFExtractor(pdf_path) as ex:
page = ex.extract_page(0)
regions = RegionDetector(
page.spans, page.rects, page.page_w, page.page_h
).detect()
return {
"page_w": page.page_w,
"page_h": page.page_h,
"regions": [
{
"region_type": r.region_type,
"label": r.label,
"bbox": [r.x0, r.y0, r.x1, r.y1],
"confidence": r.confidence,
}
for r in regions
],
}
except Exception as exc:
raise HTTPException(500, f"Region detection failed: {exc}")
@app.get("/api/projects/{project_id}/pdf-pages/{unit_type:path}")
async def pdf_page_image(project_id: str, unit_type: str):
result = _find_project(project_id)
if result is None:
raise HTTPException(404, "Config not found")
config, _, _ = result
unit_type = unit_type.replace("+", " ")
pdf_path = PROJECT_ROOT / config.get("unit_plan_pdfs", {}).get(unit_type, "")
if not pdf_path.exists():
raise HTTPException(404, f"PDF not found for unit {unit_type!r}")
try:
doc = fitz.open(str(pdf_path))
pix = doc[0].get_pixmap(dpi=120)
img = pix.tobytes("png")
doc.close()
return Response(content=img, media_type="image/png")
except Exception as exc:
raise HTTPException(500, f"Render failed: {exc}")
# ─────────────────────────────────────────────────────────────────────────────
# STATIC FILES — must be mounted last
# ─────────────────────────────────────────────────────────────────────────────
app.mount(
"/",
StaticFiles(directory=str(_HERE / "static"), html=True),
name="static",
)
if __name__ == "__main__":
import uvicorn
uvicorn.run("web_app.app:app", host="127.0.0.1", port=8080, reload=True,
app_dir=str(PROJECT_ROOT))
File diff suppressed because it is too large Load Diff
+477
View File
@@ -0,0 +1,477 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<meta name="description" content="ItalianKB AI-powered cabinet shop drawing generation and estimation system."/>
<title>ItalianKB — Cabinet Estimator & Shop Drawing Automation</title>
<link rel="preconnect" href="https://fonts.googleapis.com"/>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin/>
<link href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@400;500&family=Inter:wght@300;400;500;600&family=Outfit:wght@400;500;600;700;800&display=swap" rel="stylesheet"/>
<link rel="stylesheet" href="style.css"/>
<script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.3/dist/chart.umd.min.js"></script>
</head>
<body>
<div class="glow glow-1" aria-hidden="true"></div>
<div class="glow glow-2" aria-hidden="true"></div>
<div class="glow glow-3" aria-hidden="true"></div>
<!-- ═══════════════════ APP SHELL ═══════════════════ -->
<div class="app-shell">
<!-- ══════ SIDEBAR ══════ -->
<aside class="sidebar" id="sidebar">
<div class="brand">
<div class="brand-logo">📐</div>
<div>
<div class="brand-name">ItalianKB</div>
<div class="brand-sub">Cabinet Automation System</div>
</div>
</div>
<div class="sb-section">
<div class="sb-label">Active Project</div>
<select id="project-select" class="ctrl-input" aria-label="Select project">
<option value="" disabled selected>Loading projects…</option>
</select>
</div>
<div class="sb-section" id="project-info-card" style="display:none">
<div class="info-card glass-dim">
<div class="info-row"><span class="info-k">Client</span><span class="info-v" id="inf-client">—</span></div>
<div class="info-row"><span class="info-k">Address</span><span class="info-v" id="inf-address">—</span></div>
<div class="info-row"><span class="info-k">Finish</span><span class="info-v" id="inf-finish">—</span></div>
<div class="info-row"><span class="info-k">Door Style</span><span class="info-v" id="inf-door">—</span></div>
<div class="info-row"><span class="info-k">Units</span><span class="info-v" id="inf-units">—</span></div>
</div>
</div>
<div class="sb-section sb-grow">
<div class="sb-label">Financial Parameters</div>
<div id="config-form" class="config-fields">
<p class="hint-text">Select a project to configure.</p>
</div>
</div>
<div class="sb-actions">
<button id="new-project-btn" class="btn btn-new-proj">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M19 11H13V5a1 1 0 00-2 0v6H5a1 1 0 000 2h6v6a1 1 0 002 0v-6h6a1 1 0 000-2z"/></svg>
New Project
</button>
<button id="delete-project-btn" class="btn btn-danger-sm" style="display:none" title="Delete this project">
🗑 Delete Project
</button>
</div>
<div class="sb-footer">
<div class="model-badge">
<span class="model-dot"></span>
Gemini 2.5 Flash · OpenRouter
</div>
<div class="version-tag">v2.0.0 Production</div>
</div>
</aside>
<!-- ══════ MAIN ══════ -->
<main class="main" id="main-content">
<!-- Top Header -->
<header class="top-bar">
<div class="top-bar-left">
<h2 class="proj-title" id="display-project-name">Select a Project</h2>
<p class="proj-meta" id="display-project-meta">No project loaded — or create a new one</p>
</div>
<div class="top-bar-right">
<div id="pipeline-status-chip" class="status-chip" style="display:none">
<span class="status-dot" id="status-dot"></span>
<span id="status-text">Ready</span>
</div>
<label class="toggle-row" for="demo-mode-toggle" title="Low-token mode: 150 DPI image + compact prompt. Saves ~85% Vision API cost. Use for demo/testing.">
<span class="toggle-lbl" style="color:hsl(38,92%,55%)">⚡ Demo Mode</span>
<span class="pill-switch">
<input type="checkbox" id="demo-mode-toggle" role="switch" checked/>
<span class="pill-track"><span class="pill-thumb"></span></span>
</span>
</label>
<label class="toggle-row" for="skip-ai-toggle" title="Skip Vision AI entirely — use cached results from previous run">
<span class="toggle-lbl">Skip Vision AI</span>
<span class="pill-switch">
<input type="checkbox" id="skip-ai-toggle" role="switch"/>
<span class="pill-track"><span class="pill-thumb"></span></span>
</span>
</label>
<button id="run-btn" class="btn btn-run" disabled>
<svg width="15" height="15" viewBox="0 0 24 24" fill="currentColor"><path d="M8 5v14l11-7z"/></svg>
Run Pipeline
</button>
</div>
</header>
<div id="readiness-banner" class="readiness-banner glass" style="display:none"></div>
<!-- KPI Cards -->
<section class="kpi-grid" aria-label="Key metrics">
<div class="kpi-card glass">
<div class="kpi-label">Total Selling Price</div>
<div class="kpi-val" id="stat-selling">—</div>
<div class="kpi-sub" id="stat-gp">GP Target: —</div>
</div>
<div class="kpi-card glass">
<div class="kpi-label">Material Cost (USD)</div>
<div class="kpi-val" id="stat-material">—</div>
<div class="kpi-sub" id="stat-rate">EUR/USD: —</div>
</div>
<div class="kpi-card glass">
<div class="kpi-label">Total Cabinets</div>
<div class="kpi-val" id="stat-cabs">—</div>
<div class="kpi-sub" id="stat-ctrs">Containers: —</div>
</div>
<div class="kpi-card glass">
<div class="kpi-label">Vision AI Cost</div>
<div class="kpi-val" id="stat-aicost">—</div>
<div class="kpi-sub" id="stat-aicalls">API Calls: —</div>
</div>
</section>
<!-- Tabs -->
<nav class="tab-nav" role="tablist">
<button class="tab-btn active" data-tab="tab-schedules" role="tab" aria-selected="true">📋 Cabinet Schedules</button>
<button class="tab-btn" data-tab="tab-costing" role="tab" aria-selected="false">💰 Job Costing</button>
<button class="tab-btn" data-tab="tab-dev" role="tab" aria-selected="false">🔧 Developer View</button>
</nav>
<!-- Tab Body -->
<div class="tab-body">
<!-- ─── TAB 1: Schedules ─── -->
<section id="tab-schedules" class="tab-pane active" role="tabpanel">
<div class="pane-header">
<div>
<h3>Cabinet Schedules by Unit Type</h3>
<p class="hint-text">Expand a unit to view the full cabinet list. Hover 🖼️ to preview elevation crops.</p>
</div>
<div class="pane-actions" id="sched-filter-bar" style="display:none">
<input type="search" id="sched-search" class="ctrl-input-sm" placeholder="Filter by cabinet type…" aria-label="Filter cabinets"/>
</div>
</div>
<div id="accordion-container">
<div class="empty-card">
<div class="empty-icon">🗂️</div>
<div class="empty-msg">Select an existing project or create a new one with <strong>+ New Project</strong> to get started.</div>
</div>
</div>
</section>
<!-- ─── TAB 2: Costing ─── -->
<section id="tab-costing" class="tab-pane" role="tabpanel">
<div class="costing-grid">
<div class="costing-sheet glass">
<div class="sheet-hdr">
<h3>Job Costing Breakdown</h3>
<div class="dl-btns">
<a id="dl-pdf" href="#" class="btn btn-dl disabled" target="_blank">📄 Shop Drawings PDF</a>
<a id="dl-xlsx" href="#" class="btn btn-dl disabled" target="_blank">📊 Costing Excel</a>
</div>
</div>
<div class="sheet-scroll">
<table class="cost-table" aria-label="Job costing table">
<thead><tr><th>Line Item</th><th>Rate / Basis</th><th class="num">Amount (USD)</th></tr></thead>
<tbody id="cost-tbody"></tbody>
</table>
</div>
</div>
<div class="costing-right">
<div class="chart-card glass">
<h3>Cost Allocation</h3>
<div class="donut-wrap"><canvas id="donut-chart"></canvas></div>
</div>
<div class="pcab-card glass">
<h3>Per-Cabinet Summary</h3>
<div class="pcab-rows">
<div class="pcab-row"><span>Cost / Cabinet</span><strong id="pc-cost">—</strong></div>
<div class="pcab-row"><span>Sell / Cabinet</span><strong id="pc-sell">—</strong></div>
<div class="pcab-row"><span>Containers Needed</span><strong id="pc-ctrs">—</strong></div>
<div class="pcab-row"><span>Achieved GP %</span><strong id="pc-gp">—</strong></div>
</div>
</div>
</div>
</div>
</section>
<!-- ─── TAB 3: Developer ─── -->
<section id="tab-dev" class="tab-pane" role="tabpanel">
<div class="dev-grid">
<div class="dev-card glass dev-flow">
<h3>System Pipeline Architecture</h3>
<div class="flow-svg-wrap">
<svg viewBox="0 0 820 180" xmlns="http://www.w3.org/2000/svg">
<defs>
<marker id="arr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="6" markerHeight="6" orient="auto">
<path d="M0 1 L10 5 L0 9z" fill="rgba(255,255,255,.22)"/>
</marker>
</defs>
<rect x="4" y="65" width="115" height="50" rx="9" class="fn-node fn-in"/>
<text x="61" y="87" class="fn-label">Upload PDF</text>
<text x="61" y="103" class="fn-sub">PyMuPDF Extract</text>
<line x1="119" y1="90" x2="156" y2="90" class="fn-arr" marker-end="url(#arr)"/>
<rect x="156" y="30" width="115" height="50" rx="9" class="fn-node"/>
<text x="213" y="52" class="fn-label">Region Detect</text>
<text x="213" y="68" class="fn-sub">Elevation Zones</text>
<rect x="156" y="100" width="115" height="50" rx="9" class="fn-node"/>
<text x="213" y="122" class="fn-label">Dim Parser</text>
<text x="213" y="138" class="fn-sub">mm / Inch Dims</text>
<line x1="271" y1="55" x2="308" y2="80" class="fn-arr" marker-end="url(#arr)"/>
<line x1="271" y1="125" x2="308" y2="100" class="fn-arr" marker-end="url(#arr)"/>
<rect x="308" y="60" width="130" height="60" rx="9" class="fn-node fn-ai"/>
<text x="373" y="84" class="fn-label fn-wh">Gemini 2.5 Flash</text>
<text x="373" y="100" class="fn-sub fn-wh">Vision Classifier</text>
<text x="373" y="115" class="fn-sub fn-wh">+Pro fallback</text>
<line x1="438" y1="90" x2="475" y2="90" class="fn-arr" marker-end="url(#arr)"/>
<rect x="475" y="60" width="120" height="60" rx="9" class="fn-node"/>
<text x="535" y="84" class="fn-label">Price Match</text>
<text x="535" y="100" class="fn-sub">Excel→USD</text>
<text x="535" y="116" class="fn-sub">±25mm fuzzy</text>
<line x1="595" y1="90" x2="632" y2="90" class="fn-arr" marker-end="url(#arr)"/>
<rect x="632" y="60" width="120" height="60" rx="9" class="fn-node"/>
<text x="692" y="84" class="fn-label">Job Costing</text>
<text x="692" y="100" class="fn-sub">Selling Price</text>
<text x="692" y="116" class="fn-sub">Algebraic Formula</text>
<line x1="752" y1="90" x2="789" y2="90" class="fn-arr" marker-end="url(#arr)"/>
<rect x="789" y="60" width="25" height="60" rx="6" class="fn-node fn-out"/>
<text x="801" y="91" class="fn-sub fn-wh" style="writing-mode:tb">PDF+XL</text>
</svg>
</div>
<div class="metrics-row">
<div class="met-chip"><span class="met-k">Primary LLM</span><span class="met-v" id="dev-model-prim">—</span></div>
<div class="met-chip"><span class="met-k">Fallback LLM</span><span class="met-v" id="dev-model-fall">—</span></div>
<div class="met-chip"><span class="met-k">Auto-Approve</span><span class="met-v">≥ 90% confidence</span></div>
<div class="met-chip"><span class="met-k">Input tokens</span><span class="met-v" id="dev-tok-in">—</span></div>
<div class="met-chip"><span class="met-k">Output tokens</span><span class="met-v" id="dev-tok-out">—</span></div>
<div class="met-chip"><span class="met-k">API calls</span><span class="met-v" id="dev-api-calls">—</span></div>
</div>
</div>
<div class="dev-card glass dev-overlay">
<div class="dev-card-hdr">
<h3>Region Detector Overlay</h3>
<select id="dev-unit-sel" class="ctrl-input-sm" aria-label="Select unit for overlay">
<option value="" disabled selected>Choose unit…</option>
</select>
</div>
<div id="overlay-container" class="overlay-container">
<p class="hint-text" style="padding:16px">Select a unit to render the PDF with detected zone boundaries.</p>
</div>
</div>
<div class="dev-card glass dev-json">
<div class="dev-card-hdr">
<h3>Raw JSON Output (Cabinet Schedule)</h3>
<div class="json-ctrls">
<button id="json-copy-btn" class="btn btn-xs">📋 Copy</button>
<button id="json-top-btn" class="btn btn-xs">⬆ Top</button>
</div>
</div>
<pre class="json-pre" id="json-viewer"><code>// Run the pipeline to see JSON output here.</code></pre>
</div>
</div>
</section>
</div><!-- /tab-body -->
</main>
</div><!-- /app-shell -->
<!-- ═══════════ CONSOLE ═══════════ -->
<div class="console" id="console-panel">
<div class="console-bar" id="console-bar" role="button" tabindex="0" aria-expanded="false">
<div class="cbar-left">
<span class="dot-ind" id="dot-ind"></span>
<span class="cbar-title">System Execution Logs</span>
</div>
<div class="cbar-right">
<button class="cnsl-btn" id="cnsl-toggle">▲ Expand</button>
<button class="cnsl-btn" id="cnsl-clear">Clear</button>
</div>
</div>
<div class="console-body" id="console-body" aria-live="polite">
<div class="log-line log-sys">[SYSTEM] Ready — select a project or create a new one.</div>
</div>
</div>
<!-- ═══════════ CROP TOOLTIP ═══════════ -->
<div class="crop-tip" id="crop-tip" aria-hidden="true" role="tooltip">
<div class="crop-tip-title">Elevation Crop Preview</div>
<img id="crop-tip-img" src="" alt="Elevation crop"/>
</div>
<!-- ═══════════ TOAST ═══════════ -->
<div class="toast" id="toast" role="alert" aria-live="assertive"></div>
<!-- ═══════════════════════════════════════════════════════════
NEW PROJECT WIZARD MODAL
5 Steps: Info → Upload PDFs → Unit Counts → Price List → Financial
═══════════════════════════════════════════════════════════ -->
<div class="modal-overlay" id="wizard-overlay" aria-modal="true" role="dialog" aria-labelledby="wizard-title" style="display:none">
<div class="modal-box">
<!-- Header -->
<div class="modal-header">
<div>
<h2 id="wizard-title">Create New Project</h2>
<p class="hint-text" id="wizard-subtitle">Step 1 of 5 — Project Information</p>
</div>
<button class="modal-close" id="wizard-close" aria-label="Close wizard">✕</button>
</div>
<!-- Step progress bar -->
<div class="step-bar" role="progressbar" aria-valuenow="1" aria-valuemin="1" aria-valuemax="5">
<div class="step-pip active" data-step="1"><span>1</span><label>Info</label></div>
<div class="step-line"></div>
<div class="step-pip" data-step="2"><span>2</span><label>PDFs</label></div>
<div class="step-line"></div>
<div class="step-pip" data-step="3"><span>3</span><label>Counts</label></div>
<div class="step-line"></div>
<div class="step-pip" data-step="4"><span>4</span><label>Price List</label></div>
<div class="step-line"></div>
<div class="step-pip" data-step="5"><span>5</span><label>Financials</label></div>
</div>
<!-- ── STEP 1: Project Info ── -->
<div class="step-content" id="step-1">
<div class="form-grid">
<div class="fg-group fg-half">
<label for="w-proj-name">Project Name <span class="req">*</span></label>
<input id="w-proj-name" class="ctrl-input" type="text" placeholder="e.g. Casa Familia" maxlength="80"/>
</div>
<div class="fg-group fg-half">
<label for="w-proj-id">Project ID <span class="req">*</span></label>
<input id="w-proj-id" class="ctrl-input" type="text" placeholder="e.g. 24-001" maxlength="20"/>
</div>
<div class="fg-group fg-half">
<label for="w-client">Client / Owner</label>
<input id="w-client" class="ctrl-input" type="text" placeholder="e.g. Atlantic Pacific Communities"/>
</div>
<div class="fg-group fg-half">
<label for="w-architect">Architect</label>
<input id="w-architect" class="ctrl-input" type="text" placeholder="e.g. Corwil Architects"/>
</div>
<div class="fg-group fg-full">
<label for="w-address">Project Address</label>
<input id="w-address" class="ctrl-input" type="text" placeholder="e.g. 10951 SW 84th St., Miami, FL 33173"/>
</div>
<div class="fg-group fg-half">
<label for="w-finish">Cabinet Finish</label>
<input id="w-finish" class="ctrl-input" type="text" placeholder="e.g. K019 SILVER LIBERTY ELM"/>
</div>
<div class="fg-group fg-half">
<label for="w-door">Door Style</label>
<input id="w-door" class="ctrl-input" type="text" placeholder="e.g. Shaker"/>
</div>
<div class="fg-group fg-half">
<label for="w-drawn">Drawn By</label>
<input id="w-drawn" class="ctrl-input" type="text" placeholder="e.g. A.C" value="A.C"/>
</div>
<div class="fg-group fg-half">
<label for="w-rev">Revision</label>
<input id="w-rev" class="ctrl-input" type="text" placeholder="e.g. 1.0" value="1.0"/>
</div>
</div>
</div>
<!-- ── STEP 2: Upload PDFs ── -->
<div class="step-content" id="step-2" style="display:none">
<p class="hint-text" style="margin-bottom:14px">
Upload one architectural PDF per unit type (e.g. A1, A2-ADA, B1). Each file should be the floor plan + elevations page for that unit.
</p>
<!-- Drop zone -->
<div class="dropzone" id="pdf-dropzone" role="button" tabindex="0" aria-label="Drag and drop PDF files here">
<div class="dz-icon">📂</div>
<div class="dz-text">Drag &amp; Drop PDF files here</div>
<div class="dz-sub">or click to browse</div>
<input type="file" id="pdf-file-input" multiple accept=".pdf" style="display:none"/>
</div>
<!-- List of uploaded files + unit name input -->
<div id="pdf-file-list" class="file-list"></div>
<p class="hint-text" style="margin-top:10px">
After dropping files, set the <strong>Unit Type Name</strong> for each (e.g. "A1", "A2-ADA") and check ADA if applicable.
</p>
</div>
<!-- ── STEP 3: Unit Counts ── -->
<div class="step-content" id="step-3" style="display:none">
<p class="hint-text" style="margin-bottom:14px">
Enter how many of each unit type exist in the building. These counts are used to calculate total cabinet quantities.
</p>
<div id="unit-counts-form" class="unit-counts-grid"></div>
</div>
<!-- ── STEP 4: Price List (optional) ── -->
<div class="step-content" id="step-4" style="display:none">
<p class="hint-text" style="margin-bottom:14px">
Upload an ItalianKB price list Excel file. If skipped, the system uses the default Level 1 price catalog.
</p>
<div class="dropzone dropzone-sm" id="xl-dropzone" role="button" tabindex="0" aria-label="Drag and drop price list Excel here">
<div class="dz-icon">📊</div>
<div class="dz-text">Drag &amp; Drop Excel Price List (.xlsx)</div>
<div class="dz-sub">or click to browse — optional</div>
<input type="file" id="xl-file-input" accept=".xlsx,.xls" style="display:none"/>
</div>
<div id="xl-file-info" class="file-badge-row" style="display:none">
<span class="file-badge">📊 <span id="xl-file-name">—</span></span>
<button class="btn btn-xs" id="xl-file-remove">✕ Remove</button>
</div>
<div class="skip-note glass-dim" style="margin-top:16px">
<span class="badge badge-ok">✓ Default</span>
The <strong>ItalianKB Level 1 – 90cm price list</strong> will be used automatically if no file is uploaded.
</div>
</div>
<!-- ── STEP 5: Financial Parameters ── -->
<div class="step-content" id="step-5" style="display:none">
<p class="hint-text" style="margin-bottom:14px">
Set the financial rates for this project. These drive the job costing and selling price formula.
</p>
<div class="form-grid">
<div class="fg-group fg-half">
<label for="w-gp">Target Gross Profit %</label>
<input id="w-gp" class="ctrl-input" type="number" step="0.01" min="0.01" max="0.9" value="0.35"/>
<small class="fg-hint">Typically 35% for multifamily projects</small>
</div>
<div class="fg-group fg-half">
<label for="w-comm">Commission %</label>
<input id="w-comm" class="ctrl-input" type="number" step="0.005" min="0" max="0.5" value="0.05"/>
</div>
<div class="fg-group fg-half">
<label for="w-bond">Performance Bond %</label>
<input id="w-bond" class="ctrl-input" type="number" step="0.005" min="0" max="0.1" value="0.015"/>
</div>
<div class="fg-group fg-half">
<label for="w-rate">EUR / USD Exchange Rate</label>
<input id="w-rate" class="ctrl-input" type="number" step="0.01" min="0.5" max="3.0" value="1.09"/>
</div>
</div>
<!-- Summary -->
<div class="review-box glass-dim" id="wizard-review" style="margin-top:20px"></div>
</div>
<!-- Footer buttons -->
<div class="modal-footer">
<button class="btn btn-ghost" id="wizard-back" style="display:none">← Back</button>
<button class="btn btn-run" id="wizard-next">Next →</button>
<button class="btn btn-run" id="wizard-create" style="display:none">
<svg width="14" height="14" viewBox="0 0 24 24" fill="currentColor"><path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/></svg>
Create &amp; Run Pipeline
</button>
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
+463
View File
@@ -0,0 +1,463 @@
/*
===========================================================================
style.css — ItalianKB Cabinet Estimator (Production v2.0)
===========================================================================
*/
/* ── Design Tokens ── */
:root {
--bg: hsl(230,28%,4%);
--sb-bg: hsl(230,28%,2.5%);
--surface: rgba(255,255,255,.03);
--surface-2: rgba(255,255,255,.06);
--border: rgba(255,255,255,.06);
--border-hi: rgba(255,255,255,.13);
--primary: hsl(258,82%,67%);
--primary-glo: hsla(258,82%,67%,.28);
--primary-dim: hsla(258,82%,67%,.12);
--primary-bdr: hsla(258,82%,67%,.3);
--success: hsl(148,70%,44%);
--success-bg: hsla(148,70%,44%,.1);
--success-bdr: hsla(148,70%,44%,.25);
--warn: hsl(38,92%,55%);
--warn-bg: hsla(38,92%,55%,.1);
--warn-bdr: hsla(38,92%,55%,.25);
--danger: hsl(4,80%,57%);
--danger-bg: hsla(4,80%,57%,.1);
--danger-bdr: hsla(4,80%,57%,.25);
--text: hsl(0,0%,94%);
--text-2: hsl(220,12%,72%);
--text-3: hsl(220,8%,50%);
--font: 'Inter', system-ui, sans-serif;
--font-disp: 'Outfit', system-ui, sans-serif;
--font-mono: 'Fira Code', 'Cascadia Code', monospace;
--sb-w: 296px;
--console-h: 44px;
--console-exp: 220px;
--r: 10px;
--r-lg: 14px;
--t: .18s cubic-bezier(.4,0,.2,1);
}
/* ── Reset ── */
*,*::before,*::after { box-sizing:border-box; margin:0; padding:0; }
html,body { height:100%; overflow:hidden; }
body { font-family:var(--font); background:var(--bg); color:var(--text); font-size:13.5px; line-height:1.55; }
a { color:inherit; text-decoration:none; }
button { cursor:pointer; font-family:var(--font); }
img { display:block; max-width:100%; }
input,select,textarea { font-family:var(--font); }
/* Scrollbars */
::-webkit-scrollbar { width:5px; height:5px; }
::-webkit-scrollbar-track { background:transparent; }
::-webkit-scrollbar-thumb { background:rgba(255,255,255,.1); border-radius:3px; }
::-webkit-scrollbar-thumb:hover { background:rgba(255,255,255,.2); }
/* Glows */
.glow { position:fixed; border-radius:50%; filter:blur(140px); opacity:.12; pointer-events:none; z-index:0; }
.glow-1 { width:550px; height:550px; background:var(--primary); top:-180px; left:-120px; }
.glow-2 { width:700px; height:700px; background:hsl(210,85%,55%); bottom:-220px; right:-180px; }
.glow-3 { width:350px; height:350px; background:hsl(170,70%,45%); top:40%; left:45%; opacity:.06; }
/* ─────────────── LAYOUT ─────────────── */
.app-shell {
position:relative; z-index:1;
display:flex; width:100vw;
height:calc(100vh - var(--console-h));
}
/* ─────────────── SIDEBAR ─────────────── */
.sidebar {
width:var(--sb-w); flex-shrink:0;
background:var(--sb-bg);
border-right:1px solid var(--border);
display:flex; flex-direction:column;
padding:22px 18px;
overflow-y:auto;
}
.brand { display:flex; align-items:center; gap:12px; margin-bottom:26px; }
.brand-logo { font-size:28px; }
.brand-name { font-family:var(--font-disp); font-size:20px; font-weight:700; letter-spacing:-.3px; }
.brand-sub { font-size:9.5px; color:var(--text-3); text-transform:uppercase; letter-spacing:.8px; }
.sb-section { margin-bottom:20px; }
.sb-grow { flex-grow:1; }
.sb-label { font-size:10px; font-weight:600; text-transform:uppercase; letter-spacing:.6px; color:var(--text-3); margin-bottom:8px; }
.info-card { padding:10px 12px; }
.info-row { display:flex; justify-content:space-between; gap:8px; padding:4px 0; border-bottom:1px solid var(--border); }
.info-row:last-child { border:none; }
.info-k { font-size:10px; color:var(--text-3); flex-shrink:0; }
.info-v { font-size:10.5px; color:var(--text-2); text-align:right; word-break:break-word; }
.config-fields { display:flex; flex-direction:column; gap:10px; }
.cf-group label { display:block; font-size:9.5px; color:var(--text-3); text-transform:uppercase; letter-spacing:.5px; margin-bottom:4px; }
.sb-actions { display:flex; flex-direction:column; gap:8px; margin-bottom:16px; }
.btn-new-proj {
background:var(--primary); color:#fff; border:none;
font-size:12px; font-weight:600; padding:9px 14px; border-radius:var(--r);
display:flex; align-items:center; gap:7px;
transition:var(--t);
}
.btn-new-proj:hover { filter:brightness(1.15); box-shadow:0 4px 18px var(--primary-glo); }
.btn-danger-sm {
background:transparent; color:var(--danger); border:1px solid var(--danger-bdr);
font-size:11.5px; padding:7px 12px; border-radius:var(--r);
transition:var(--t);
}
.btn-danger-sm:hover { background:var(--danger-bg); }
.btn-save-cfg {
width:100%; margin-top:6px; padding:9px; border-radius:var(--r);
background:transparent; border:1px solid var(--primary);
color:var(--text); font-size:12px; font-weight:600; transition:var(--t);
}
.btn-save-cfg:hover { background:var(--primary); box-shadow:0 0 16px var(--primary-glo); }
.sb-footer { margin-top:auto; border-top:1px solid var(--border); padding-top:14px; }
.model-badge { display:flex; align-items:center; gap:7px; font-size:10.5px; color:var(--text-3); margin-bottom:4px; }
.model-dot { width:7px; height:7px; border-radius:50%; background:var(--success); box-shadow:0 0 8px var(--success); }
.version-tag { font-size:9.5px; color:var(--text-3); font-family:var(--font-mono); }
/* ─────────────── MAIN ─────────────── */
.main { flex-grow:1; display:flex; flex-direction:column; overflow:hidden; padding:22px 24px 8px; }
/* Top bar */
.top-bar { display:flex; justify-content:space-between; align-items:center; margin-bottom:20px; flex-shrink:0; }
.proj-title { font-family:var(--font-disp); font-size:24px; font-weight:700; letter-spacing:-.4px; }
.proj-meta { font-size:11.5px; color:var(--text-3); margin-top:2px; }
.top-bar-right { display:flex; align-items:center; gap:16px; }
/* Status chip */
.status-chip { display:flex; align-items:center; gap:7px; background:var(--surface-2); border:1px solid var(--border-hi); border-radius:20px; padding:5px 12px; font-size:11px; }
.status-dot { width:7px; height:7px; border-radius:50%; background:var(--text-3); }
.status-dot.running { background:var(--primary); box-shadow:0 0 8px var(--primary); animation:pulse 1.4s infinite; }
.status-dot.done { background:var(--success); box-shadow:0 0 8px var(--success); }
.status-dot.error { background:var(--danger); box-shadow:0 0 8px var(--danger); }
/* Toggle */
.toggle-row { display:flex; align-items:center; gap:9px; cursor:pointer; user-select:none; }
.toggle-lbl { font-size:11.5px; color:var(--text-2); }
.pill-switch { position:relative; display:inline-block; }
.pill-switch input { position:absolute; opacity:0; width:0; height:0; }
.pill-track { display:block; width:40px; height:21px; border-radius:11px; background:rgba(255,255,255,.1); transition:var(--t); position:relative; }
.pill-thumb { position:absolute; top:3px; left:3px; width:15px; height:15px; border-radius:50%; background:#fff; transition:var(--t); }
.pill-switch input:checked ~ .pill-track { background:var(--primary); box-shadow:0 0 10px var(--primary-glo); }
.pill-switch input:checked ~ .pill-track .pill-thumb { transform:translateX(19px); }
/* KPI Cards */
.kpi-grid { display:grid; grid-template-columns:repeat(4,1fr); gap:13px; margin-bottom:18px; flex-shrink:0; }
.kpi-card { padding:14px 17px; border-radius:var(--r-lg); transition:transform var(--t),box-shadow var(--t); }
.kpi-card:hover { transform:translateY(-2px); box-shadow:0 8px 30px rgba(0,0,0,.35); }
.kpi-label { font-size:9.5px; font-weight:600; text-transform:uppercase; letter-spacing:.6px; color:var(--text-3); margin-bottom:6px; }
.kpi-val { font-family:var(--font-disp); font-size:22px; font-weight:700; margin-bottom:3px; }
.kpi-sub { font-size:10.5px; color:var(--text-2); }
/* Tabs */
.tab-nav { display:flex; gap:4px; border-bottom:1px solid var(--border); margin-bottom:16px; flex-shrink:0; }
.tab-btn {
background:transparent; border:none;
padding:9px 18px; font-size:13px; font-weight:500;
color:var(--text-3); border-radius:var(--r) var(--r) 0 0;
position:relative; transition:var(--t); outline:none;
}
.tab-btn:hover { color:var(--text-2); }
.tab-btn.active { color:var(--primary); font-weight:600; }
.tab-btn.active::after { content:''; position:absolute; bottom:-1px; left:0; right:0; height:2px; background:var(--primary); border-radius:2px 2px 0 0; }
.tab-body { flex-grow:1; overflow:hidden; }
.tab-pane { display:none; height:100%; overflow-y:auto; padding-bottom:12px; }
.tab-pane.active { display:block; }
/* Pane header */
.pane-header { display:flex; justify-content:space-between; align-items:flex-start; margin-bottom:16px; gap:16px; }
.pane-header h3 { font-family:var(--font-disp); font-size:17px; font-weight:600; margin-bottom:3px; }
.pane-actions { display:flex; gap:8px; align-items:center; }
/* Empty card */
.empty-card { display:flex; flex-direction:column; align-items:center; justify-content:center; gap:12px; height:220px; border:1px dashed var(--border-hi); border-radius:var(--r-lg); color:var(--text-3); }
.empty-icon { font-size:36px; opacity:.5; }
.empty-msg { font-size:13px; text-align:center; max-width:380px; line-height:1.6; }
/* ─────────────── ACCORDION ─────────────── */
.unit-group { margin-bottom:12px; border-radius:var(--r-lg); overflow:hidden; border:1px solid var(--border); }
.unit-hdr { display:flex; justify-content:space-between; align-items:center; padding:13px 18px; cursor:pointer; user-select:none; transition:background var(--t); }
.unit-hdr:hover { background:rgba(255,255,255,.015); }
.unit-hdr-l { display:flex; align-items:center; gap:10px; }
.unit-hdr-r { display:flex; align-items:center; gap:14px; font-size:11px; color:var(--text-2); }
.unit-name { font-family:var(--font-disp); font-size:15px; font-weight:600; }
.arrow-ico { font-size:10px; color:var(--text-3); transition:transform var(--t); }
.unit-group.open .arrow-ico { transform:rotate(180deg); }
.unit-body { display:none; padding:0 18px 16px; background:rgba(0,0,0,.12); border-top:1px solid var(--border); }
.unit-group.open .unit-body { display:block; }
.badge { font-size:9px; font-weight:700; padding:2px 8px; border-radius:20px; text-transform:uppercase; letter-spacing:.4px; }
.badge-ok { background:var(--success-bg); color:var(--success); border:1px solid var(--success-bdr); }
.badge-warn{ background:var(--warn-bg); color:var(--warn); border:1px solid var(--warn-bdr); }
.badge-ada { background:var(--primary-dim); color:var(--primary); border:1px solid var(--primary-bdr); }
.flag-box { background:var(--warn-bg); border:1px solid var(--warn-bdr); border-radius:var(--r); padding:10px 14px; margin:14px 0; }
.flag-box-title { color:var(--warn); font-size:10.5px; font-weight:700; text-transform:uppercase; margin-bottom:5px; }
.flag-list { list-style:none; font-size:11.5px; color:var(--text-2); display:flex; flex-direction:column; gap:3px; }
.flag-list li::before { content:'⚠ '; }
.elev-section { margin-top:16px; }
.elev-title-bar { display:flex; justify-content:space-between; align-items:center; padding-bottom:6px; border-bottom:1px solid var(--border); margin-bottom:10px; }
.elev-title-bar h4 { font-family:var(--font-disp); font-size:13px; font-weight:600; color:var(--text-2); }
.elev-meta { font-size:11px; color:var(--text-3); display:flex; gap:14px; }
.sched-table { width:100%; border-collapse:collapse; font-size:11.5px; }
.sched-table th { font-size:9px; font-weight:600; text-transform:uppercase; letter-spacing:.5px; color:var(--text-3); padding:7px 10px; text-align:left; border-bottom:1px solid var(--border); }
.sched-table td { padding:7px 10px; border-bottom:1px solid var(--border); vertical-align:middle; }
.sched-table tr:last-child td { border:none; }
.sched-table tr:hover td { background:rgba(255,255,255,.012); }
.mono { font-family:var(--font-mono); font-size:11px; }
.num { text-align:right !important; }
.conf-bar { display:inline-flex; align-items:center; gap:6px; }
.conf-pct { font-size:10px; }
.conf-pip { width:34px; height:4px; border-radius:2px; background:rgba(255,255,255,.08); overflow:hidden; }
.conf-fill { height:100%; border-radius:2px; }
.crop-btn { background:transparent; border:1px solid var(--border); border-radius:5px; padding:3px 7px; font-size:12px; color:var(--text-2); transition:var(--t); }
.crop-btn:hover { background:var(--surface-2); border-color:var(--border-hi); }
/* ─────────────── COSTING ─────────────── */
.costing-grid { display:grid; grid-template-columns:3fr 1.6fr; gap:16px; height:100%; }
.costing-sheet { display:flex; flex-direction:column; padding:18px 20px; overflow:hidden; }
.sheet-hdr { display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; flex-shrink:0; }
.sheet-hdr h3 { font-family:var(--font-disp); font-size:16px; font-weight:600; }
.dl-btns { display:flex; gap:8px; }
.sheet-scroll { flex-grow:1; overflow-y:auto; }
.cost-table { width:100%; border-collapse:collapse; font-size:12.5px; }
.cost-table th { font-size:9.5px; text-transform:uppercase; color:var(--text-3); font-weight:600; padding:8px 10px; border-bottom:1px solid var(--border-hi); }
.cost-table td { padding:9px 10px; border-bottom:1px solid var(--border); color:var(--text-2); }
.cost-table tr.subtotal-row td { border-top:1px solid var(--border-hi); font-weight:600; color:var(--text); font-size:13px; }
.cost-table tr.total-row td { border-top:2px solid var(--primary); font-weight:700; font-size:14px; color:var(--text); }
.costing-right { display:flex; flex-direction:column; gap:14px; }
.chart-card,.pcab-card { padding:16px 18px; }
.chart-card h3,.pcab-card h3 { font-family:var(--font-disp); font-size:14px; font-weight:600; margin-bottom:14px; }
.donut-wrap { height:195px; position:relative; }
.pcab-rows { display:flex; flex-direction:column; gap:8px; }
.pcab-row { display:flex; justify-content:space-between; align-items:center; padding:7px 0; border-bottom:1px solid var(--border); font-size:12px; }
.pcab-row:last-child { border:none; }
.pcab-row span { color:var(--text-3); }
.pcab-row strong { font-family:var(--font-mono); font-size:12px; }
/* ─────────────── DEVELOPER ─────────────── */
.dev-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
.dev-card { padding:18px 20px; border-radius:var(--r-lg); }
.dev-flow,.dev-json { grid-column:1/3; }
.dev-card-hdr { display:flex; justify-content:space-between; align-items:center; margin-bottom:14px; }
.dev-card-hdr h3 { font-family:var(--font-disp); font-size:14px; font-weight:600; }
.flow-svg-wrap { border:1px solid var(--border); border-radius:var(--r); background:rgba(0,0,0,.2); padding:14px; margin-bottom:14px; }
.fn-node { fill:rgba(255,255,255,.04); stroke:var(--border-hi); stroke-width:1.5; }
.fn-in { fill:rgba(99,72,219,.12); stroke:var(--primary); }
.fn-ai { fill:var(--primary); stroke:var(--primary-glo); }
.fn-out { fill:rgba(54,180,114,.25); stroke:var(--success); }
.fn-arr { stroke:rgba(255,255,255,.18); stroke-width:1.5; fill:none; }
.fn-label { fill:var(--text-2); font-family:Inter,sans-serif; font-size:11.5px; font-weight:600; text-anchor:middle; }
.fn-sub { fill:var(--text-3); font-family:Inter,sans-serif; font-size:9px; text-anchor:middle; }
.fn-wh { fill:#fff !important; }
.metrics-row { display:flex; flex-wrap:wrap; gap:8px; }
.met-chip { background:rgba(255,255,255,.03); border:1px solid var(--border); border-radius:6px; padding:7px 11px; display:flex; flex-direction:column; min-width:110px; }
.met-k { font-size:9px; text-transform:uppercase; color:var(--text-3); margin-bottom:3px; }
.met-v { font-family:var(--font-mono); font-size:11px; font-weight:500; }
.dev-overlay { display:flex; flex-direction:column; }
.overlay-container { flex-grow:1; background:rgba(0,0,0,.3); border:1px solid var(--border); border-radius:var(--r); position:relative; overflow:hidden; min-height:220px; }
.zone-box { position:absolute; box-sizing:border-box; border:2px solid var(--primary); background:var(--primary-dim); border-radius:3px; cursor:pointer; transition:var(--t); }
.zone-box:hover { background:rgba(99,72,219,.3); }
.zone-tag { position:absolute; top:-17px; left:-2px; background:var(--primary); color:#fff; font-size:8px; font-family:var(--font-mono); padding:1px 5px; border-radius:3px; white-space:nowrap; }
.json-pre { background:rgba(0,0,0,.3); border:1px solid var(--border); border-radius:var(--r); padding:14px 16px; max-height:280px; overflow-y:auto; }
.json-pre code { font-family:var(--font-mono); font-size:11px; color:hsl(155,70%,70%); white-space:pre-wrap; }
.json-ctrls { display:flex; gap:6px; }
/* ─────────────── CONSOLE ─────────────── */
.console { position:fixed; bottom:0; left:0; right:0; height:var(--console-h); background:hsl(232,25%,2%); border-top:1px solid var(--border); transition:height var(--t); z-index:100; display:flex; flex-direction:column; }
.console.expanded { height:var(--console-exp); }
.console-bar { height:var(--console-h); flex-shrink:0; display:flex; justify-content:space-between; align-items:center; padding:0 20px; cursor:pointer; }
.cbar-left { display:flex; align-items:center; gap:10px; }
.cbar-title { font-size:11px; font-weight:600; text-transform:uppercase; letter-spacing:.5px; color:var(--text-2); }
.cbar-right { display:flex; gap:6px; }
.cnsl-btn { background:rgba(255,255,255,.05); border:1px solid var(--border); border-radius:5px; color:var(--text-3); font-size:10px; padding:3px 9px; transition:var(--t); }
.cnsl-btn:hover { background:rgba(255,255,255,.1); color:var(--text); }
.console-body { flex-grow:1; overflow-y:auto; padding:10px 20px; }
.dot-ind { width:7px; height:7px; border-radius:50%; background:var(--text-3); flex-shrink:0; transition:var(--t); }
.dot-ind.active { background:var(--primary); box-shadow:0 0 8px var(--primary); animation:pulse 1.4s infinite; }
.dot-ind.success { background:var(--success); box-shadow:0 0 8px var(--success); }
.dot-ind.error { background:var(--danger); box-shadow:0 0 8px var(--danger); }
@keyframes pulse { 0%,100%{opacity:.6;transform:scale(.9)} 50%{opacity:1;transform:scale(1.15)} }
.log-line { font-family:var(--font-mono); font-size:11px; line-height:1.65; }
.log-sys { color:var(--primary); }
.log-ok { color:var(--success); }
.log-err { color:var(--danger); }
.log-warn { color:var(--warn); }
/* ─────────────── CROP TOOLTIP ─────────────── */
.crop-tip { position:fixed; display:none; background:hsl(232,25%,3%); border:1px solid var(--border-hi); border-radius:var(--r); padding:10px; box-shadow:0 10px 40px rgba(0,0,0,.7); z-index:999; width:290px; pointer-events:none; }
.crop-tip-title { font-size:9px; text-transform:uppercase; letter-spacing:.5px; color:var(--text-3); margin-bottom:7px; }
.crop-tip img { width:100%; border-radius:5px; border:1px solid var(--border); }
/* ─────────────── TOAST ─────────────── */
.toast { position:fixed; bottom:calc(var(--console-h)+16px); left:50%; transform:translateX(-50%) translateY(12px); background:hsl(232,22%,12%); border:1px solid var(--border-hi); border-radius:var(--r); padding:10px 18px; font-size:12.5px; box-shadow:0 8px 30px rgba(0,0,0,.5); opacity:0; pointer-events:none; transition:opacity .25s,transform .25s; z-index:200; }
.toast.show { opacity:1; transform:translateX(-50%) translateY(0); }
/* ─────────────── SHARED ─────────────── */
.glass { background:var(--surface); backdrop-filter:blur(14px) saturate(1.3); -webkit-backdrop-filter:blur(14px) saturate(1.3); border:1px solid var(--border); border-radius:var(--r-lg); }
.glass-dim { background:rgba(255,255,255,.025); border:1px solid var(--border); border-radius:var(--r); }
.ctrl-input { width:100%; background:rgba(255,255,255,.03); border:1px solid var(--border); border-radius:var(--r); color:var(--text); padding:8px 12px; font-family:var(--font); font-size:12.5px; outline:none; transition:border-color var(--t),box-shadow var(--t); appearance:none; }
.ctrl-input:focus { border-color:var(--primary); box-shadow:0 0 0 3px var(--primary-glo); }
select.ctrl-input { background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='rgba(255,255,255,.35)'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'/%3E%3C/svg%3E"); background-repeat:no-repeat; background-position:right 10px center; background-size:15px; padding-right:34px; cursor:pointer; }
.ctrl-input-sm { background:rgba(255,255,255,.03); border:1px solid var(--border); border-radius:7px; color:var(--text); padding:5px 10px; font-size:11.5px; outline:none; transition:border-color var(--t); appearance:none; }
.ctrl-input-sm:focus { border-color:var(--primary); }
select.ctrl-input-sm { background-image:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 24 24' stroke='rgba(255,255,255,.35)'%3E%3Cpath stroke-linecap='round' stroke-linejoin='round' stroke-width='2' d='M19 9l-7 7-7-7'/%3E%3C/svg%3E"); background-repeat:no-repeat; background-position:right 8px center; background-size:13px; padding-right:28px; cursor:pointer; }
.hint-text { font-size:11.5px; color:var(--text-3); }
.btn { display:inline-flex; align-items:center; gap:7px; padding:9px 16px; border-radius:var(--r); font-size:12.5px; font-weight:600; border:none; transition:var(--t); outline:none; }
.btn-run { background:var(--primary); color:#fff; }
.btn-run:not(:disabled):hover { filter:brightness(1.15); box-shadow:0 4px 18px var(--primary-glo); transform:translateY(-1px); }
.btn-run:disabled { opacity:.35; cursor:not-allowed; }
.btn-ghost { background:transparent; color:var(--text-2); border:1px solid var(--border); }
.btn-ghost:hover { border-color:var(--border-hi); color:var(--text); }
.btn-dl { background:transparent; border:1px solid var(--border); color:var(--text-2); font-size:11.5px; padding:7px 12px; }
.btn-dl:not(.disabled):hover { background:var(--surface-2); border-color:var(--border-hi); color:var(--text); }
.btn-dl.disabled { opacity:.3; pointer-events:none; }
.btn-xs { background:rgba(255,255,255,.05); border:1px solid var(--border); color:var(--text-3); font-size:10.5px; padding:4px 10px; border-radius:6px; }
.btn-xs:hover { background:rgba(255,255,255,.09); color:var(--text); }
.spinner { display:inline-block; width:16px; height:16px; border:2px solid rgba(255,255,255,.15); border-top-color:currentColor; border-radius:50%; animation:spin .7s linear infinite; flex-shrink:0; }
@keyframes spin { to{transform:rotate(360deg)} }
.loading-msg { display:flex; align-items:center; gap:10px; color:var(--text-3); font-size:12px; padding:16px; }
.readiness-banner {
margin:0 0 14px;
padding:11px 14px;
display:flex;
align-items:flex-start;
justify-content:space-between;
gap:14px;
border-radius:var(--r);
}
.readiness-banner.ok { border-color:var(--success-bdr); background:var(--success-bg); }
.readiness-banner.warn { border-color:var(--warn-bdr); background:var(--warn-bg); }
.readiness-banner.err { border-color:var(--danger-bdr); background:var(--danger-bg); }
.ready-title { font-size:12px; font-weight:700; color:var(--text); margin-bottom:4px; }
.ready-detail { font-size:11px; color:var(--text-2); line-height:1.45; }
.ready-pills { display:flex; flex-wrap:wrap; gap:6px; justify-content:flex-end; min-width:220px; }
.ready-pill { border:1px solid var(--border); background:rgba(0,0,0,.15); border-radius:999px; padding:4px 8px; font-size:10px; color:var(--text-2); white-space:nowrap; }
.ready-pill.ok { border-color:var(--success-bdr); color:var(--success); }
.ready-pill.warn { border-color:var(--warn-bdr); color:var(--warn); }
.ready-pill.err { border-color:var(--danger-bdr); color:var(--danger); }
/* ─────────────── WIZARD MODAL ─────────────── */
.modal-overlay {
position:fixed; inset:0; background:rgba(0,0,0,.75); backdrop-filter:blur(8px);
z-index:500; display:flex; align-items:center; justify-content:center;
animation:fadein .2s ease;
}
@keyframes fadein { from{opacity:0} to{opacity:1} }
.modal-box {
background:hsl(230,25%,7%); border:1px solid var(--border-hi);
border-radius:18px; width:720px; max-width:96vw; max-height:92vh;
display:flex; flex-direction:column; overflow:hidden;
box-shadow:0 30px 80px rgba(0,0,0,.8);
animation:slideup .25s cubic-bezier(.4,0,.2,1);
}
@keyframes slideup { from{transform:translateY(20px);opacity:0} to{transform:none;opacity:1} }
.modal-header { display:flex; justify-content:space-between; align-items:flex-start; padding:24px 28px 0; }
.modal-header h2 { font-family:var(--font-disp); font-size:22px; font-weight:700; }
.modal-close { background:transparent; border:1px solid var(--border); border-radius:6px; color:var(--text-3); width:28px; height:28px; display:flex; align-items:center; justify-content:center; font-size:13px; transition:var(--t); flex-shrink:0; }
.modal-close:hover { background:rgba(255,255,255,.07); color:var(--text); }
/* Step bar */
.step-bar { display:flex; align-items:center; padding:20px 28px 0; }
.step-pip { display:flex; flex-direction:column; align-items:center; gap:4px; position:relative; flex-shrink:0; }
.step-pip span { width:28px; height:28px; border-radius:50%; background:rgba(255,255,255,.06); border:1.5px solid var(--border-hi); display:flex; align-items:center; justify-content:center; font-size:12px; font-weight:600; color:var(--text-3); transition:var(--t); }
.step-pip label { font-size:9px; text-transform:uppercase; letter-spacing:.5px; color:var(--text-3); transition:var(--t); }
.step-pip.active span { background:var(--primary); border-color:var(--primary); color:#fff; box-shadow:0 0 12px var(--primary-glo); }
.step-pip.active label { color:var(--primary); }
.step-pip.done span { background:var(--success); border-color:var(--success); color:#fff; }
.step-pip.done label { color:var(--success); }
.step-line { flex-grow:1; height:1.5px; background:var(--border-hi); margin:0 8px; margin-bottom:18px; }
.step-content { flex-grow:1; overflow-y:auto; padding:20px 28px; }
/* Form grid inside wizard */
.form-grid { display:grid; grid-template-columns:1fr 1fr; gap:14px; }
.fg-group { display:flex; flex-direction:column; }
.fg-half { grid-column:span 1; }
.fg-full { grid-column:span 2; }
.fg-group label { font-size:10px; font-weight:600; text-transform:uppercase; letter-spacing:.5px; color:var(--text-3); margin-bottom:5px; }
.fg-group .req { color:var(--danger); }
.fg-hint { font-size:10px; color:var(--text-3); margin-top:4px; }
/* Dropzone */
.dropzone {
border:2px dashed var(--border-hi); border-radius:var(--r-lg);
display:flex; flex-direction:column; align-items:center; justify-content:center;
gap:8px; padding:32px 24px; cursor:pointer; transition:var(--t);
text-align:center;
}
.dropzone:hover, .dropzone.drag-over { border-color:var(--primary); background:var(--primary-dim); }
.dropzone-sm { padding:20px 24px; }
.dz-icon { font-size:32px; opacity:.7; }
.dz-text { font-size:14px; font-weight:500; color:var(--text-2); }
.dz-sub { font-size:11.5px; color:var(--text-3); }
/* File list */
.file-list { display:flex; flex-direction:column; gap:8px; margin-top:14px; }
.file-row {
background:rgba(255,255,255,.03); border:1px solid var(--border);
border-radius:var(--r); padding:10px 14px;
display:grid; grid-template-columns:auto 1fr auto auto auto;
align-items:center; gap:10px;
}
.file-row-icon { font-size:18px; }
.file-row-name { font-size:12px; font-weight:500; truncate:true; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
.file-row-size { font-size:10px; color:var(--text-3); white-space:nowrap; }
.file-row-ada { display:flex; align-items:center; gap:5px; font-size:10.5px; color:var(--text-3); white-space:nowrap; }
.file-row-ada input { cursor:pointer; }
.file-row-unit { min-width:100px; }
.file-row-del { background:transparent; border:1px solid var(--danger-bdr); color:var(--danger); border-radius:5px; padding:2px 7px; font-size:10.5px; transition:var(--t); flex-shrink:0; }
.file-row-del:hover { background:var(--danger-bg); }
.file-badge-row { display:flex; align-items:center; gap:10px; margin-top:12px; }
.file-badge { background:var(--success-bg); border:1px solid var(--success-bdr); color:var(--success); padding:5px 12px; border-radius:20px; font-size:11.5px; }
/* Unit counts grid in step 3 */
.unit-counts-grid { display:grid; grid-template-columns:repeat(auto-fill, minmax(200px,1fr)); gap:12px; }
.uc-group { background:rgba(255,255,255,.03); border:1px solid var(--border); border-radius:var(--r); padding:12px 14px; }
.uc-label { font-size:11px; font-weight:600; color:var(--text-2); margin-bottom:8px; display:flex; align-items:center; gap:6px; }
.uc-input { width:100%; }
/* Skip note */
.skip-note { padding:12px 14px; display:flex; align-items:center; gap:10px; font-size:12px; color:var(--text-2); }
/* Review box */
.review-box { padding:14px 16px; }
.review-box h4 { font-family:var(--font-disp); font-size:14px; font-weight:600; margin-bottom:10px; }
.review-row { display:flex; justify-content:space-between; padding:5px 0; border-bottom:1px solid var(--border); font-size:12px; }
.review-row:last-child { border:none; }
.review-row span:first-child { color:var(--text-3); }
.review-row strong { font-weight:500; }
.modal-footer { display:flex; justify-content:flex-end; align-items:center; gap:10px; padding:16px 28px; border-top:1px solid var(--border); flex-shrink:0; }