Files
cad-building-showcase/scripts/verify_showcase.py

140 lines
5.4 KiB
Python

#!/usr/bin/env python3
"""Verify a building_spec.json (+ optional GLBs) without Blender.
Outputs:
- a text report: per-floor segment counts, footprint area, cap presence,
glazing continuity, and (for any GLBs passed) node/vertex counts, file size
and a pass/fail against a size budget;
- orthographic elevation/plan previews (front / side / top) as a PNG, so the
Agent can eyeball completeness and orientation before accepting the model.
Usage:
python3 verify_showcase.py --spec building_spec.json \
[--glb overview.glb standard.glb detail.glb] \
[--out verify_previews.png] \
[--budget-mb 0.6]
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
import showcase_schema
def load_spec(path: Path) -> dict:
return json.loads(path.read_text(encoding="utf-8"))
def glb_stats(path: Path):
"""Node + vertex count and byte size; works on Draco GLBs (accessor.count kept)."""
try:
from pygltflib import GLTF2
except Exception:
return {"file": path.name, "bytes": path.stat().st_size, "note": "pygltflib not installed"}
g = GLTF2().load(str(path))
verts = 0
for m in g.meshes:
for p in m.primitives:
if p.attributes.POSITION is not None:
verts += g.accessors[p.attributes.POSITION].count
return {
"file": path.name,
"bytes": path.stat().st_size,
"meshes": len(g.meshes),
"vertices": verts,
"draco": any("KHR_draco_mesh_compression" in (e or "") for e in (g.extensionsUsed or [])),
}
def text_report(spec: dict, glbs: list[Path], budget_mb: float) -> tuple[str, bool]:
lines = ["# Showcase verification", ""]
failed = False
floors = spec.get("floors", {})
lines.append(f"{'floor':7} {'z':>6} {'h':>4} {'fp_area':>8} {'caps':>4} segments")
for k, f in floors.items():
segs = {c: len(v) for c, v in f.get("segments", {}).items() if v}
fp = f.get("footprint", {}).get("area")
caps = len(f.get("caps", []))
merged = sum(1 for s in f.get("segments", {}).get("glazing", []) if s.get("source_type") == "merged")
glz = len(f.get("segments", {}).get("glazing", []))
cont = f" glazing_continuous={merged}/{glz}" if glz else ""
lines.append(f"{k:7} {f.get('z', 0):>6.1f} {f.get('height', 0):>4.1f} {str(fp):>8} {caps:>4} {segs}{cont}")
lines.append("")
if glbs:
lines.append("## GLB budget")
budget = budget_mb * 1024 * 1024
for p in glbs:
st = glb_stats(p)
mb = st["bytes"] / 1024 / 1024
ok = "OK" if st["bytes"] <= budget else "OVER"
failed = failed or st["bytes"] > budget or not st.get("meshes")
extra = f" verts={st.get('vertices', '?')} draco={st.get('draco', '?')}"
lines.append(f" {st['file']:20} {mb:6.2f} MB [{ok} vs {budget_mb}MB]{extra}")
return "\n".join(lines), failed
def render_previews(spec: dict, out: Path) -> bool:
try:
import numpy as np # noqa
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
except Exception:
return False
floors = spec["floors"]
fig = plt.figure(figsize=(22, 7))
# front elevation (X vs Z), side elevation (Y vs Z), plan (X vs Y)
for sub, (ax_h, ax_v, title) in enumerate(
[(0, 2, "Front elevation (X-Z)"), (1, 2, "Side elevation (Y-Z)"), (0, 1, "Plan overlay (X-Y)")]
):
ax = fig.add_subplot(1, 3, sub + 1)
for k, f in floors.items():
z = float(f["z"])
h = float(f.get("height", 4.2))
for cat, col in [("walls", "#8a7f6a"), ("columns", "#f58a1f"), ("glazing", "#5aa9c9")]:
for s in f.get("segments", {}).get(cat, []):
a, b = s["start"], s["end"]
if ax_v == 2: # elevation: vertical extent z..z+h at midpoint of horizontal axis
ah0, ah1 = a[ax_h], b[ax_h]
ax.fill([ah0, ah1, ah1, ah0], [z, z, z + h, z + h], color=col, lw=0, alpha=0.12)
ax.plot([ah0, ah1], [z + h, z + h], color=col, lw=0.2, alpha=0.5)
else: # plan
ax.plot([a[ax_h], b[ax_h]], [a[ax_v], b[ax_v]], color=col, lw=0.15, alpha=0.4)
ax.set_title(title)
if ax_v == 1:
ax.set_aspect("equal")
plt.tight_layout()
plt.savefig(out, dpi=120)
return True
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--spec", required=True)
ap.add_argument("--glb", nargs="*", default=[])
ap.add_argument("--out", default="verify_previews.png")
ap.add_argument("--budget-mb", type=float, default=0.6)
ap.add_argument("--strict", action="store_true", help="Exit 3 on invalid GLB budget/structure or missing preview")
a = ap.parse_args()
spec = showcase_schema.normalize_spec(load_spec(Path(a.spec)))
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
report, failed = text_report(spec, [Path(p) for p in a.glb], a.budget_mb)
print(report)
ok = render_previews(spec, Path(a.out))
print(f"\npreviews: {'written ' + a.out if ok else 'skipped (matplotlib not installed)'}")
if a.strict and (failed or not ok):
return 3
return 0
if __name__ == "__main__":
raise SystemExit(main())