vastu-plan-generation / core /render_plan.py
Aakash231217
Free editor movement + rule-check panel; fix pair labels and hero title
00b0961
Raw History Blame Contribute Delete
10.8 kB
"""
PDF-style COLOURED plan renderer.
Draws a FloorPlan (or a list of {name,x,y,w,h} boxes) exactly in the layout
style of the client's reference PDF β€” plot boundary, setback red lines, ROAD
band, north arrow, room name + WxH labels β€” but with every room FILLED in its
ROOM_COLORS colour instead of white.
Usage:
from core.render_plan import render_floorplan, render_pairs_sheet
render_floorplan(fp, "plan.png", road_side="S", title="Optimised Plan 1")
render_pairs_sheet(pairs, "sheet.png", road_side="S") # raw vs optimised
"""
from __future__ import annotations
import math
from typing import List, Optional
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.patches import Rectangle, FancyArrow
# ── colours: bind to the project's ROOM_COLORS when available ────────────────
try:
from .constants import ROOM_COLORS
except Exception: # pragma: no cover
ROOM_COLORS = {}
_DEFAULT_COLORS = {
"master_bedroom": "#1565C0", "bedroom_01": "#1976D2",
"bedroom_02": "#1E88E5", "bedroom_03": "#2196F3",
"kitchen": "#B71C1C", "living_room": "#2E7D32",
"dining_room": "#388E3C", "common_bathroom": "#F9A825",
"attached_bathroom": "#F57F17", "attached_bathroom_02": "#FFB300",
"powder_room": "#FF8F00",
"foyer": "#6A1B9A", "internal_corridor": "#78909C",
"balcony": "#00695C", "pooja_room": "#E65100",
"utility_area": "#4E342E", "study": "#283593",
"external_staircase": "#455A64", "lift": "#212121",
}
_LABELS = {
"external_staircase": "STAIRCASE", "internal_corridor": "CORRIDOR",
"living_room": "LIVING", "dining_room": "DINING", "kitchen": "KITCHEN",
"common_bathroom": "WASHROOM", "attached_bathroom": "ATT. WASHROOM",
"attached_bathroom_02": "ATT. WASHROOM 2",
"master_bedroom": "MASTER BEDROOM", "bedroom_01": "BEDROOM 1",
"bedroom_02": "BEDROOM 2", "bedroom_03": "BEDROOM 3",
"pooja_room": "POOJA", "utility_area": "UTILITY", "study": "STUDY",
"foyer": "FOYER", "balcony": "BALCONY", "lift": "LIFT",
"internal_corridor": "PASSAGE",
}
try:
from .ml_pipeline import get_setbacks
except Exception: # pragma: no cover
def get_setbacks(road_side: str = "S"):
sb_road, sb_other = 6.56, 3.28
return (sb_road if road_side == "W" else sb_other,
sb_road if road_side == "E" else sb_other,
sb_road if road_side == "S" else sb_other,
sb_road if road_side == "N" else sb_other)
def _color(name: str) -> str:
return ROOM_COLORS.get(name, _DEFAULT_COLORS.get(name, "#9E9E9E"))
def _ft_in(v: float) -> str:
ft = int(v)
inch = int(round((v - ft) * 12))
if inch == 12:
ft, inch = ft + 1, 0
return f"{ft}'" + (f"{inch}\"" if inch else "")
def _boxes_of(plan):
"""Accept a FloorPlan or a list of dict boxes."""
if hasattr(plan, "rooms"):
return [{"name": r.name, "x": r.x, "y": r.y, "w": r.w, "h": r.h}
for r in plan.rooms], plan.plot_w, plan.plot_h
return plan, None, None
def draw_plan(ax, plan, plot_w: Optional[float] = None,
plot_h: Optional[float] = None, road_side: str = "S",
title: str = "", show_dims: bool = True,
alpha: float = 0.80, text_scale: float = 1.0):
"""`text_scale` shrinks EVERY piece of text on the drawing. The font sizes
below are tuned for a full-size plan; a gallery thumbnail is roughly half
that width, so at scale 1.0 its labels look enormous against the rooms.
Callers rendering small previews pass a scale well under 1."""
boxes, pw, ph = _boxes_of(plan)
plot_w = plot_w or pw
plot_h = plot_h or ph
# ROAD band outside the plot on the road side
road_band = max(plot_w, plot_h) * 0.16
if road_side == "S":
rb = Rectangle((0, -road_band), plot_w, road_band)
road_xy, rot = (plot_w / 2, -road_band / 2), 0
elif road_side == "N":
rb = Rectangle((0, plot_h), plot_w, road_band)
road_xy, rot = (plot_w / 2, plot_h + road_band / 2), 0
elif road_side == "W":
rb = Rectangle((-road_band, 0), road_band, plot_h)
road_xy, rot = (-road_band / 2, plot_h / 2), 90
else:
rb = Rectangle((plot_w, 0), road_band, plot_h)
road_xy, rot = (plot_w + road_band / 2, plot_h / 2), 90
rb.set(facecolor="#ECEFF1", edgecolor="none", zorder=0)
ax.add_patch(rb)
ax.text(*road_xy, "ROAD", rotation=rot, ha="center", va="center",
fontsize=13 * text_scale, fontweight="bold", color="#37474F",
zorder=1)
# plot boundary
ax.add_patch(Rectangle((0, 0), plot_w, plot_h, facecolor="white",
edgecolor="black", linewidth=1.6, zorder=1))
# setback (red dashed) rectangle
l, r, b, t = get_setbacks(road_side)
ax.add_patch(Rectangle((l, b), plot_w - l - r, plot_h - b - t,
facecolor="none", edgecolor="#D32F2F",
linestyle=(0, (5, 4)), linewidth=1.0, zorder=2))
label_owner = {}
for bx in boxes:
name = bx["name"]
if name == "internal_corridor":
continue
current = label_owner.get(name)
if current is None or bx["w"] * bx["h"] > current["w"] * current["h"]:
label_owner[name] = bx
# rooms β€” coloured fills, dark outline (the "not white" part)
for bx in boxes:
room_area = bx["w"] * bx["h"]
min_side = min(bx["w"], bx["h"])
duplicate_fragment = (
bx["name"] != "internal_corridor"
and label_owner.get(bx["name"]) is not bx
)
render_name = bx["name"]
if duplicate_fragment and bx["name"] not in (
"pooja_room", "balcony", "utility_area",
"common_bathroom", "attached_bathroom"):
render_name = "internal_corridor"
c = _color(render_name)
ax.add_patch(Rectangle((bx["x"], bx["y"]), bx["w"], bx["h"],
facecolor=c, alpha=alpha,
edgecolor="#212121", linewidth=1.1, zorder=3))
is_tiny = room_area < 18.0 or min_side < 2.5
if render_name == "internal_corridor":
if room_area < 6.0 or min_side < 0.45:
continue
elif is_tiny and bx["name"] not in (
"pooja_room", "balcony", "utility_area",
"common_bathroom", "attached_bathroom"):
continue
label = _LABELS.get(render_name, render_name.upper())
if render_name == "internal_corridor" and bx["h"] > bx["w"]:
rot_lbl = 90
else:
rot_lbl = 0
# one uniform, small font for EVERY room (no per-room scaling) and no
# bold β€” bold was rendering blurry and larger text spilled out of the
# smaller rectangles
fs = 6.0 * text_scale
txt = label
if show_dims and render_name != "internal_corridor" and room_area >= 18.0 and min_side >= 2.0:
txt += f"\n{_ft_in(bx['w'])} X {_ft_in(bx['h'])}"
ax.text(bx["x"] + bx["w"] / 2, bx["y"] + bx["h"] / 2, txt,
ha="center", va="center", fontsize=fs, rotation=rot_lbl,
color="white", fontweight="normal", zorder=4,
path_effects=None)
# north arrow (top-right corner)
ax_len = max(plot_w, plot_h) * 0.06
ax.add_patch(FancyArrow(plot_w * 1.04, plot_h * 0.94, 0, ax_len,
width=ax_len * 0.18, head_width=ax_len * 0.55,
head_length=ax_len * 0.6, color="black",
zorder=5, clip_on=False))
ax.text(plot_w * 1.04, plot_h * 0.94 + ax_len * 2.0, "N", ha="center",
fontsize=9 * text_scale, fontweight="bold", clip_on=False)
pad = road_band + 2
ax.set_xlim(-pad if road_side == "W" else -2,
plot_w + (pad if road_side == "E" else 4))
ax.set_ylim(-pad if road_side == "S" else -2,
plot_h + (pad if road_side == "N" else 4))
ax.set_aspect("equal")
ax.axis("off")
if title:
ax.set_title(title, fontsize=10, fontweight="bold")
def render_floorplan(plan, path: str, plot_w: Optional[float] = None,
plot_h: Optional[float] = None, road_side: str = "S",
title: str = "", dpi: int = 150):
fig, ax = plt.subplots(figsize=(6, 9))
draw_plan(ax, plan, plot_w, plot_h, road_side, title)
fig.tight_layout()
fig.savefig(path, dpi=dpi, bbox_inches="tight")
plt.close(fig)
return path
def render_pairs_sheet(pairs, path: str, road_side: str = "S",
max_pairs: int = 4, dpi: int = 130):
"""One row per plan: RAW (AI generated) on the left, OPTIMISED right."""
pairs = list(pairs)[:max_pairs]
rows = len(pairs)
fig, axes = plt.subplots(rows, 2, figsize=(11, 7.2 * rows))
if rows == 1:
axes = [axes]
for k, (raw, opt) in enumerate(pairs):
name = getattr(opt, "template_name", f"plan {k + 1}")
draw_plan(axes[k][0], raw, road_side=road_side,
title=f"AI GENERATED β€” {name}")
draw_plan(axes[k][1], opt, road_side=road_side,
title=f"OPTIMISED β€” {name}")
fig.tight_layout()
fig.savefig(path, dpi=dpi, bbox_inches="tight")
plt.close(fig)
return path
def fig_floorplan(plan, plot_w: Optional[float] = None,
plot_h: Optional[float] = None, road_side: str = "S",
title: str = ""):
"""Return a Matplotlib Figure for one plan (for Streamlit st.pyplot /
fig_to_bytes), without writing a file."""
fig, ax = plt.subplots(figsize=(6, 9))
draw_plan(ax, plan, plot_w, plot_h, road_side, title)
fig.tight_layout()
return fig
def fig_comparison(raw, opt, plot_w: Optional[float] = None,
plot_h: Optional[float] = None, road_side: str = "S",
rank: Optional[int] = None,
left_title: str = "Layout Proposer Generated",
right_title: str = "Expert Engine Generated"):
"""Return a Figure with the RAW plan (left) and OPTIMISED plan (right),
matching the existing draw_comparison call signature used by app.py."""
fig, (axl, axr) = plt.subplots(1, 2, figsize=(12, 9))
lt = left_title if rank is None else f"{left_title} β€” Plan {rank}"
rt = right_title if rank is None else f"{right_title} β€” Plan {rank}"
draw_plan(axl, raw, plot_w, plot_h, road_side, lt)
draw_plan(axr, opt, plot_w, plot_h, road_side, rt)
fig.tight_layout()
return fig