feat: harden CAD showcase skill and delivery pipeline
This commit is contained in:
@@ -30,13 +30,14 @@ from __future__ import annotations
|
||||
import argparse
|
||||
import fnmatch
|
||||
import json
|
||||
import math
|
||||
import re
|
||||
import statistics
|
||||
import sys
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
import showcase_schema
|
||||
|
||||
PLAN_TITLE = re.compile(r"平面图$")
|
||||
PLAN_EXCLUDE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
|
||||
OTHER_TITLE = re.compile(r"(立面图|剖面图)$")
|
||||
@@ -60,6 +61,8 @@ def decode_mif(text: str) -> str:
|
||||
return match.group(0)
|
||||
|
||||
return MIF_RE.sub(repl, text)
|
||||
|
||||
|
||||
CN_NUM = {"一": 1, "二": 2, "三": 3, "四": 4, "五": 5, "六": 6, "七": 7, "八": 8, "九": 9, "十": 10}
|
||||
FLOOR_NAME_KEY = [
|
||||
(re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"B{_cn(m.group('n'))}M"),
|
||||
@@ -124,22 +127,30 @@ def parse_args() -> argparse.Namespace:
|
||||
parser.add_argument("--out-config", default="work/frames_config.json")
|
||||
parser.add_argument("--out-report", default="work/frames_report.md")
|
||||
parser.add_argument("--vendor-dir", default="work/vendor")
|
||||
parser.add_argument("--title-regex", default=r"平面图$",
|
||||
help="Plan-frame title pattern; e.g. '(?i)(FLOOR )?PLAN$' for English sets")
|
||||
parser.add_argument(
|
||||
"--title-regex", default=r"平面图$", help="Plan-frame title pattern; e.g. '(?i)(FLOOR )?PLAN$' for English sets"
|
||||
)
|
||||
parser.add_argument("--title-exclude-regex", default=r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
|
||||
parser.add_argument("--title-exclude-layers", default="*图签*,*PUB_TAB*,*TK*,*图框*,*目录*")
|
||||
# Wildcards matter: design institutes prefix layers (13号地块: A_DOTE/A_AXIS),
|
||||
# and an exact "DOTE" token silently zeroes the grid-correlation votes.
|
||||
parser.add_argument("--axis-layers", default="*AXIS*,*DOTE*,*轴线*,*轴网*,S-GRID,*GRID*",
|
||||
help="TArch t3 exports draw plan grids on DOTE; AXIS often only holds detail-sheet stubs")
|
||||
parser.add_argument(
|
||||
"--axis-layers",
|
||||
default="*AXIS*,*DOTE*,*轴线*,*轴网*,S-GRID,*GRID*",
|
||||
help="TArch t3 exports draw plan grids on DOTE; AXIS often only holds detail-sheet stubs",
|
||||
)
|
||||
parser.add_argument("--wall-layers", default="WALL,*WALL*,*墙*")
|
||||
parser.add_argument("--refine-fallback-layers",
|
||||
default="*屋面*,*ROOF*,A-ROOF*|*RAIL*,*栏杆*,STAIR,*FLOR*",
|
||||
help="'|'-separated layer groups tried in order when no walls exist in a frame (e.g. roof plans)")
|
||||
parser.add_argument("--frame-aspect", type=float, default=1.5,
|
||||
help="Initial clip width = pitch * aspect (A1 landscape + margin)")
|
||||
parser.add_argument("--grid-bin", type=float, default=60.0,
|
||||
help="Cluster tolerance (source units) for axis positions and vote bins")
|
||||
parser.add_argument(
|
||||
"--refine-fallback-layers",
|
||||
default="*屋面*,*ROOF*,A-ROOF*|*RAIL*,*栏杆*,STAIR,*FLOR*",
|
||||
help="'|'-separated layer groups tried in order when no walls exist in a frame (e.g. roof plans)",
|
||||
)
|
||||
parser.add_argument(
|
||||
"--frame-aspect", type=float, default=1.5, help="Initial clip width = pitch * aspect (A1 landscape + margin)"
|
||||
)
|
||||
parser.add_argument(
|
||||
"--grid-bin", type=float, default=60.0, help="Cluster tolerance (source units) for axis positions and vote bins"
|
||||
)
|
||||
return parser.parse_args()
|
||||
|
||||
|
||||
@@ -304,8 +315,7 @@ def correlate_shift(ref_pos, src_pos, coarse: float = 500.0, fine: float = 50.0)
|
||||
if not fine_votes:
|
||||
return None, 0.0, 0.0
|
||||
fb = max(fine_votes, key=lambda k: fine_votes[k])
|
||||
sel = [(rp - sp, min(rw, sw)) for rp, rw in ref_pos for sp, sw in src_pos
|
||||
if abs((rp - sp) - fb * fine) <= fine]
|
||||
sel = [(rp - sp, min(rw, sw)) for rp, rw in ref_pos for sp, sw in src_pos if abs((rp - sp) - fb * fine) <= fine]
|
||||
mass = sum(w for _, w in sel)
|
||||
shift = sum(d * w for d, w in sel) / mass if mass else center
|
||||
return shift, coverage, ratio
|
||||
@@ -425,10 +435,12 @@ def main() -> int:
|
||||
vk = ve.dxftype()
|
||||
if vk == "LINE":
|
||||
for p in (ve.dxf.start, ve.dxf.end):
|
||||
xs_fb.append(float(p.x)); ys_fb.append(float(p.y))
|
||||
xs_fb.append(float(p.x))
|
||||
ys_fb.append(float(p.y))
|
||||
elif vk == "LWPOLYLINE":
|
||||
for px, py in ve.get_points("xy"):
|
||||
xs_fb.append(float(px)); ys_fb.append(float(py))
|
||||
xs_fb.append(float(px))
|
||||
ys_fb.append(float(py))
|
||||
except Exception:
|
||||
continue
|
||||
if not xs_fb:
|
||||
@@ -501,19 +513,23 @@ def main() -> int:
|
||||
notes = []
|
||||
refine_groups = [wall_layers] + [
|
||||
[p.strip() for p in group.split(",") if p.strip()]
|
||||
for group in args.refine_fallback_layers.split("|") if group.strip()
|
||||
for group in args.refine_fallback_layers.split("|")
|
||||
if group.strip()
|
||||
]
|
||||
for t in titles:
|
||||
rough = [t["x"] - clip_w * 0.55, t["y"] - pitch * 0.06, t["x"] + clip_w * 0.55, t["y"] + clip_h]
|
||||
if pitch_x and not pitch_y:
|
||||
# row layout: title x may sit anywhere under its frame; centre on it
|
||||
rough = [t["x"] - clip_w * 0.6, t["y"] - clip_h * 0.04, t["x"] + clip_w * 0.6, t["y"] + clip_h]
|
||||
frame_rect = next((r for r in frame_rects
|
||||
if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None)
|
||||
frame_rect = next((r for r in frame_rects if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None)
|
||||
if frame_rect is not None:
|
||||
fw, fh = frame_rect[2] - frame_rect[0], frame_rect[3] - frame_rect[1]
|
||||
rough = [frame_rect[0] + fw * 0.01, frame_rect[1] + fh * 0.01,
|
||||
frame_rect[2] - fw * 0.01, frame_rect[3] - fh * 0.01]
|
||||
rough = [
|
||||
frame_rect[0] + fw * 0.01,
|
||||
frame_rect[1] + fh * 0.01,
|
||||
frame_rect[2] - fw * 0.01,
|
||||
frame_rect[3] - fh * 0.01,
|
||||
]
|
||||
notes.append(f"{t['name']}: frame-block rect used for clip window ({fw / 1000:.1f}x{fh / 1000:.1f} m)")
|
||||
clip = None
|
||||
for group in refine_groups:
|
||||
@@ -524,8 +540,12 @@ def main() -> int:
|
||||
margin = pitch * 0.06
|
||||
clip = [min(xs) - margin, min(ys_) - margin, max(xs) + margin, max(ys_) + margin]
|
||||
if frame_rect is not None: # never swallow the neighbour sheet
|
||||
clip = [max(clip[0], rough[0]), max(clip[1], rough[1]),
|
||||
min(clip[2], rough[2]), min(clip[3], rough[3])]
|
||||
clip = [
|
||||
max(clip[0], rough[0]),
|
||||
max(clip[1], rough[1]),
|
||||
min(clip[2], rough[2]),
|
||||
min(clip[3], rough[3]),
|
||||
]
|
||||
break
|
||||
if clip is None:
|
||||
clip = rough
|
||||
@@ -554,21 +574,24 @@ def main() -> int:
|
||||
f"{t['name']}: auxiliary-titled frame (qualifier '{qualifier}') — likely a "
|
||||
"separate structure or revision sheet; excluded from reference candidacy"
|
||||
)
|
||||
floors.append({
|
||||
"key": floor_key_for(t["name"], used_keys),
|
||||
"name": t["name"],
|
||||
"clip": [round(c, 1) for c in clip],
|
||||
"_vx": cluster_positions(vert, args.grid_bin),
|
||||
"_hy": cluster_positions(horiz, args.grid_bin),
|
||||
"_walls": segments_in(lines, clip, wall_layers),
|
||||
"_aux": bool(qualifier),
|
||||
})
|
||||
floors.append(
|
||||
{
|
||||
"key": floor_key_for(t["name"], used_keys),
|
||||
"name": t["name"],
|
||||
"clip": [round(c, 1) for c in clip],
|
||||
"_vx": cluster_positions(vert, args.grid_bin),
|
||||
"_hy": cluster_positions(horiz, args.grid_bin),
|
||||
"_walls": segments_in(lines, clip, wall_layers),
|
||||
"_aux": bool(qualifier),
|
||||
}
|
||||
)
|
||||
|
||||
def ref_rank(f):
|
||||
# never anchor on auxiliary structures (bike ramps, 人防 revisions...);
|
||||
# prefer a pure ground-floor plan, then the richest grid
|
||||
f1_family = 0 if re.match(r"^F1(_\d+)?$", f["key"]) else 1
|
||||
return (1 if f["_aux"] else 0, f1_family, -(len(f["_vx"]) + len(f["_hy"])))
|
||||
|
||||
reference = sorted(floors, key=ref_rank)[0]
|
||||
|
||||
alignment = []
|
||||
@@ -587,12 +610,9 @@ def main() -> int:
|
||||
# Grid voting failed (no axis geometry in this frame). Try wall-profile
|
||||
# correlation before surrendering to the clip-corner anchor, which is
|
||||
# off by whole bays whenever wall bboxes differ between floors.
|
||||
wdx, covx, ratx = correlate_shift(wall_profile(reference["_walls"], 0),
|
||||
wall_profile(f["_walls"], 0))
|
||||
wdy, covy, raty = correlate_shift(wall_profile(reference["_walls"], 1),
|
||||
wall_profile(f["_walls"], 1))
|
||||
if (wdx is not None and wdy is not None
|
||||
and covx >= 0.35 and covy >= 0.35 and ratx >= 1.5 and raty >= 1.5):
|
||||
wdx, covx, ratx = correlate_shift(wall_profile(reference["_walls"], 0), wall_profile(f["_walls"], 0))
|
||||
wdy, covy, raty = correlate_shift(wall_profile(reference["_walls"], 1), wall_profile(f["_walls"], 1))
|
||||
if wdx is not None and wdy is not None and covx >= 0.35 and covy >= 0.35 and ratx >= 1.5 and raty >= 1.5:
|
||||
f["offset"] = [round(wdx, 1), round(wdy, 1)]
|
||||
alignment.append(
|
||||
f"{f['key']}: wall-correlated (votes x={vx} y={vy}; coverage x={covx:.2f} "
|
||||
@@ -600,8 +620,7 @@ def main() -> int:
|
||||
f"offset={f['offset']}{aux_tag} — verify overlay!"
|
||||
)
|
||||
continue
|
||||
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1),
|
||||
round(reference["clip"][1] - f["clip"][1], 1)]
|
||||
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1), round(reference["clip"][1] - f["clip"][1], 1)]
|
||||
alignment.append(
|
||||
f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']}{aux_tag} — verify overlay!"
|
||||
)
|
||||
@@ -626,34 +645,49 @@ def main() -> int:
|
||||
covers = covered_floor_numbers(f["name"])
|
||||
if covers:
|
||||
for n in covers:
|
||||
config_floors.append({"key": _unique_key(f"F{n}"), "name": f"{n}层({f['name']})",
|
||||
"clip": f["clip"], "offset": f["offset"]})
|
||||
notes.append(f"{f['name']}: multi-floor title expanded to "
|
||||
f"{', '.join('F' + str(n) for n in covers)} (same clip/offset; fill z/height per storey)")
|
||||
config_floors.append(
|
||||
{
|
||||
"key": _unique_key(f"F{n}"),
|
||||
"name": f"{n}层({f['name']})",
|
||||
"clip": f["clip"],
|
||||
"offset": f["offset"],
|
||||
}
|
||||
)
|
||||
notes.append(
|
||||
f"{f['name']}: multi-floor title expanded to "
|
||||
f"{', '.join('F' + str(n) for n in covers)} (same clip/offset; fill z/height per storey)"
|
||||
)
|
||||
else:
|
||||
config_floors.append({"key": _unique_key(f["key"]), "name": f["name"],
|
||||
"clip": f["clip"], "offset": f["offset"]})
|
||||
config_floors.append(
|
||||
{"key": _unique_key(f["key"]), "name": f["name"], "clip": f["clip"], "offset": f["offset"]}
|
||||
)
|
||||
|
||||
config = {
|
||||
"config_version": showcase_schema.CONFIG_VERSION,
|
||||
"project_name": path.stem,
|
||||
"scale": 0.001,
|
||||
"floor_height": 4.2,
|
||||
"_comment": "Review floor order/keys/z/heights (use elevation/section frames). offset stacks each frame onto the reference frame; origin_strategy normalizes globally.",
|
||||
"origin_strategy": "min",
|
||||
"drawings": [{
|
||||
"file": path.name,
|
||||
"floors": config_floors,
|
||||
}],
|
||||
"drawings": [
|
||||
{
|
||||
"file": path.name,
|
||||
"floors": config_floors,
|
||||
}
|
||||
],
|
||||
}
|
||||
out_config = Path(args.out_config)
|
||||
out_config.parent.mkdir(parents=True, exist_ok=True)
|
||||
out_config.write_text(json.dumps(config, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
|
||||
report = [
|
||||
f"# Sheet Frame Detection: {path.name}", "",
|
||||
f"# Sheet Frame Detection: {path.name}",
|
||||
"",
|
||||
f"- plan frames: {len(floors)} (sheet pitch ≈ {round(pitch, 1)})",
|
||||
f"- reference frame: {reference['key']} ({reference['name']})", "",
|
||||
"## Floors", "",
|
||||
f"- reference frame: {reference['key']} ({reference['name']})",
|
||||
"",
|
||||
"## Floors",
|
||||
"",
|
||||
]
|
||||
for f in floors:
|
||||
report.append(f"- `{f['key']}` {f['name']} clip={f['clip']} offset={f['offset']}")
|
||||
@@ -674,8 +708,10 @@ def main() -> int:
|
||||
elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$")
|
||||
votes: Counter = Counter()
|
||||
ladders: dict[str, set] = {o["name"]: set() for o in frames_e}
|
||||
boxes = [(o["name"], o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06,
|
||||
o["x"] + clip_w * 0.6, o["y"] + clip_h) for o in frames_e]
|
||||
boxes = [
|
||||
(o["name"], o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, o["x"] + clip_w * 0.6, o["y"] + clip_h)
|
||||
for o in frames_e
|
||||
]
|
||||
for entity in msp:
|
||||
if entity.dxftype() != "TEXT":
|
||||
continue
|
||||
@@ -701,10 +737,16 @@ def main() -> int:
|
||||
report.append(line)
|
||||
levels = sorted(v for v, n in votes.items() if n >= 2 or (votes[v] >= 1 and -20 < v < 150))
|
||||
if levels:
|
||||
report.extend(["", "## Suggested storey elevations (from 剖面/立面 标高 texts)", "",
|
||||
"- " + ", ".join(f"{v:+.3f}" for v in levels),
|
||||
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
|
||||
"storey z = consecutive major levels, height = difference."])
|
||||
report.extend(
|
||||
[
|
||||
"",
|
||||
"## Suggested storey elevations (from 剖面/立面 标高 texts)",
|
||||
"",
|
||||
"- " + ", ".join(f"{v:+.3f}" for v in levels),
|
||||
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
|
||||
"storey z = consecutive major levels, height = difference.",
|
||||
]
|
||||
)
|
||||
# Uniform-step suggestion: the dominant consecutive difference and
|
||||
# its longest chain. A SUGGESTION for the Agent to verify against
|
||||
# the 剖面 — stair sections beat at half-storey rhythm (2.25 for a
|
||||
@@ -732,12 +774,20 @@ def main() -> int:
|
||||
report.append(
|
||||
f"- suggested storey table: uniform step {step} m x {len(best_chain) - 1} "
|
||||
f"storeys, z {best_chain[0]:+.3f} → {best_chain[-1]:+.3f} — verify against "
|
||||
"剖面/立面 per-frame ladders (podium and machine floors may differ)")
|
||||
"剖面/立面 per-frame ladders (podium and machine floors may differ)"
|
||||
)
|
||||
Path(args.out_report).write_text("\n".join(report) + "\n", encoding="utf-8")
|
||||
print(json.dumps({
|
||||
"config": str(out_config), "report": args.out_report,
|
||||
"floors": [f["key"] for f in floors], "pitch": round(pitch, 1),
|
||||
}, ensure_ascii=False))
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
"config": str(out_config),
|
||||
"report": args.out_report,
|
||||
"floors": [f["key"] for f in floors],
|
||||
"pitch": round(pitch, 1),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
return 0
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user