feat: harden CAD showcase skill and delivery pipeline

This commit is contained in:
2026-07-10 09:21:13 +08:00
parent a6856f903d
commit 8b1b1d5e89
53 changed files with 5405 additions and 1327 deletions

View File

@@ -13,6 +13,8 @@ from collections import defaultdict
from pathlib import Path
from typing import Any
import showcase_schema
DEFAULT_CATEGORIES = {
"walls": {"label": "墙体", "color": "#d4cbb8", "width": 0.20},
@@ -78,16 +80,15 @@ def import_ezdxf(vendor_dir: Path):
from ezdxf import recover # type: ignore
except ImportError as exc:
raise SystemExit(
"Missing dependency: ezdxf. Install locally with:\n"
f" python3 -m pip install --target {vendor_dir} ezdxf"
f"Missing dependency: ezdxf. Install locally with:\n python3 -m pip install --target {vendor_dir} ezdxf"
) from exc
return ezdxf, recover
def read_json(path: Path | None) -> dict[str, Any]:
if not path:
return {}
return json.loads(path.read_text(encoding="utf-8"))
return showcase_schema.normalize_config({})
return showcase_schema.normalize_config(json.loads(path.read_text(encoding="utf-8")))
def read_doc(path: Path, ezdxf, recover):
@@ -405,10 +406,7 @@ def polyline_points(entity) -> list[tuple[float, float]]:
if entity.dxftype() == "LWPOLYLINE":
return [(float(x), float(y)) for x, y in entity.get_points("xy")]
if entity.dxftype() == "POLYLINE":
return [
(float(vertex.dxf.location.x), float(vertex.dxf.location.y))
for vertex in entity.vertices
]
return [(float(vertex.dxf.location.x), float(vertex.dxf.location.y)) for vertex in entity.vertices]
return []
@@ -489,10 +487,7 @@ def collect_raw_segments(
recover,
) -> tuple[dict[str, dict[str, Any]], list[dict[str, Any]]]:
patterns = layer_patterns(config)
default_widths = {
key: float(value.get("width", 0.1))
for key, value in DEFAULT_CATEGORIES.items()
}
default_widths = {key: float(value.get("width", 0.1)) for key, value in DEFAULT_CATEGORIES.items()}
default_widths.update({key: float(value) for key, value in config.get("default_widths", {}).items()})
scale = float(config.get("scale", config.get("scale_to_meters", 0.001)))
min_source_length = float(config.get("min_source_length", 1.0))
@@ -731,7 +726,9 @@ def generated_footprint(segments: dict[str, list[dict[str, Any]]], config: dict[
}
def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offset_tol: float = 0.30, gap_tol: float = 3.6) -> list[dict[str, Any]]:
def merge_collinear(
segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offset_tol: float = 0.30, gap_tol: float = 3.6
) -> list[dict[str, Any]]:
"""Merge collinear, near-touching segments into continuous spans.
CAD curtain walls are often drawn as sparse panel/mullion segments with gaps;
@@ -742,10 +739,14 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
groups: dict[tuple, list] = {}
keep: list[dict[str, Any]] = []
for s in segs:
a = s["start"]; b = s["end"]
dx = b[0] - a[0]; dy = b[1] - a[1]; length = math.hypot(dx, dy)
a = s["start"]
b = s["end"]
dx = b[0] - a[0]
dy = b[1] - a[1]
length = math.hypot(dx, dy)
if length < 1e-6:
keep.append(s); continue
keep.append(s)
continue
ang = math.atan2(dy, dx) % math.pi
akey = round(ang / math.radians(angle_tol_deg))
nx, ny = -dy / length, dx / length
@@ -757,8 +758,9 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
dirx, diry = -ny, nx
offv = a0[0] * nx + a0[1] * ny
intervals = []
for (a, b, *_rest) in items:
t0 = a[0] * dirx + a[1] * diry; t1 = b[0] * dirx + b[1] * diry
for a, b, *_rest in items:
t0 = a[0] * dirx + a[1] * diry
t1 = b[0] * dirx + b[1] * diry
intervals.append([min(t0, t1), max(t0, t1)])
intervals.sort()
merged = [intervals[0][:]]
@@ -768,11 +770,15 @@ def merge_collinear(segs: list[dict[str, Any]], angle_tol_deg: float = 6.0, offs
else:
merged.append([lo, hi])
for lo, hi in merged:
out.append({
"start": [round(offv * nx + lo * dirx, 6), round(offv * ny + lo * diry, 6)],
"end": [round(offv * nx + hi * dirx, 6), round(offv * ny + hi * diry, 6)],
"width": width, "layer": layer, "source_type": "merged",
})
out.append(
{
"start": [round(offv * nx + lo * dirx, 6), round(offv * ny + lo * diry, 6)],
"end": [round(offv * nx + hi * dirx, 6), round(offv * ny + hi * diry, 6)],
"width": width,
"layer": layer,
"source_type": "merged",
}
)
return out
@@ -783,14 +789,7 @@ def _cap_floor_group(fk: str, config: dict[str, Any] | None = None) -> str:
(fnmatch patterns, first match wins). Defaults reproduce the A208 case:
AUX_* prefix = annex tower, B1/B1M = basement, everything else = main.
"""
for pattern, group in (config or {}).get("cap_groups", []):
if fnmatch.fnmatch(fk.upper(), str(pattern).upper()):
return str(group)
if fk.startswith("AUX_"):
return "AUX"
if fk in {"B1", "B1M"}:
return "BASE"
return "MAIN"
return showcase_schema.floor_group(fk, config)
def _shapely_union(polys: list):
@@ -862,7 +861,9 @@ def compute_caps(floors: dict[str, Any], config: dict[str, Any]) -> None:
fl.setdefault("caps", []).append({"z": round(ftop, 6), "polygons": polys})
def drop_isolated_clusters(segments: dict[str, list[dict[str, Any]]], config: dict[str, Any], floor_key: str) -> dict[str, list[dict[str, Any]]]:
def drop_isolated_clusters(
segments: dict[str, list[dict[str, Any]]], config: dict[str, Any], floor_key: str
) -> dict[str, list[dict[str, Any]]]:
"""Drop tiny segment clusters far away from the floor's main mass.
Sheet legends and title blocks draw window/door symbols with REAL geometry
@@ -925,8 +926,10 @@ def drop_isolated_clusters(segments: dict[str, list[dict[str, Any]]], config: di
seg = items[idx][2]
(x1, y1), (x2, y2) = seg["start"], seg["end"]
total += math.hypot(x2 - x1, y2 - y1)
bx[0] = min(bx[0], x1, x2); bx[1] = min(bx[1], y1, y2)
bx[2] = max(bx[2], x1, x2); bx[3] = max(bx[3], y1, y2)
bx[0] = min(bx[0], x1, x2)
bx[1] = min(bx[1], y1, y2)
bx[2] = max(bx[2], x1, x2)
bx[3] = max(bx[3], y1, y2)
return total, bx
stats = {root: cluster_stats(idx_list) for root, idx_list in clusters.items()}
@@ -1051,7 +1054,9 @@ def finalize_spec(
if key not in floor_data:
continue
floor = floor_data[key]
segments: dict[str, list[dict[str, Any]]] = {category: [] for category in DEFAULT_CATEGORIES if category != "slab"}
segments: dict[str, list[dict[str, Any]]] = {
category: [] for category in DEFAULT_CATEGORIES if category != "slab"
}
xs: list[float] = []
ys: list[float] = []
for category, raw_segments in floor["segments_source"].items():
@@ -1131,14 +1136,12 @@ def finalize_spec(
file=sys.stderr,
)
categories = {
key: {"label": value["label"], "color": value["color"]}
for key, value in DEFAULT_CATEGORIES.items()
}
categories = {key: {"label": value["label"], "color": value["color"]} for key, value in DEFAULT_CATEGORIES.items()}
for key, value in config.get("categories", {}).items():
categories.setdefault(key, {}).update(value)
return {
"schema_version": showcase_schema.SCHEMA_VERSION,
"project": {
"name": config.get("project_name", "CAD Building Showcase"),
"description": config.get("description", "建筑 CAD 生成的 Web 展示模型"),
@@ -1164,9 +1167,19 @@ def main() -> int:
if not dxf_dir.exists():
raise SystemExit(f"DXF folder not found: {dxf_dir}")
config = read_json(Path(args.config) if args.config else None)
try:
config = showcase_schema.validate_config(config, dxf_dir)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
floor_data, extraction_report = collect_raw_segments(dxf_dir, config, ezdxf, recover)
spec = finalize_spec(floor_data, config, extraction_report, dxf_dir)
try:
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(spec, ensure_ascii=False, indent=2), encoding="utf-8")