import os
import sys
import time
import pandas as pd
import streamlit as st
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from core import metrics as plan_metrics
from core.constants import VASTU_RULES
try:
from core.constants import ROOM_COLORS as _ROOM_COLORS
except Exception:
_ROOM_COLORS = {}
from core.generator import FloorPlan, Room, _score_one, generate_population, rank_plans
from core.visualizer import draw_comparison, fig_to_bytes
from core import pdf_templates
from core import pdf_templates_2bhk
from core import pdf_templates_3bhk
from core import pdf_templates_4bhk
from core.render_plan import fig_comparison, fig_floorplan
from floorplan_editor import floor_plan_editor
APP_LAYOUT_VERSION = "2026-06-25-drag-editor-v1"
st.set_page_config(
page_title="Architectural Floor Plan Generation System",
page_icon="๐ ",
layout="wide",
initial_sidebar_state="expanded",
)
if st.session_state.get("app_layout_version") != APP_LAYOUT_VERSION:
st.session_state.pop("last_top_plans", None)
st.session_state.pop("last_road_side", None)
st.session_state["app_layout_version"] = APP_LAYOUT_VERSION
st.markdown(
"""
""",
unsafe_allow_html=True,
)
def pretty_room(name: str) -> str:
return (
name.replace("_", " ")
.replace("01", "1")
.replace("02", "2")
.replace("03", "3")
.title()
)
def render_side_scores(raw_fp, opt_fp, road_side, selected_vastu=None):
"""Compact scorecard for the column beside the plans. Rendered as small HTML
rows rather than st.metric tiles so that EVERY metric โ fitness down to
functional zoning โ fits within the height of the plan next to it."""
cr = plan_metrics.evaluate(raw_fp, road_side, selected_vastu)
co = plan_metrics.evaluate(opt_fp, road_side, selected_vastu)
def row(lab, val, dv, big=False):
col = "#1B7F3B" if dv > 0.05 else ("#C0392B" if dv < -0.05 else "#5A6B80")
sz = "15px" if big else "13px"
wt = "700" if big else "500"
return (
f'
'
f'{lab}'
f''
f'{val * 100:.0f}%{dv * 100:+.0f}
')
html = ['',
'
'
'Score
',
row("Fitness", co.fitness, co.fitness - cr.fitness, big=True)]
for key, lab in plan_metrics.METRIC_LABELS:
html.append(row(lab, co.scores[key],
co.scores[key] - cr.scores[key]))
html.append('
'
'green/red = change vs the AI-generated plan
')
st.markdown("".join(html), unsafe_allow_html=True)
def render_side_legend(fp):
"""Room-colour key for the sidebar. Set in readable type with generous rows
so it fills the column properly rather than sitting as a cramped block with
dead space beneath it."""
seen, html = set(), []
for r in fp.rooms:
if r.name in seen:
continue
seen.add(r.name)
col = _ROOM_COLORS.get(r.name, "#607D8B")
html.append(
''
f''
f'{pretty_room(r.name)}
')
st.markdown(
'Rooms
'
+ "".join(html), unsafe_allow_html=True)
def plan_thumbnail(fp, road_side):
"""A small cached PNG of one plan for the gallery. Cached by the plan's
geometry so clicking a tile (which reruns the whole page) does not
re-render all twenty every time."""
sig = (road_side, tuple((r.name, round(r.x, 1), round(r.y, 1),
round(r.w, 1), round(r.h, 1)) for r in fp.rooms))
cache = st.session_state.setdefault("_thumb_cache", {})
key = hash(sig)
if key in cache:
return cache[key]
import matplotlib.pyplot as _plt
from core.render_plan import draw_plan
fig, ax = _plt.subplots(figsize=(2.7, 3.4))
# A gallery tile is a PREVIEW: room names only, at roughly half the normal
# text size. Full-size labels on a tile this small came out bigger than the
# rooms they sat in, and the dimensions are unreadable at this scale anyway
# โ the plan opens at full size on click.
draw_plan(ax, fp, fp.plot_w, fp.plot_h, road_side, "",
show_dims=False, text_scale=0.55)
fig.tight_layout(pad=0.15)
png = fig_to_bytes(fig).getvalue()
_plt.close(fig)
cache[key] = png
return png
def enforce_bhk_rooms(plan_type: str, required_rooms, optional_rooms):
required = list(dict.fromkeys(required_rooms))
optional = list(dict.fromkeys(optional_rooms))
def require(room):
if room not in required:
required.append(room)
if room in optional:
optional.remove(room)
def remove(room):
if room in required:
required.remove(room)
if room in optional:
optional.remove(room)
bedroom_counts = {"1BHK": 0, "2BHK": 1, "3BHK": 2, "4BHK": 3}
for room in ("bedroom_01", "bedroom_02", "bedroom_03"):
remove(room)
for room in ("bedroom_01", "bedroom_02", "bedroom_03")[:bedroom_counts[plan_type]]:
require(room)
require("common_bathroom")
if plan_type == "1BHK":
remove("attached_bathroom")
remove("attached_bathroom_02")
elif plan_type == "2BHK":
remove("attached_bathroom_02")
elif plan_type == "3BHK":
require("attached_bathroom")
remove("attached_bathroom_02")
else:
require("attached_bathroom")
require("attached_bathroom_02")
return required, optional
def metric_row(raw_fp, opt_fp, road_side="S", selected_vastu=None):
"""One row of headline numbers โ ALL from the finalised scoring system, so
every panel on the page agrees (no more one Vastu here, another there)."""
cr = plan_metrics.evaluate(raw_fp, road_side, selected_vastu)
co = plan_metrics.evaluate(opt_fp, road_side, selected_vastu)
def cell(col, label, key, is_fit=False):
rv = cr.fitness if is_fit else cr.scores[key]
ov = co.fitness if is_fit else co.scores[key]
col.metric(label, f"{ov * 100:.1f}%", f"{(ov - rv) * 100:+.1f}%")
cols = st.columns(6)
cols[0].metric("Layout Proposer Fitness", f"{cr.fitness * 100:.1f}%")
cell(cols[1], "Domain Expert Fitness", None, is_fit=True)
cell(cols[2], "Vastu", "vastu")
cell(cols[3], "Adjacency", "adjacency")
cell(cols[4], "Constraints", "constraints")
cell(cols[5], "Space Utilization", "space_utilization")
def room_presence_line(fp):
counts = {}
for room in fp.rooms:
counts[room.name] = counts.get(room.name, 0) + 1
parts = [
f"Master: {counts.get('master_bedroom', 0)}",
f"Bedroom: {counts.get('bedroom_01', 0) + counts.get('bedroom_02', 0) + counts.get('bedroom_03', 0)}",
f"Study: {counts.get('study', 0)}",
f"Dining: {counts.get('dining_room', 0)}",
f"Utility: {counts.get('utility_area', 0)}",
]
return " | ".join(parts)
def score_table(fp):
score = fp.scores
return pd.DataFrame(
{
"Metric": ["Fitness", "Vastu", "Adjacency", "Cost",
"Space Usage", "Area Compliance", "Layout Compactness"],
"Score": [
f"{score['Fitness']:.3f}",
f"{score['VS'] * 100:.0f}%",
f"{score['AQ'] * 100:.0f}%",
f"{score['CS'] * 100:.0f}%",
f"{score['SU'] * 100:.0f}%",
f"{score['AC'] * 100:.0f}%",
f"{score['LC'] * 100:.0f}%",
],
}
)
def score_formula_table(fp):
score = fp.scores
failed = score.get("hard_failed", 0)
return pd.DataFrame(
{
"UI metric": [
"Fitness",
"Vastu",
"Adjacency",
"Cost",
"Space Usage",
"Area Compliance",
"Layout Compactness",
],
"Calculation used": [
"30% VS + 25% AQ + 15% CS + 15% SU + 10% AC + 5% LC - hard-constraint penalty",
"matched Vastu rule weight / total applicable Vastu rule weight x 100",
"earned adjacency weight / required adjacency weight, minus forbidden/avoid penalties x 100",
"1.0 when estimated cost/sqft <= 1.05 x base rate; 0.0 when >= 1.40 x base rate; linear between x 100",
"occupied buildable-area grid cells / total inner setback area x 100",
"average room-size compliance against min/max guide table x 100",
"0.4 x bounding-box compactness + 0.6 x room fill inside bounding box x 100",
],
"Current value": [
f"{score['Fitness']:.3f} ({failed} hard checks failed)",
f"{score['VS'] * 100:.0f}%",
f"{score['AQ'] * 100:.0f}%",
f"{score['CS'] * 100:.0f}%",
f"{score['SU'] * 100:.0f}%",
f"{score['AC'] * 100:.0f}%",
f"{score['LC'] * 100:.0f}%",
],
}
)
def _pct(v):
return f"{v * 100:.1f}%"
def fig_connectivity_graph(nodes, edges, blocked_edges=()):
"""The plan's access graph. Each room is a small dot at its centroid with
its name beside it (never inside โ the text is unreadable in a dot). A SOLID
line is a legal doorway you may walk through; a DOTTED line is a pair of
rooms that physically touch but may not be used as a route (e.g. two
bedrooms), which is what usually explains a stranded room."""
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(3.6, 3.1), dpi=110)
for i, j in blocked_edges:
ax.plot([nodes[i][1], nodes[j][1]], [nodes[i][2], nodes[j][2]],
":", color="#E53935", lw=1.0, alpha=0.75, zorder=1)
for i, j in edges:
ax.plot([nodes[i][1], nodes[j][1]], [nodes[i][2], nodes[j][2]],
"-", color="#8899A6", lw=1.2, zorder=2)
short = {"external_staircase": "Staircase", "internal_corridor": "Passage",
"attached_bathroom": "Att. Bath", "attached_bathroom_02": "Att. Bath 2",
"common_bathroom": "Common Bath", "master_bedroom": "Master",
"utility_area": "Utility", "living_room": "Living",
"dining_room": "Dining", "pooja_room": "Pooja",
"bedroom_01": "Bed 1", "bedroom_02": "Bed 2", "bedroom_03": "Bed 3",
"walk_in_closet": "Closet"}
# Labels sit off the dot and are joined to it by a thin leader, so which
# name belongs to which dot is never in doubt even when rooms sit close.
spots = [(13, 9), (-13, 9), (13, -11), (-13, -11)]
for k, (name, cx, cy, reach, is_entry, _hop) in enumerate(nodes):
color = "#2E7D32" if is_entry else ("#1E88E5" if reach else "#E53935")
ax.scatter([cx], [cy], s=46, color=color, edgecolor="white",
linewidth=1.0, zorder=4)
dx, dy = spots[k % len(spots)]
ax.annotate(short.get(name, pretty_room(name)), (cx, cy),
textcoords="offset points", xytext=(dx, dy),
ha="left" if dx > 0 else "right", va="center",
fontsize=6, color="#111111", zorder=5,
bbox=dict(fc="white", ec=color, lw=0.5,
boxstyle="round,pad=0.22", alpha=0.95),
arrowprops=dict(arrowstyle="-", color=color, lw=0.7,
shrinkA=0, shrinkB=2))
ax.set_aspect("equal")
ax.axis("off")
ax.margins(0.18)
ax.set_title("Access graph โ green entry ยท blue reachable ยท red isolated\n"
"solid = usable doorway ยท dotted = touching but not a route",
fontsize=6)
fig.tight_layout()
return fig
def render_edit_comparison(orig_fp, edited_fp, road_side, selected_vastu=None):
"""Score the plan the user edited in the room editor with the SAME finalised
system and compare it, metric by metric, to the original optimised plan.
(Walls and doors are visual only and do not change the score; moving,
resizing or deleting rooms does.)"""
before = plan_metrics.evaluate(orig_fp, road_side, selected_vastu)
after = plan_metrics.evaluate(edited_fp, road_side, selected_vastu)
delta = (after.fitness - before.fitness) * 100
verdict = ("improved" if delta > 0.05
else "lowered" if delta < -0.05 else "kept")
st.markdown('',
unsafe_allow_html=True)
# Scores only โ the weighting break-up follows underneath.
rows = [{"Metric": label,
"Domain Expert Engine": _pct(before.scores[key]),
"Your Edit": _pct(after.scores[key]),
"ฮ": f"{(after.scores[key] - before.scores[key]) * 100:+.1f}"}
for key, label in plan_metrics.METRIC_LABELS]
rows.append({"Metric": "FLOOR PLAN FITNESS",
"Domain Expert Engine": _pct(before.fitness),
"Your Edit": _pct(after.fitness),
"ฮ": f"{delta:+.1f}"})
st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")
st.caption(
f"Your edits **{verdict}** the fitness by **{delta:+.1f} points**. "
"Walls and doors are visual only โ moving, resizing or deleting rooms "
"is what changes the score. The full per-metric working is below.")
# The full per-metric break-up, recomputed on the EDITED plan: which Vastu
# tier each room now reaches, which adjacency pairs survived, which
# constraints still hold, plus the weighted fold under the Fitness tab.
#
# OPEN BY DEFAULT, unlike the generated plan's copy above. A flat
# weight/score/contribution table used to sit here, but it was the
# Evaluation Metrics table again with different numbers AND a duplicate of
# this panel's own Fitness tab โ so the page showed the same summary twice
# while the per-metric working stayed folded behind a collapsed row that
# nobody opened. The duplicate is gone and the working is what opens.
render_evaluation(
orig_fp, edited_fp, road_side, selected_vastu,
left_label="Domain Expert Engine",
right_label="Your Edit",
expander_label="Break-up โ the exact calculation on your edited plan",
show_summary=False,
expanded=True)
_WALL_OUTER, _WALL_INNER = 0.75, 0.40 # ft โ same as the editor's walls
def _carpet_dims(r, rooms):
"""Carpet (inside-wall) dimensions: subtract half an inner wall (0.2') on
each shared side and a full outer wall (0.75') on each exterior side โ
identical to the editor's carpet display."""
tol, minov = 0.6, 1.0
def neigh(side):
for o in rooms:
if o is r:
continue
yov = min(o.y + o.h, r.y + r.h) - max(o.y, r.y) >= minov
xov = min(o.x + o.w, r.x + r.w) - max(o.x, r.x) >= minov
if side == "L" and abs(o.x + o.w - r.x) < tol and yov:
return True
if side == "R" and abs(r.x + r.w - o.x) < tol and yov:
return True
if side == "B" and abs(o.y + o.h - r.y) < tol and xov:
return True
if side == "T" and abs(r.y + r.h - o.y) < tol and xov:
return True
return False
allow = lambda side: (_WALL_INNER / 2 if neigh(side) else _WALL_OUTER)
return (max(0.0, r.w - allow("L") - allow("R")),
max(0.0, r.h - allow("B") - allow("T")))
def _carpet_map(fp):
"""{room name: carpet sqft} for one plan."""
out, tot = {}, 0.0
for r in fp.rooms:
cw, ch = _carpet_dims(r, fp.rooms)
a = cw * ch
out[r.name] = out.get(r.name, 0.0) + a
tot += a
return out, tot
def render_carpet_area(fp, before_fp=None):
"""Each room's carpet area (usable area inside the walls). When `before_fp`
is given the table gains BEFORE and AFTER columns so an edit can be read
room by room. DISPLAY ONLY โ never used in scoring."""
after, ta = _carpet_map(fp)
if before_fp is None:
rows = [{"Room": pretty_room(n), "Carpet Area (sqft)": f"{a:.1f}"}
for n, a in after.items()]
rows.append({"Room": "TOTAL", "Carpet Area (sqft)": f"{ta:.1f}"})
st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")
return
before, tb = _carpet_map(before_fp)
rows = []
for n in list(before) + [k for k in after if k not in before]:
b_, a_ = before.get(n), after.get(n)
rows.append({
"Room": pretty_room(n),
"Before (sqft)": f"{b_:.1f}" if b_ is not None else "โ",
"After (sqft)": f"{a_:.1f}" if a_ is not None else "removed",
"Change": (f"{a_ - b_:+.1f}" if b_ is not None and a_ is not None
else ("new" if b_ is None else "removed")),
})
rows.append({"Room": "TOTAL", "Before (sqft)": f"{tb:.1f}",
"After (sqft)": f"{ta:.1f}", "Change": f"{ta - tb:+.1f}"})
st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")
st.caption(
"Carpet area is the usable floor inside the walls โ each side loses half "
"an inner wall (0.2') where shared and a full outer wall (0.75') where "
"it faces outside. Display only; scoring uses built-up areas.")
def render_evaluation(raw_fp, opt_fp, road_side, selected_vastu=None,
left_label="Layout Proposer",
right_label="Domain Expert Engine",
expander_label=None,
show_summary=True,
expanded=False):
"""The finalised scoring system: the nine-metric table (with the official
weights) plus a click-to-expand EXACT calculation break-up per metric.
The break-up is always computed on `opt_fp`, so the same function serves
the generated plan AND the user's edited plan โ call it a second time with
(original, edited) and the per-room Vastu tiers, adjacency pairs,
constraint results and size tables all reflect the edit. `show_summary`
suppresses the top table where the caller has already drawn its own.
Nothing inside is a keyed widget, so calling it twice is safe.
"""
craw = plan_metrics.evaluate(raw_fp, road_side, selected_vastu)
copt = plan_metrics.evaluate(opt_fp, road_side, selected_vastu)
W = plan_metrics.DEFAULT_WEIGHTS
# Fitness table: metric ยท weight ยท score ยท contribution to the fitness.
if show_summary:
rows = []
for key, label in plan_metrics.METRIC_LABELS:
w = W.get(key, 0.0)
rows.append({
"Metric": label,
"Weight": f"{w:.2f}",
"Score": _pct(copt.scores[key]),
"Contribution": f"{copt.scores[key] * w * 100:.2f}",
})
rows.append({"Metric": "FLOOR PLAN FITNESS", "Weight": "1.00",
"Score": _pct(copt.fitness),
"Contribution": f"{copt.fitness * 100:.2f}"})
st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")
st.caption(
"Contribution = Score ร Weight, and the contributions sum to the "
"fitness. All nine metrics now carry weight and the weights sum to "
f"1.00. Expand any metric for its exact calculation on the "
f"{right_label} plan.")
with st.expander(expander_label or
"Break-up โ the exact calculation behind every metric",
expanded=expanded):
_tabs = st.tabs([f"{left_label} vs {right_label}", "Vastu", "Adjacency",
"Constraints", "Room Size", "Room Width",
"Aspect Ratio", "Zoning", "Connectivity",
"Space Util", "Fitness"])
with _tabs[0]:
cmp_rows = [{"Metric": label,
left_label: _pct(craw.scores[key]),
right_label: _pct(copt.scores[key]),
"ฮ": f"{(copt.scores[key] - craw.scores[key]) * 100:+.1f}"}
for key, label in plan_metrics.METRIC_LABELS]
cmp_rows.append({"Metric": "FLOOR PLAN FITNESS",
left_label: _pct(craw.fitness),
right_label: _pct(copt.fitness),
"ฮ": f"{(copt.fitness - craw.fitness) * 100:+.1f}"})
st.dataframe(pd.DataFrame(cmp_rows), hide_index=True, width="stretch")
d = copt.details
s = copt.scores
_ZONE_FULL = {"NE": "North-East", "N": "North", "E": "East",
"SE": "South-East", "S": "South", "SW": "South-West",
"W": "West", "NW": "North-West", "Centre": "Centre"}
# "none" = the room has no Vastu rule at all. Shown as a dash, because a
# column full of the word "None" reads like a bug rather than a fact.
_TIER_TXT = {"high": "High", "med": "Med", "low": "Low",
"ok": "Acceptable", "avoid": "Avoid", "none": "โ"}
_TIER_CNT = {"high": "+1.0", "med": "+0.5", "low": "+0.2",
"ok": "+0.1", "avoid": "โ1.0", "none": "0"}
with _tabs[1]:
st.markdown(f"**Vastu Compliance โ {_pct(s['vastu'])}**")
vd = d["vastu"]
st.markdown(
"Each ruled room's occupied zone lands in a tier โ "
"**High +1 ยท Med +0.5 ยท Low +0.2 ยท Acceptable +0.1 ยท Avoid โ1**. "
"Two readings are shown below: the **plain compliance %** (rooms in "
"any allowed zone รท total) and the **weighted %** (total counts รท "
"the max if every room were High).")
vt, total_credit = [], 0.0
for r, z, t, c in vd["rows"]:
total_credit += c
ideal = plan_metrics.FINAL_VASTU.get(r, {}).get("high", ("โ",))[0]
# a room outside the rule set has no zone/tier โ show a dash
# rather than letting a bare None reach the table
_dash = lambda v: "โ" if v in (None, "") else v
vt.append({
"Room": pretty_room(r),
"Ideal Zone": _dash(_ZONE_FULL.get(ideal, ideal)),
"Current Zone": _dash(_ZONE_FULL.get(z, z)),
"Tier": _dash(_TIER_TXT.get(t, t)),
"Counts": _dash(_TIER_CNT.get(t, str(c) if c is not None else None))})
vt.append({"Room": "TOTAL", "Ideal Zone": "", "Current Zone": "",
"Tier": "", "Counts": f"{total_credit:+g}"})
st.dataframe(pd.DataFrame(vt), hide_index=True, width="stretch")
n = vd["total"]
weighted = max(0.0, min(1.0, total_credit / n)) if n else 1.0
st.markdown(
f"**Plain compliance = {vd['satisfied']} in an allowed zone รท "
f"{n} ruled rooms = {_pct(s['vastu'])}** \n"
f"**Weighted Vastu (novelty) = total {total_credit:+g} รท {n} max "
f"= {_pct(weighted)}**")
with _tabs[2]:
st.markdown(f"**Adjacency Achieved โ {_pct(s['adjacency'])}**")
ad = d["adjacency"]
_atier = {1.0: "High", 0.5: "Med", 0.2: "Low"}
st.markdown(
"Each finalised room pair earns its tier value when the two rooms "
"**share a wall** โ **High +1 ยท Med +0.5 ยท Low +0.2**. Every "
"**Avoid** pair that touches subtracts 1. "
"**Total possible is the MAX SCORE**, not the pair count โ a High "
"pair is worth 1.0 but a Low pair only 0.2, so the pairs sum to "
"less than their number. Score = (total counts โ avoid penalties) "
"รท total possible.")
# only the pairs that are actually present in the plan are judged
arows = [{"Room Pairs": n, "Tier": _atier.get(w, str(w)),
"Status": "Shares wall" if ok else "Doesn't share wall",
"Counts": f"+{w:g}" if ok else "0"}
for n, w, ap, ok in ad["rows"] if ap]
njudged = sum(1 for _n, _w, ap, _ok in ad["rows"] if ap)
arows.append({"Room Pairs": "TOTAL", "Tier": "", "Status": "",
"Counts": f"+{ad['earned']:g}"})
st.dataframe(pd.DataFrame(arows), hide_index=True, width="stretch")
if any(ap for _n, ap, _h in ad["avoid_rows"]):
st.markdown("**Avoid pairs (โ1 each if the two touch):**")
st.dataframe(pd.DataFrame(
[{"Room Pairs": n,
"Status": "Touching" if hit else "Apart",
"Counts": "โ1" if hit else "0"}
for n, ap, hit in ad["avoid_rows"] if ap]), hide_index=True,
width="stretch")
st.markdown(
f"**Final = (counts {ad['earned']:g} โ avoid "
f"{ad['penalties']:.0f}) รท {ad['possible']:g} max score "
f"= {_pct(s['adjacency'])}** \n"
f"*{njudged} pairs judged ยท max score {ad['possible']:g} = their "
f"tier values summed (High 1.0 ยท Med 0.5 ยท Low 0.2), not the pair "
f"count.*")
with _tabs[3]:
st.markdown(f"**Constraint Validation Engine โ {_pct(s['constraints'])}**")
cd = d["constraints"]
st.markdown(
f"**{cd['hard_total']} hard constraints (+1 each)** plus two soft "
"credits: +0.5 ร the Vastu fraction and +0.5 ร the Adjacency "
f"fraction. Score = (passed + soft) รท {cd['total_possible']:.0f}.")
crows = [{"Description": plan_metrics.CONSTRAINT_DESCRIPTIONS.get(k, k),
"Status": "Pass" if v else "Fail"}
for k, v in cd["hard"]]
crows.append({"Description": "TOTAL passed",
"Status": f"{cd['passed']} / {cd['hard_total']}"})
st.dataframe(pd.DataFrame(crows), hide_index=True, width="stretch")
st.markdown(
f"hard passed **{cd['passed']}/{cd['hard_total']}** ยท soft vastu "
f"**+{cd['soft_vastu']}** ยท soft adjacency "
f"**+{cd['soft_adjacency']}**\n\n"
f"**Final = ({cd['passed']} + {cd['soft_vastu']} + "
f"{cd['soft_adjacency']}) รท {cd['total_possible']:.0f} = "
f"{_pct(s['constraints'])}**")
with _tabs[4]:
st.markdown(f"**Room Size Accuracy โ {_pct(s['size_accuracy'])}**")
sd = d["size_accuracy"]
st.markdown(
"**Required Area** = the room's share of the buildable area from "
"the Proportions table (the size it SHOULD be). **Predicted Area** "
"= its actual drawn size in this plan (width ร depth). "
"**Deviation** = Predicted โ Required (signed: **+** over-sized, "
"**โ** under-sized). This is the standard **MAPE** "
"(mean absolute percentage error): "
"**Error % = |Deviation| รท Required ร 100**, and "
"**Accuracy = 100 โ mean(Error %)**.")
# metrics gives (name, plan_area, proportions_area, error%). Required =
# the proportions area; Predicted = the plan area; Deviation = a โ p.
st.dataframe(pd.DataFrame(
[{"Room": pretty_room(n), "Required Area (sqft)": p,
"Predicted Area (sqft)": a, "Deviation (sqft)": f"{a - p:+.1f}",
"Error %": e}
for n, a, p, e in sd["rooms"]]),
hide_index=True, width="stretch")
st.markdown(f"**Final = 100 โ mean error {sd['mean_error_pct']}% "
f"= {_pct(s['size_accuracy'])}**")
with _tabs[5]:
st.markdown(f"**Room Width Compliance โ {_pct(s['room_width'])}**")
rw = d["room_width"]
st.markdown(
"Each room's NARROW side must stay inside the Proportions width "
"table (living 9-12 ft ยท bedroom 8-12 ยท master 10-16 ยท "
"kitchen 7-10 ยท dining 5-8 ยท washroom 4-7 ยท utility 4-6 ยท "
"pooja 3-5). Score = rooms within bounds รท rooms judged.")
st.dataframe(pd.DataFrame(
[{"Room": pretty_room(n), "Width as per plan (ft)": f"{sh}",
"Min Req Width (ft)": f"{lo}", "Max Allowed (ft)": f"{hi}",
"Count": "Satisfied" if ok == "yes" else "Not satisfied"}
for n, sh, lo, hi, ok in rw["rows"]]),
hide_index=True, width="stretch")
st.markdown(f"**Final = {rw['ok']} satisfied รท {rw['judged']} judged "
f"= {_pct(s['room_width'])}**")
with _tabs[6]:
st.markdown(f"**Room Aspect Ratio โ {_pct(s['aspect_ratio'])}**")
ad2 = d["aspect_ratio"]
st.markdown("Per room: clamp((2.5 โ aspect) รท 1.5) โ 1:1 (a perfect "
"square) is ideal and scores 100%, โฅ2.5:1 scores zero. "
"Metric = the mean (passages and balconies exempt).")
arows = [{"Room": pretty_room(n), "Aspect": a, "Score": _pct(sc)}
for n, a, sc in ad2["rows"]]
st.dataframe(pd.DataFrame(arows), hide_index=True, width="stretch")
if arows:
st.markdown(
f"**Final = mean of {len(arows)} room scores = "
f"{_pct(s['aspect_ratio'])}**")
with _tabs[7]:
st.markdown(f"**Functional Zoning โ {_pct(s['zoning'])}**")
zd = d["zoning"]
c1, c2 = zd.get("cuts", (0.40, 0.55))
st.markdown(
"Distance = staircase centroid โ room centroid, **normalised** by "
"the farthest staircase-to-corner distance (**0** at the entry, "
"**1** at the deepest corner) so it is plot-size independent. "
f"Bands: **Common โค {c1} ยท Transitional โค {c2} ยท Private > {c2}**. "
"Ideal: Common areas near the entry, Private deepest. A room is "
"**Satisfied** when it lands in its ideal band or an adjacent one. "
"Score = satisfied รท total rooms.")
if "rows" in zd:
st.dataframe(pd.DataFrame(
[{"Room": pretty_room(n), "Ideal Zone": ib.title(),
"Distance from Entry (ft)": dist, "Normalised (0โ1)": nm,
"Current Zone": ab.title(),
"Count": "Satisfied" if ok else "Not satisfied"}
for n, ib, dist, nm, ab, ok in zd["rows"]]),
hide_index=True, width="stretch")
st.markdown(f"**Final = {zd['satisfied']} satisfied รท "
f"{zd['total']} rooms = {_pct(s['zoning'])}** \n"
f"*The staircase is not in the count โ it is the entry "
f"every distance is measured FROM, so its own distance "
f"from itself is meaningless. Every other room in the "
f"plan is judged.*")
with _tabs[8]:
st.markdown(f"**Connectivity โ {_pct(s['connectivity'])}**")
cn = d["connectivity"]
st.markdown(
"Access is **directional**: a route may only be walked in the "
"direction a room is legitimately entered from. So the passage "
"gives access to a bedroom, but a bedroom does **not** give access "
"to the passage โ you cannot reach the passage (and everything "
"hanging off it) by crossing somebody's bedroom. Each room's "
"permitted entry rooms:")
st.dataframe(pd.DataFrame([
{"Room": "Living ยท Passage", "May be entered from":
"Staircase (entry), Living, Dining, Passage"},
{"Room": "Dining", "May be entered from":
"Staircase (entry), Living, Dining, Passage, Kitchen"},
{"Room": "Kitchen ยท Bedrooms ยท Common bath ยท Study",
"May be entered from": "Living, Dining, Passage"},
{"Room": "Utility", "May be entered from":
"Living, Dining, Passage, Kitchen"},
{"Room": "Pooja", "May be entered from":
"Living, Dining, Passage, Kitchen"},
{"Room": "Balcony", "May be entered from":
"Living, Dining, Passage, any Bedroom"},
{"Room": "Attached bath", "May be entered from":
"Its own bedroom only"},
]), hide_index=True, width="stretch")
st.markdown(
"Rooms are then reached by walking those directed doorways out from "
"the entry (staircase). Score = reachable รท total rooms.")
if cn.get("nodes"):
fig_cg = fig_connectivity_graph(cn["nodes"], cn["edges"],
cn.get("blocked_edges", ()))
gcol, _gpad = st.columns([1, 1.6]) # keep the graph small
gcol.pyplot(fig_cg)
import matplotlib.pyplot as _plt
_plt.close(fig_cg)
iso = cn["unreachable"]
st.markdown(
"**โ
All rooms are reachable from the entry.**" if not iso else
"**โ Not fully connected โ isolated: " +
", ".join(pretty_room(x) for x in iso) + "**")
unreach = set(cn["unreachable"])
st.dataframe(pd.DataFrame(
[{"Room": pretty_room(r.name),
"Reachable from entry": "No" if r.name in unreach else "Yes"}
for r in opt_fp.rooms]), hide_index=True, width="stretch")
st.markdown(f"**Final = {cn['reachable']} reachable รท {cn['total']} "
f"rooms = {_pct(s['connectivity'])}**")
with _tabs[9]:
st.markdown(f"**Space Utilization โ {_pct(s['space_utilization'])}**")
su = d["space_utilization"]
st.markdown(
f"Fraction of the buildable (setback) area covered by rooms โ "
f"overlaps counted once, a gapless tiling scores 100%.\n\n"
f"**Final = {su['covered_sqft']} covered รท {su['buildable_sqft']} "
f"buildable sqft = {_pct(s['space_utilization'])}**")
with _tabs[10]:
st.markdown(f"**Floor Plan Fitness โ {_pct(copt.fitness)} (weighted fold)**")
fd = d["fitness"]
st.dataframe(pd.DataFrame(
[{"Metric": k, "Score": _pct(sc), "Weight": f"{w:.2f}",
"Contribution": f"{c * 100:.2f}"}
for k, sc, w, c in fd["contributions"]]),
hide_index=True, width="stretch")
st.markdown(f"**SUM รท {fd['weight_sum']} = {_pct(copt.fitness)}**")
def floorplan_to_dxf(fp, road_side="S", openings=None, walls=None):
"""Hand-written ASCII DXF using only R12-safe entities.
Room outlines used to be written as LWPOLYLINE, but LWPOLYLINE is an R14+
entity and the file declared no version, so AutoCAD read it as R12 and
silently dropped every outline โ the export opened showing the labels only.
Everything is now emitted as LINE + TEXT, which every DXF version supports,
and the header states $ACADVER explicitly."""
def esc(text):
return str(text).replace("\n", " ").replace("\r", " ")
def _ft_in(v):
"""Feet as the feet-inches string a drawing is normally annotated in."""
ft = int(v)
inch = int(round((v - ft) * 12))
if inch == 12:
ft, inch = ft + 1, 0
return f"{ft}'-{inch}\"" if inch else f"{ft}'"
lines = [
"0", "SECTION", "2", "HEADER",
"9", "$ACADVER", "1", "AC1009",
"9", "$INSBASE", "10", "0.0", "20", "0.0", "30", "0.0",
# extents include the title block below and the north arrow to the right
"9", "$EXTMIN", "10", "-2.0", "20", "-15.0", "30", "0.0",
"9", "$EXTMAX", "10", f"{fp.plot_w + 10.0:.3f}",
"20", f"{fp.plot_h + 2.0:.3f}", "30", "0.0",
"0", "ENDSEC",
"0", "SECTION", "2", "TABLES",
"0", "TABLE", "2", "LAYER", "70", "8",
"0", "LAYER", "2", "PLOT", "70", "0", "62", "7", "6", "CONTINUOUS",
"0", "LAYER", "2", "SETBACK", "70", "0", "62", "1", "6", "DASHED",
"0", "LAYER", "2", "ROOMS", "70", "0", "62", "5", "6", "CONTINUOUS",
"0", "LAYER", "2", "WALLS", "70", "0", "62", "8", "6", "CONTINUOUS",
"0", "LAYER", "2", "DOORS", "70", "0", "62", "3", "6", "CONTINUOUS",
"0", "LAYER", "2", "WINDOWS", "70", "0", "62", "4", "6", "CONTINUOUS",
"0", "LAYER", "2", "TEXT", "70", "0", "62", "7", "6", "CONTINUOUS",
"0", "LAYER", "2", "TITLE", "70", "0", "62", "7", "6", "CONTINUOUS",
"0", "ENDTAB", "0", "ENDSEC",
"0", "SECTION", "2", "ENTITIES",
]
def line(layer, x1, y1, x2, y2):
lines.extend([
"0", "LINE", "8", layer,
"10", f"{x1:.3f}", "20", f"{y1:.3f}", "30", "0.0",
"11", f"{x2:.3f}", "21", f"{y2:.3f}", "31", "0.0",
])
def rect(layer, x, y, w, h):
line(layer, x, y, x + w, y)
line(layer, x + w, y, x + w, y + h)
line(layer, x + w, y + h, x, y + h)
line(layer, x, y + h, x, y)
def text(layer, x, y, height, value):
# 72/73 = centred both ways, so 11/21 is the alignment point
lines.extend([
"0", "TEXT", "8", layer,
"10", f"{x:.3f}", "20", f"{y:.3f}", "30", "0.0",
"40", f"{height:.3f}", "1", esc(value),
"72", "1", "73", "2",
"11", f"{x:.3f}", "21", f"{y:.3f}", "31", "0.0",
])
def text_left(layer, x, y, height, value):
"""Left-aligned text (72=0/73=0 uses the 10/20 point as the baseline)."""
lines.extend([
"0", "TEXT", "8", layer,
"10", f"{x:.3f}", "20", f"{y:.3f}", "30", "0.0",
"40", f"{height:.3f}", "1", esc(value),
"72", "0", "73", "0",
"11", f"{x:.3f}", "21", f"{y:.3f}", "31", "0.0",
])
def arc(layer, cx, cy, r, a1, a2):
lines.extend([
"0", "ARC", "8", layer,
"10", f"{cx:.3f}", "20", f"{cy:.3f}", "30", "0.0",
"40", f"{r:.3f}", "50", f"{a1:.1f}", "51", f"{a2:.1f}",
])
rect("PLOT", 0, 0, fp.plot_w, fp.plot_h)
sb_road, sb_other = 6.56, 3.28
left = sb_road if road_side == "W" else sb_other
right = sb_road if road_side == "E" else sb_other
bottom = sb_road if road_side == "S" else sb_other
top = sb_road if road_side == "N" else sb_other
rect("SETBACK", left, bottom, fp.plot_w - left - right, fp.plot_h - bottom - top)
# Room labels are sized to FIT INSIDE their room. A DXF character is about
# 0.6 x the text height wide, so a 14-character name at the old 2 ft height
# was ~17 ft wide โ wider than the room, which is why labels came out huge.
CHAR_W = 0.62 # width of one character, as a fraction of height
MIN_H = 0.30 # below this a label is unreadable, so it is dropped
def fitted_height(s, room_w, room_h, cap=0.65):
"""Largest text height that keeps `s` inside the room."""
if not s:
return 0.0
return min(cap,
(room_w * 0.86) / (len(s) * CHAR_W),
room_h * 0.16)
for room in fp.rooms:
rect("ROOMS", room.x, room.y, room.w, room.h)
name = pretty_room(room.name).upper() # architectural convention
dims = f"{_ft_in(room.w)} x {_ft_in(room.h)}"
area = f"{room.w * room.h:.0f} SQ.FT."
# one height for the whole block so the lines read evenly
h = min(fitted_height(name, room.w, room.h),
fitted_height(dims, room.w, room.h))
if h < MIN_H:
# too tight for the full block โ try the name alone, else skip
h = fitted_height(name, room.w, room.h)
if h >= MIN_H:
text("TEXT", room.cx, room.cy, h, name)
continue
show_area = room.h > h * 7 and fitted_height(area, room.w, room.h) >= MIN_H
if show_area:
text("TEXT", room.cx, room.cy + h * 1.5, h, name)
text("TEXT", room.cx, room.cy, h * 0.85, dims)
text("TEXT", room.cx, room.cy - h * 1.4, h * 0.75, area)
else:
text("TEXT", room.cx, room.cy + h * 0.8, h, name)
text("TEXT", room.cx, room.cy - h * 0.8, h * 0.85, dims)
# โโ WALLS: the second face of every wall, so it reads as a thickness โโ
if walls:
t_out = float(walls.get("outer", _WALL_OUTER))
t_in = float(walls.get("inner", _WALL_INNER))
tol, minov = 0.6, 1.0
rs = fp.rooms
if rs:
x0 = min(r.x for r in rs); y0 = min(r.y for r in rs)
x1 = max(r.x + r.w for r in rs); y1 = max(r.y + r.h for r in rs)
rect("WALLS", x0, y0, x1 - x0, y1 - y0)
rect("WALLS", x0 + t_out, y0 + t_out,
(x1 - x0) - 2 * t_out, (y1 - y0) - 2 * t_out)
for i in range(len(rs)):
for j in range(i + 1, len(rs)):
a, b = rs[i], rs[j]
if abs(a.x + a.w - b.x) < tol or abs(b.x + b.w - a.x) < tol:
lo, hi = max(a.y, b.y), min(a.y + a.h, b.y + b.h)
if hi - lo >= minov:
xb = a.x + a.w if abs(a.x + a.w - b.x) < tol else b.x + b.w
line("WALLS", xb - t_in / 2, lo, xb - t_in / 2, hi)
line("WALLS", xb + t_in / 2, lo, xb + t_in / 2, hi)
if abs(a.y + a.h - b.y) < tol or abs(b.y + b.h - a.y) < tol:
lo, hi = max(a.x, b.x), min(a.x + a.w, b.x + b.w)
if hi - lo >= minov:
yb = a.y + a.h if abs(a.y + a.h - b.y) < tol else b.y + b.h
line("WALLS", lo, yb - t_in / 2, hi, yb - t_in / 2)
line("WALLS", lo, yb + t_in / 2, hi, yb + t_in / 2)
# โโ DOORS and WINDOWS at the positions set in the editor โโ
by_name = {r.name: r for r in fp.rooms}
for op in (openings or []):
r = by_name.get(op.get("room"))
if r is None:
continue
side, ow = op.get("side"), float(op.get("w", 3.0))
vert = side in ("L", "R")
span = r.h if vert else r.w
ow = max(0.8, min(ow, span))
t = max(ow / 2, min(float(op.get("t", span / 2)), span - ow / 2))
at = (r.x if side == "L" else r.x + r.w if side == "R"
else r.y if side == "B" else r.y + r.h)
base = r.y if vert else r.x
lo, hi = base + t - ow / 2, base + t + ow / 2
if op.get("kind") == "window":
# two parallel lines across the opening = a window in plan
if vert:
line("WINDOWS", at - 0.1, lo, at - 0.1, hi)
line("WINDOWS", at + 0.1, lo, at + 0.1, hi)
else:
line("WINDOWS", lo, at - 0.1, hi, at - 0.1)
line("WINDOWS", lo, at + 0.1, hi, at + 0.1)
else:
# leaf + quarter-circle swing, opening into the room
if vert:
inward = 1.0 if (r.x + r.w / 2) > at else -1.0
line("DOORS", at, lo, at + inward * ow, lo)
arc("DOORS", at, lo, ow, 0.0, 90.0) if inward > 0 else \
arc("DOORS", at, lo, ow, 90.0, 180.0)
else:
inward = 1.0 if (r.y + r.h / 2) > at else -1.0
line("DOORS", lo, at, lo, at + inward * ow)
arc("DOORS", lo, at, ow, 0.0, 90.0) if inward > 0 else \
arc("DOORS", lo, at, ow, 270.0, 360.0)
# โโ North arrow, to the right of the plot so it never sits over a room โโ
nx, ny = fp.plot_w + 6.0, fp.plot_h - 10.0
line("TITLE", nx, ny, nx, ny + 7.0)
line("TITLE", nx, ny + 7.0, nx - 1.1, ny + 4.8)
line("TITLE", nx, ny + 7.0, nx + 1.1, ny + 4.8)
text("TITLE", nx, ny + 8.8, 1.1, "N")
# โโ Title block under the plot โโ
built = sum(r.w * r.h for r in fp.rooms)
tb_y1, tb_h = -2.0, 11.0
tb_y0 = tb_y1 - tb_h
rect("TITLE", 0.0, tb_y0, fp.plot_w, tb_h)
line("TITLE", 0.0, tb_y1 - 3.4, fp.plot_w, tb_y1 - 3.4) # header rule
text_left("TITLE", 0.9, tb_y1 - 2.5, 1.25, "VASTU FLOOR PLAN")
rows = [
("PLOT SIZE", f"{_ft_in(fp.plot_w)} x {_ft_in(fp.plot_h)}"),
("ROAD FACING", {"S": "SOUTH", "N": "NORTH",
"E": "EAST", "W": "WEST"}.get(road_side, road_side)),
("BUILT-UP AREA", f"{built:.0f} SQ.FT."),
("ROOMS", str(len(fp.rooms))),
]
col_w = fp.plot_w / max(len(rows), 1)
for i, (k, v) in enumerate(rows):
x = 0.9 + i * col_w
text_left("TITLE", x, tb_y1 - 5.4, 0.62, k)
text_left("TITLE", x, tb_y1 - 7.4, 0.85, v)
text_left("TITLE", 0.9, tb_y0 + 1.0, 0.5,
"ALL DIMENSIONS IN FEET-INCHES. LAYERS: PLOT / SETBACK / ROOMS / "
"WALLS / DOORS / WINDOWS / TEXT / TITLE")
lines.extend(["0", "ENDSEC", "0", "EOF"])
return "\n".join(lines).encode("ascii", errors="ignore")
def clone_floorplan(fp):
rooms = [Room(r.name, r.x, r.y, r.w, r.h) for r in fp.rooms]
cloned = FloorPlan(rooms, fp.plot_w, fp.plot_h)
cloned.scores = dict(getattr(fp, "scores", {}))
cloned.template_name = getattr(fp, "template_name", "manual_adjusted")
return cloned
def score_adjusted_plan(fp, selected_vastu, w_vs, w_aq, w_cs, w_su, w_ac, w_lc):
weights = (w_aq, w_vs, w_su, w_ac, w_cs, w_lc)
_score_one(fp, selected_vastu, weights)
return fp
st.markdown(
"""
Architectural Floor Plan Generation System
Hybrid AI-Assisted Decision Support for Residential Layout Planning
""",
unsafe_allow_html=True,
)
with st.sidebar:
st.markdown("## Configuration")
st.markdown("---")
st.markdown("### Plot")
c1, c2 = st.columns(2)
with c1:
plot_w = st.number_input("Width (ft)", min_value=20, max_value=100, value=40, step=5)
with c2:
plot_h = st.number_input("Depth (ft)", min_value=20, max_value=100, value=60, step=5)
road_side = st.selectbox(
"Road-facing side",
options=["S", "N", "E", "W"],
index=0,
format_func={"S": "South", "N": "North", "E": "East", "W": "West"}.get,
)
plan_type = st.radio(
"Plan type",
options=["1BHK", "2BHK", "3BHK", "4BHK"],
index=0,
horizontal=True,
)
# switching plan type clears stale plans of the other type
if st.session_state.get("last_plan_type") not in (None, plan_type):
st.session_state.pop("last_top_plans", None)
st.session_state["last_plan_type"] = plan_type
st.markdown("")
generate_btn = st.button("Generate Floor Plans", width="stretch",
type="primary")
# โโ Fixed defaults (no longer shown as controls) โโโโโโโโโโโโโโโโโโโโโโโโโ
# Rooms are decided by the plan type; the shown plans are re-ranked by the
# finalised nine-metric fitness, so the generation weights are just defaults.
core_required = {
"external_staircase": True, "living_room": True, "kitchen": True,
"dining_room": True, "utility_area": True, "common_bathroom": True,
"master_bedroom": True,
"attached_bathroom": plan_type in {"2BHK", "3BHK", "4BHK"},
}
required_rooms = [r for r, on in core_required.items() if on]
opt_defaults = {
"bedroom_01": plan_type in {"2BHK", "3BHK", "4BHK"},
"bedroom_02": plan_type in {"3BHK", "4BHK"},
"bedroom_03": plan_type == "4BHK",
"balcony": True, "pooja_room": True,
}
optional_rooms = [r for r, on in opt_defaults.items() if on]
required_rooms, optional_rooms = enforce_bhk_rooms(
plan_type, required_rooms, optional_rooms)
room_names = required_rooms + optional_rooms
selected_vastu = [rule[0] for rule in VASTU_RULES]
w_vs, w_aq, w_cs, w_su, w_ac, w_lc = 0.30, 0.25, 0.15, 0.15, 0.10, 0.05
if generate_btn:
progress_bar = st.progress(0, text="Initialising generation pipeline...")
status = st.empty()
with st.spinner(""):
status.markdown("**Stage I โ Cognitive Intelligence** ยท Layout Proposer predicts the conceptual layout")
progress_bar.progress(20, text="Layout Proposer: Graph VAE predicting candidate topologies...")
time.sleep(0.2)
status.markdown("**Step 2/4** - AI engine designs the layouts")
progress_bar.progress(45, text="AI engine: designing layouts...")
plan_count = int(os.getenv("PLAN_COUNT", "20"))
# The GPT-first BHK pipeline is the PRIMARY path: it designs all the
# plans with the GPT engine and only uses its own PDF templates when
# no API key is available. generate_population (ml/rule backends) is
# kept strictly as an emergency fallback.
_bhk_generator = {
"2BHK": pdf_templates_2bhk.generate_bhk2_pdf_population,
"3BHK": pdf_templates_3bhk.generate_bhk3_pdf_population,
"4BHK": pdf_templates_4bhk.generate_bhk4_pdf_population,
}.get(plan_type, pdf_templates.generate_bhk1_pdf_population)
bhk_selected_optional = list(optional_rooms)
if plan_type == "2BHK" and "attached_bathroom" in required_rooms:
bhk_selected_optional.append("attached_bathroom")
try:
plan_pairs = _bhk_generator(
plot_w=plot_w, plot_h=plot_h,
selected_optional=bhk_selected_optional, road_side=road_side,
n=plan_count)
except Exception as exc:
print(f"[app] {plan_type} pipeline failed: {exc}")
plan_pairs = []
if not plan_pairs:
st.warning("BHK pipeline returned no plans; using emergency backend generator.")
plan_pairs = generate_population(
room_names,
plot_w,
plot_h,
n=plan_count,
required_rooms=required_rooms,
optional_rooms=optional_rooms,
road_side=road_side,
)
time.sleep(0.2)
status.markdown("**Stage II โ Design Synthesis** ยท Domain Expert Engine constructs and validates the layouts")
progress_bar.progress(75, text="Domain Expert Engine: conditioned geometry construction...")
ranked = rank_plans(
plan_pairs,
selected_vastu,
w_vs=w_vs,
w_aq=w_aq,
w_cs=w_cs,
w_su=w_su,
w_ac=w_ac,
w_lc=w_lc,
road_side=road_side,
regenerate_peak=False,
)
top_plans = ranked[:plan_count]
# RANK BY THE FINALISED FITNESS so Plan 1 is genuinely the best plan
# under the same scoring system every panel displays (rank_plans uses
# the legacy objective, which would disagree with the shown numbers).
top_plans.sort(
key=lambda p: -plan_metrics.evaluate(
p.get("peak", p["optimised"]), road_side,
selected_vastu).fitness)
st.session_state["last_top_plans"] = top_plans
st.session_state["last_road_side"] = road_side
status.markdown("**Stage III โ Decision Support** ยท Multi-Criteria Evaluation Engine scores and ranks")
progress_bar.progress(100, text="Complete")
time.sleep(0.2)
progress_bar.empty()
status.empty()
else:
top_plans = st.session_state.get("last_top_plans")
if top_plans:
road_side = st.session_state.get("last_road_side", road_side)
if top_plans:
best_opt = top_plans[0].get("peak", top_plans[0]["optimised"])
_engine_name = str(getattr(best_opt, "template_name", "") or "")
if "_ai_" not in _engine_name and "_bb_" not in _engine_name:
st.warning("These plans came from the legacy emergency backend. "
"Check the setup and click Generate again.")
# โโ Average of ALL nine metrics across every generated plan โโโโโโโโโโโโโโ
_cards = [plan_metrics.evaluate(p.get("peak", p["optimised"]), road_side,
selected_vastu) for p in top_plans]
_n = len(_cards) or 1
_avg_fit = sum(c.fitness for c in _cards) / _n
_avg = {k: sum(c.scores[k] for c in _cards) / _n
for k, _lab in plan_metrics.METRIC_LABELS}
st.markdown(f'', unsafe_allow_html=True)
tiles = [("Fitness", _avg_fit)] + [
(lab, _avg[k]) for k, lab in plan_metrics.METRIC_LABELS]
per_row = 6
for start in range(0, len(tiles), per_row):
cols = st.columns(per_row)
for c, (lab, val) in enumerate(tiles[start:start + per_row]):
cols[c].metric(lab, f"{val * 100:.0f}%")
st.caption("Each score meaned over all generated plans. Click a plan below "
"for its own full break-up.")
# Room-colour legend goes in the sidebar's empty space, so it sits on the
# LEFT alongside the whole gallery rather than beside one plan.
with st.sidebar:
st.markdown("---")
render_side_legend(top_plans[0].get("peak", top_plans[0]["optimised"]))
# โโ Plan gallery: all plans at once, click a tile to open it โโโโโโโโโโโโโโ
st.markdown('',
unsafe_allow_html=True)
selected_idx = min(st.session_state.get("selected_plan_idx", 0),
len(top_plans) - 1)
GALLERY_COLS = 5
for row_start in range(0, len(top_plans), GALLERY_COLS):
cols = st.columns(GALLERY_COLS)
for c, idx in enumerate(
range(row_start, min(row_start + GALLERY_COLS, len(top_plans)))):
with cols[c]:
fp_i = top_plans[idx].get("peak", top_plans[idx]["optimised"])
sel = (idx == selected_idx)
st.markdown(f'',
unsafe_allow_html=True)
st.image(plan_thumbnail(fp_i, road_side),
width="stretch")
st.markdown('
', unsafe_allow_html=True)
fit = _cards[idx].fitness * 100
if st.button(f"{'โ ' if sel else ''}Plan {idx + 1} ยท {fit:.0f}%",
key=f"pick_{idx}", width="stretch",
type="primary" if sel else "secondary"):
st.session_state["selected_plan_idx"] = idx
st.rerun()
# Ranked comparison of every plan, directly under the gallery it describes.
st.markdown('', unsafe_allow_html=True)
# _cards[idx] is the finalised evaluation of top_plans[idx]'s optimised
# plan, already computed for the average panel โ reuse it here.
rows = []
for idx, (pair_i, co) in enumerate(zip(top_plans, _cards)):
cr = plan_metrics.evaluate(pair_i["raw"], road_side, selected_vastu)
rows.append({
"Plan": f"Plan {idx + 1}",
"Layout Proposer": f"{cr.fitness * 100:.1f}%",
"Domain Expert Engine": f"{co.fitness * 100:.1f}%",
"Gain": f"{(co.fitness - cr.fitness) * 100:+.1f}%",
"Vastu": f"{co.scores['vastu'] * 100:.0f}%",
"Adjacency": f"{co.scores['adjacency'] * 100:.0f}%",
"Constraints": f"{co.scores['constraints'] * 100:.0f}%",
"Aspect": f"{co.scores['aspect_ratio'] * 100:.0f}%",
"Room Size": f"{co.scores['size_accuracy'] * 100:.0f}%",
"Space Util": f"{co.scores['space_utilization'] * 100:.0f}%",
})
st.dataframe(pd.DataFrame(rows), hide_index=True, width="stretch")
st.markdown(f'', unsafe_allow_html=True)
pair = top_plans[selected_idx]
raw_fp = pair["raw"]
opt_fp = pair.get("peak", pair["optimised"])
comparison_fig = fig_comparison(
raw_fp, opt_fp,
rank=selected_idx + 1,
road_side=road_side,
left_title="Layout Proposer Generated",
right_title="Expert Engine Generated",
)
comparison_png = fig_to_bytes(comparison_fig).getvalue()
# Scores + legend as a vertical column on the LEFT, the plans on the RIGHT.
side, main = st.columns([1, 3.6])
with side:
render_side_scores(raw_fp, opt_fp, road_side, selected_vastu)
with main:
st.image(comparison_png, width="stretch")
st.markdown('', unsafe_allow_html=True)
render_evaluation(raw_fp, opt_fp, road_side, selected_vastu)
st.markdown('', unsafe_allow_html=True)
editor_result = floor_plan_editor(
rooms=opt_fp.rooms,
plot_w=opt_fp.plot_w,
plot_h=opt_fp.plot_h,
road_side=road_side,
key=f"editor_{selected_idx}",
)
# The editor returns the edited room list. Keep the ORIGINAL optimised plan
# intact (so we can compare) and stash the edit in session state so it
# survives Streamlit reruns; then score it against the original below.
edited_key = f"edited_fp_{selected_idx}"
if editor_result:
st.session_state[edited_key] = editor_result
edited_result = st.session_state.get(edited_key)
if edited_result:
# the editor sends {rooms, openings, walls}; older payloads were a bare
# room list, so accept both
if isinstance(edited_result, dict):
ed_rooms = edited_result.get("rooms", [])
ed_openings = edited_result.get("openings", [])
ed_walls = edited_result.get("walls", {})
else:
ed_rooms, ed_openings, ed_walls = edited_result, [], {}
edited_fp = FloorPlan(
[Room(r["name"], r["x"], r["y"], r["w"], r["h"])
for r in ed_rooms],
opt_fp.plot_w, opt_fp.plot_h)
st.session_state[f"edited_fp_obj_{selected_idx}"] = (
edited_fp, ed_openings, ed_walls)
# Domain Expert Engine plan and YOUR edited plan, side by side.
st.markdown('', unsafe_allow_html=True)
import matplotlib.pyplot as _plt_ed
o_fig = fig_floorplan(opt_fp, opt_fp.plot_w, opt_fp.plot_h, road_side,
"Domain Expert Engine (original)")
o_png = fig_to_bytes(o_fig).getvalue()
_plt_ed.close(o_fig)
ed_fig = fig_floorplan(edited_fp, edited_fp.plot_w, edited_fp.plot_h,
road_side, "Your Edited Plan")
ed_png = fig_to_bytes(ed_fig).getvalue()
_plt_ed.close(ed_fig)
# Kept to two thirds of the row so the pair reads at a comfortable size
# rather than filling the page โ these are a comparison, not the
# working drawing.
pv1, pv2, _pv_pad = st.columns([1, 1, 1])
pv1.image(o_png, width="stretch")
pv2.image(ed_png, width="stretch")
render_edit_comparison(opt_fp, edited_fp, road_side, selected_vastu)
st.markdown('', unsafe_allow_html=True)
render_carpet_area(edited_fp, before_fp=opt_fp)
# Carpet area of the plan as generated โ only when nothing has been edited
# (the edited plan shows its own carpet table up in the editor section).
_edit = st.session_state.get(f"edited_fp_obj_{selected_idx}")
if not _edit:
st.markdown('',
unsafe_allow_html=True)
render_carpet_area(opt_fp)
# โโ Everything downloadable, at the very end โโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
st.markdown('',
unsafe_allow_html=True)
dxf_fp, dxf_openings, dxf_walls = (_edit if _edit else (opt_fp, [], {}))
dcols = st.columns(4 if _edit else 2)
dcols[0].download_button(
"Plan PNG",
data=comparison_png,
file_name=f"{plan_type.lower()}_plan_{selected_idx + 1}.png",
mime="image/png", key=f"png_download_{selected_idx}", width="stretch")
dcols[1].download_button(
"Plan DXF (AutoCAD)",
data=floorplan_to_dxf(opt_fp, road_side),
file_name=f"{plan_type.lower()}_plan_{selected_idx + 1}.dxf",
mime="application/dxf", key=f"dxf_download_{selected_idx}",
width="stretch")
if _edit:
dcols[2].download_button(
"Edited plan PNG",
data=ed_png,
file_name=f"{plan_type.lower()}_plan_{selected_idx + 1}_edited.png",
mime="image/png", key=f"png_edit_{selected_idx}", width="stretch")
dcols[3].download_button(
"Edited plan DXF",
data=floorplan_to_dxf(dxf_fp, road_side, dxf_openings, dxf_walls),
file_name=f"{plan_type.lower()}_plan_{selected_idx + 1}_edited.dxf",
mime="application/dxf", key=f"dxf_edit_{selected_idx}",
width="stretch")
st.caption(
"DXF layers: PLOT ยท SETBACK ยท ROOMS ยท WALLS ยท DOORS ยท WINDOWS ยท TEXT ยท "
"TITLE. The edited DXF carries your rooms, walls, doors and windows. "
"DWG is AutoCAD's proprietary format โ open the DXF and **Save As โ "
".dwg** if a DWG is needed.")
else:
st.markdown(
"""
Configure the Design Requirements
Specify the design requirements to generate and compare multiple layout alternatives.
""",
unsafe_allow_html=True,
)
st.markdown('', unsafe_allow_html=True)
c1, c2, c3, c4 = st.columns(4)
cards = [
(c1, "Stage I โ Cognitive Intelligence",
"Learns user requirements and predicts the conceptual layout. "
"Layout Proposer โ Graph VAE + Geometry Constructor."),
(c2, "Stage II โ Design Synthesis",
"Generates and validates multiple candidate layouts. "
"Domain Expert Engine with Conditioned Geometry Constructor, "
"checked by the Constraint Validation Engine."),
(c3, "Stage III โ Decision Support",
"Evaluates, ranks and โ after editing โ re-evaluates the layouts to "
"help choose the best alternative. "
"Multi-Criteria Evaluation Engine."),
(c4, "Stage IV โ Documentation",
"The selected design is detailed with walls, doors and windows, then "
"exported to CAD and image formats. "
"User Interactive Editor Module."),
]
for col, title, desc in cards:
col.markdown(
f"""
""",
unsafe_allow_html=True,
)