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

@@ -14,6 +14,7 @@ from typing import Any
sys.path.insert(0, str(Path(__file__).resolve().parent))
import derive_showcase_spec as derive # noqa: E402
import showcase_schema # noqa: E402
HIGH_RISK_TYPES = {
@@ -48,8 +49,8 @@ def parse_args() -> argparse.Namespace:
nargs="*",
default=None,
help="detect_sheet_frames out-config JSON(s): enables the frame-ledger gate "
"(every detected plan frame must be in the extraction config or listed "
"in config discarded_frames with a reason)",
"(every detected plan frame must be in the extraction config or listed "
"in config discarded_frames with a reason)",
)
return parser.parse_args()
@@ -87,10 +88,7 @@ def block_layer_unit_lengths(doc, name: str, max_chord: float, max_depth: int, d
for layer, length in block_layer_unit_lengths(doc, inner_name, max_chord, max_depth, depth + 1).items():
totals[layer] += length * factor
else:
length = sum(
segment_length_source(segment)
for segment in derive.entity_segments(inner, max_chord)
)
length = sum(segment_length_source(segment) for segment in derive.entity_segments(inner, max_chord))
if length > 0:
totals[derive.entity_layer(inner)] += length
result = dict(totals)
@@ -141,7 +139,8 @@ def inspect_entity(
"supported_length": supported_length,
"sample": sample,
"high_risk": dxftype in HIGH_RISK_TYPES,
"insert_name": block_name or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
"insert_name": block_name
or (str(entity.dxf.name) if dxftype == "INSERT" and entity.dxf.hasattr("name") else ""),
}
@@ -168,15 +167,17 @@ def spec_counts(spec: dict[str, Any]) -> dict[str, dict[str, int]]:
categories = [key for key in spec.get("categories", {}) if key != "slab"]
result = {}
for floor_key, floor in spec.get("floors", {}).items():
result[floor_key] = {
category: len(floor.get("segments", {}).get(category, []))
for category in categories
}
result[floor_key] = {category: len(floor.get("segments", {}).get(category, [])) for category in categories}
return result
def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path,
frames: list[dict[str, Any]] | None = None) -> dict[str, Any]:
def audit(
dxf_dir: Path,
config: dict[str, Any],
spec: dict[str, Any],
vendor_dir: Path,
frames: list[dict[str, Any]] | None = None,
) -> dict[str, Any]:
ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0))
@@ -232,9 +233,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
sx = abs(float(source_entity.dxf.get("xscale", 1.0) or 1.0))
sy = abs(float(source_entity.dxf.get("yscale", 1.0) or 1.0))
factor = (sx + sy) / 2.0
unit_lengths = block_layer_unit_lengths(
doc, insert_name, max_chord, max_block_depth
)
unit_lengths = block_layer_unit_lengths(doc, insert_name, max_chord, max_block_depth)
for inner_layer, unit_length in unit_lengths.items():
inner_length = unit_length * factor
if inner_length <= 0:
@@ -343,9 +342,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
"coverage": {
"supported_length_meters": round(total_supported * scale, 3),
"classified_supported_length_meters": round(classified_supported * scale, 3),
"supported_length_coverage": round(classified_supported / total_supported, 4)
if total_supported
else None,
"supported_length_coverage": round(classified_supported / total_supported, 4) if total_supported else None,
"block_locked_length_meters": round(block_locked_total * scale, 3),
"block_locked_classifiable_length_meters": round(block_locked_classifiable * scale, 3),
"block_captured_classified_length_meters": round(captured_from_blocks * scale, 3),
@@ -390,9 +387,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
xs = [v for s in walls for v in (s["start"][0], s["end"][0])]
ys = [v for s in walls for v in (s["start"][1], s["end"][1])]
size = max(max(xs) - min(xs), max(ys) - min(ys))
groups[derive._cap_floor_group(fk, config)].append(
(fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size)
)
groups[derive._cap_floor_group(fk, config)].append((fk, (min(xs) + max(xs)) / 2, (min(ys) + max(ys)) / 2, size))
worst: tuple[float, str] | None = None
for grp, items in groups.items():
if len(items) < 2:
@@ -402,7 +397,10 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for j in range(i + 1, len(items)):
dist = math.hypot(items[i][1] - items[j][1], items[i][2] - items[j][2])
if dist > limit and (worst is None or dist > worst[0]):
worst = (dist, f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})")
worst = (
dist,
f"{grp}: {items[i][0]} vs {items[j][0]} centers {round(dist, 1)} m apart (limit {round(limit, 1)})",
)
if worst:
return {
"name": "floors_aligned",
@@ -432,16 +430,15 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
for grp, keys in by_group.items():
if len(keys) < 2:
continue
ref_key = max(keys, key=lambda k: sum(
math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_key = max(keys, key=lambda k: sum(math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_x = wall_profile(wall_segs[ref_key], 0, axis_tol=0.02, min_len=0.4)
ref_y = wall_profile(wall_segs[ref_key], 1, axis_tol=0.02, min_len=0.4)
def zero_cov(ref_prof, prof, tol: float = 0.25) -> float:
total = sum(w for _, w in prof)
if total <= 0:
return 0.0
matched = sum(w for p, w in prof
if any(abs(p - rp) <= tol for rp, _ in ref_prof))
matched = sum(w for p, w in prof if any(abs(p - rp) <= tol for rp, _ in ref_prof))
return matched / total
for fk in keys:
@@ -455,8 +452,7 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
# let any small profile "match" somewhere: 27号 1#A PH)
if shift is not None and zero_cov(ref_prof, prof) >= 0.7 * cov:
continue
if (shift is not None and cov >= 0.45 and ratio >= 1.5
and abs(shift) > 1.0):
if shift is not None and cov >= 0.45 and ratio >= 1.5 and abs(shift) > 1.0:
return {
"name": "floors_aligned",
"status": "FAIL",
@@ -475,28 +471,40 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
}
def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any],
frames: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]:
def evaluate_gates(
report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any], frames: list[dict[str, Any]] | None = None
) -> list[dict[str, Any]]:
"""Hard checks that must pass before 3D generation.
A gate FAIL means the extraction is known-incomplete in a way that high
coverage numbers cannot excuse; fix the config (block expansion, layer
mapping, source re-export) and re-run instead of accepting the model.
"""
gates: list[dict[str, Any]] = [floors_alignment_gate(spec, config)]
gates: list[dict[str, Any]] = [
{
"name": "all_config_drawings_present",
"status": "PASS",
"detail": "Every configured source drawing exists and passed config validation.",
},
{
"name": "unique_floor_keys",
"status": "PASS",
"detail": "Configured floor keys are unique.",
},
{
"name": "every_floor_nonempty",
"status": "PASS",
"detail": "Every floor contains segments, footprint polygons, or caps.",
},
floors_alignment_gate(spec, config),
]
spec_glazing_segments = sum(
counts.get("glazing", 0) for counts in report["spec_counts"].values()
)
spec_glazing_segments = sum(counts.get("glazing", 0) for counts in report["spec_counts"].values())
locked_glazing_meters = sum(
item["supported_length_meters"]
for item in report["block_locked_layers"]
if item["category"] == "glazing"
item["supported_length_meters"] for item in report["block_locked_layers"] if item["category"] == "glazing"
)
glazing_named_blocks = [
name
for name in report["top_insert_names"]
if derive.match_patterns(name, derive.GLAZING_BLOCK_PATTERNS)
name for name in report["top_insert_names"] if derive.match_patterns(name, derive.GLAZING_BLOCK_PATTERNS)
]
glazing_evidence = locked_glazing_meters >= GATE_GLAZING_MIN_METERS or bool(glazing_named_blocks)
if not glazing_evidence:
@@ -524,7 +532,7 @@ def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[st
gates.append(
{
"name": "no_annotation_layers_classified",
"status": "WARN" if annotation_classified else "PASS",
"status": "FAIL" if annotation_classified else "PASS",
"detail": (
f"Annotation/identification layers classified as geometry: {', '.join(annotation_classified[:5])}. "
"These are tags, not elements; exclude them."
@@ -586,8 +594,7 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
`"discarded_frames": [{"name": ..., "reason": ...}]`.
"""
if not frames:
return {"name": "frame_ledger", "status": "SKIP",
"detail": "No --frames given; frame ledger not checked."}
return {"name": "frame_ledger", "status": "SKIP", "detail": "No --frames given; frame ledger not checked."}
discarded = {str(d.get("name", "")) for d in config.get("discarded_frames", [])}
cfg_by_file: dict[str, list[dict[str, Any]]] = {}
for drawing in config.get("drawings", []) or []:
@@ -604,10 +611,7 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
clip = frame.get("clip")
if name in discarded:
continue
if clip and any(
fl.get("clip") and _rect_overlap_ratio(clip, fl["clip"]) >= 0.3
for fl in cfg_floors
):
if clip and any(fl.get("clip") and _rect_overlap_ratio(clip, fl["clip"]) >= 0.3 for fl in cfg_floors):
continue
unaccounted.append(f"{file}: {frame.get('key', '?')} {name}")
if unaccounted:
@@ -621,8 +625,11 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
"floors/wings vanish — use them or discard them WITH a reason."
),
}
return {"name": "frame_ledger", "status": "PASS",
"detail": f"All {total} detected plan frames are used or explicitly discarded."}
return {
"name": "frame_ledger",
"status": "PASS",
"detail": f"All {total} detected plan frames are used or explicitly discarded.",
}
def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -635,8 +642,11 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
"""
declared = config.get("declared_areas_m2")
if not declared:
return {"name": "area_declared", "status": "SKIP",
"detail": "No declared_areas_m2 in config; area cross-check not requested."}
return {
"name": "area_declared",
"status": "SKIP",
"detail": "No declared_areas_m2 in config; area cross-check not requested.",
}
tol = float(config.get("declared_area_tolerance", 0.15))
problems = []
for key, want in declared.items():
@@ -649,19 +659,26 @@ def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str
if got <= 0:
problems.append(f"{key}: no footprint area in spec")
elif abs(got - want) / want > tol:
problems.append(f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)")
problems.append(
f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)"
)
if problems:
return {
"name": "area_declared",
"status": "FAIL",
"detail": ("Footprint area disagrees with the declared evidence: "
+ "; ".join(problems)
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."),
"detail": (
"Footprint area disagrees with the declared evidence: "
+ "; ".join(problems)
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."
),
}
return {"name": "area_declared", "status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values."}
return {
"name": "area_declared",
"status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values.",
}
def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
@@ -672,20 +689,29 @@ def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str,
"""
expected = config.get("expected_storeys_above_ground")
if expected is None:
return {"name": "storey_count", "status": "SKIP",
"detail": "No expected_storeys_above_ground in config; count cross-check not requested."}
return {
"name": "storey_count",
"status": "SKIP",
"detail": "No expected_storeys_above_ground in config; count cross-check not requested.",
}
import re as _re
actual = sum(1 for k in spec.get("floors", {}) if _re.fullmatch(r"F\d+", str(k)))
if actual != int(expected):
return {
"name": "storey_count",
"status": "FAIL",
"detail": (f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."),
"detail": (
f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."
),
}
return {"name": "storey_count", "status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count."}
return {
"name": "storey_count",
"status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count.",
}
def agent_questions(unclassified_layers: list[dict], high_risk: Counter, insert_names: Counter) -> list[str]:
@@ -727,11 +753,15 @@ def markdown(report: dict[str, Any]) -> str:
f"- Classified supported length: `{coverage['classified_supported_length_meters']}` m",
f"- Supported-length coverage: `{coverage['supported_length_coverage']}` "
"(modelspace linework only — block-locked geometry is NOT in this denominator)",
*([
f"- CLIP-SCOPED coverage: `{coverage['clipped_supported_length_coverage']}` over "
f"`{coverage['clipped_supported_length_meters']}` m inside floor clips — "
"on multi-frame sheets judge extraction by THIS number, not the file-global one"
] if coverage.get("clipped_supported_length_coverage") is not None else []),
*(
[
f"- CLIP-SCOPED coverage: `{coverage['clipped_supported_length_coverage']}` over "
f"`{coverage['clipped_supported_length_meters']}` m inside floor clips — "
"on multi-frame sheets judge extraction by THIS number, not the file-global one"
]
if coverage.get("clipped_supported_length_coverage") is not None
else []
),
f"- Block-locked geometry: `{coverage['block_locked_length_meters']}` m total, "
f"`{coverage['block_locked_classifiable_length_meters']}` m classifiable, "
f"`{coverage['block_captured_classified_length_meters']}` m captured into the spec",
@@ -765,14 +795,12 @@ def markdown(report: dict[str, Any]) -> str:
lines.extend(["", "## Classified Layers", ""])
for layer in report["classified_layers"][:30]:
lines.append(
f"- `{layer['layer']}`: `{layer['categories']}`, "
f"classified length `{layer['classified_length_meters']}` m"
f"- `{layer['layer']}`: `{layer['categories']}`, classified length `{layer['classified_length_meters']}` m"
)
lines.extend(["", "## Files", ""])
for item in report["files"]:
lines.append(
f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, "
f"high-risk `{item['high_risk_types']}`"
f"- `{item['file']}`: coverage `{item['supported_length_coverage']}`, high-risk `{item['high_risk_types']}`"
)
return "\n".join(lines)
@@ -781,6 +809,12 @@ def main() -> int:
args = parse_args()
config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
try:
config = showcase_schema.validate_config(config, Path(args.dxf_dir))
showcase_schema.validate_spec(spec)
except showcase_schema.ValidationFailure as exc:
print(str(exc), file=sys.stderr)
return 3
frames = None
if args.frames:
frames = [json.loads(Path(p).read_text(encoding="utf-8")) for p in args.frames]