Files
cad-building-showcase/scripts/detect_sheet_frames.py
zhengwr 06776e4b76 detect_sheet_frames: MTEXT height probe uses char_height
dxf.get("height") raises DXFAttributeError on MTEXT (undefined-for-type);
a short MTEXT reaching the title probe crashed the 27号 1#A detection.
Fixture gains a short MTEXT note.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 22:22:31 +08:00

477 lines
21 KiB
Python

#!/usr/bin/env python3
"""Detect per-floor plan frames inside a multi-sheet DXF and propose extraction config.
Chinese construction sets commonly put ALL sheets of one building into a single
DWG modelspace (plans, elevations, sections, details side by side / stacked).
Treating such a file as one floor superimposes every sheet; treating N files as
N floors scatters plans by their sheet offsets (the "diagonal staircase" bug).
This tool:
1. Finds plan-title TEXTs (一层平面图 / 地下一层平面图 / 屋顶平面图 ...),
filtering out sheet-catalog rows and title-block copies (keeps, per title
name, only the largest-height instances outside excluded layers).
2. Proposes a clip window per plan frame from the sheet pitch, then refines it
to the wall-geometry bounding box inside the frame (drops title blocks,
notes, and neighbouring sheets).
3. Aligns every floor onto a reference floor with a label-free grid
correlation: vertical/horizontal axis-line positions are matched by voting
over candidate translations. Works even when upper floors show partial
grids, and needs no axis-number texts.
4. Emits a ready-to-edit extraction config skeleton plus a Markdown report
(elevation/section frames are listed for floor heights, not as floors).
Usage:
python3 detect_sheet_frames.py --dxf work/dxf_sanitized/xxx.dxf \
--out-config work/frames_config.json --out-report work/frames_report.md
"""
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
PLAN_TITLE = re.compile(r"平面图$")
PLAN_EXCLUDE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
OTHER_TITLE = re.compile(r"(立面图|剖面图)$")
# AutoCAD MIF escapes (\M+5XXXX): CJK titles in pre-Unicode DWGs arrive as
# literal escape sequences, invisible to the 平面图 regexes until decoded.
MIF_RE = re.compile(r"\\M\+([1-5])([0-9A-Fa-f]{4})")
MIF_CODEPAGES = {"1": "cp932", "2": "big5", "3": "cp949", "4": "johab", "5": "gbk"}
def decode_mif(text: str) -> str:
if "\\M+" not in text:
return text
def repl(match: "re.Match[str]") -> str:
value = int(match.group(2), 16)
raw = value.to_bytes(2, "big") if value > 0xFF else value.to_bytes(1, "big")
try:
return raw.decode(MIF_CODEPAGES.get(match.group(1), "gbk"))
except (UnicodeDecodeError, LookupError):
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"),
(re.compile(r"地下(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"B{_cn(m.group('n'))}"),
(re.compile(r"屋顶机房|机房层|电梯机房"), lambda m: "PH"),
(re.compile(r"屋顶|屋面|顶板"), lambda m: "RF"),
(re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层夹层"), lambda m: f"F{_cn(m.group('n'))}M"),
(re.compile(r"(?P<n>[一二三四五六七八九十\d]+)层"), lambda m: f"F{_cn(m.group('n'))}"),
(re.compile(r"地下|底层"), lambda m: "B1"),
]
def _cn(token: str) -> int:
if token.isdigit():
return int(token)
return CN_NUM.get(token, 0)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dxf", required=True)
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-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("--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")
return parser.parse_args()
def import_ezdxf(vendor_dir: Path):
if vendor_dir.exists():
sys.path.insert(0, str(vendor_dir.resolve()))
try:
import ezdxf # type: ignore
from ezdxf import recover # type: ignore
except ImportError as exc:
raise SystemExit(f"Missing ezdxf. pip install --target {vendor_dir} ezdxf") from exc
return ezdxf, recover
def match_any(value: str, patterns: list[str]) -> bool:
upper = value.upper()
return any(fnmatch.fnmatch(upper, p.upper()) for p in patterns)
def entity_text(entity) -> str:
try:
if entity.dxftype() == "TEXT":
return decode_mif(str(entity.dxf.text or "").strip())
if entity.dxftype() == "MTEXT":
return decode_mif(str(entity.plain_text() or "").strip())
except Exception:
pass
return ""
def floor_key_for(name: str, used: set[str]) -> str:
for pattern, keyfn in FLOOR_NAME_KEY:
match = pattern.search(name)
if match:
key = keyfn(match)
break
else:
key = re.sub(r"[^0-9A-Za-z]+", "_", name)[:12] or "FLOOR"
base, i = key, 2
while key in used:
key = f"{base}_{i}"
i += 1
used.add(key)
return key
def cluster_positions(values: list[float], tol: float) -> list[float]:
if not values:
return []
values = sorted(values)
clusters, current = [], [values[0]]
for v in values[1:]:
if v - current[-1] <= tol:
current.append(v)
else:
clusters.append(sum(current) / len(current))
current = [v]
clusters.append(sum(current) / len(current))
return clusters
def vote_translation(ref: list[float], src: list[float], bin_size: float) -> tuple[float | None, int]:
"""Best dx such that {src + dx} matches ref, by histogram voting."""
if not ref or not src:
return None, 0
votes: Counter = Counter()
for r in ref:
for s in src:
votes[round((r - s) / bin_size)] += 1
best_bin, best_votes = votes.most_common(1)[0]
if best_votes < 2:
return None, best_votes
fine = [r - s for r in ref for s in src if abs((r - s) - best_bin * bin_size) <= bin_size]
return statistics.median(fine), best_votes
def segments_in(entities, clip, layers):
out = []
x1, y1, x2, y2 = clip
for layer, sx, sy, ex, ey in entities:
if not match_any(layer, layers):
continue
mx, my = (sx + ex) / 2, (sy + ey) / 2
if x1 <= mx <= x2 and y1 <= my <= y2:
out.append((sx, sy, ex, ey))
return out
def main() -> int:
args = parse_args()
ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
path = Path(args.dxf)
try:
doc = ezdxf.readfile(path)
except ezdxf.DXFError:
doc, _ = recover.readfile(path)
msp = doc.modelspace()
title_excludes = [p.strip() for p in args.title_exclude_layers.split(",") if p.strip()]
axis_layers = [p.strip() for p in args.axis_layers.split(",") if p.strip()]
wall_layers = [p.strip() for p in args.wall_layers.split(",") if p.strip()]
plan_title = re.compile(args.title_regex)
plan_exclude = re.compile(args.title_exclude_regex) if args.title_exclude_regex else None
titles, others = [], []
lines = [] # (layer, sx, sy, ex, ey) for LINE and polyline edges
# Plan grids are not always modelspace lines: TArch exports may wrap each
# frame's axis system in an anonymous block (黄桥: A$C... wrappers holding
# hundreds of DOTE lines while msp has ~8). Expand INSERTs — but only
# blocks that actually contain axis/wall-layer curves (memoized per block
# name), or a sheet full of door/furniture blocks slows the scan for nothing.
expand_patterns = axis_layers + wall_layers
block_memo: dict[str, bool] = {}
def block_has_expandable(name: str, depth: int = 0) -> bool:
if name in block_memo:
return block_memo[name]
if depth > 3 or name not in doc.blocks:
return False
block_memo[name] = False # cycle guard
found = False
for be in doc.blocks.get(name):
bkind = be.dxftype()
if bkind in {"LINE", "LWPOLYLINE"} and match_any(str(be.dxf.layer), expand_patterns):
found = True
break
if bkind == "INSERT" and block_has_expandable(str(be.dxf.name), depth + 1):
found = True
break
block_memo[name] = found
return found
def collect_insert_lines(insert, depth: int = 0) -> None:
if depth > 3:
return
try:
virtual = list(insert.virtual_entities())
except Exception:
return
for ve in virtual:
vkind = ve.dxftype()
if vkind == "LINE":
d = ve.dxf
if match_any(str(d.layer), expand_patterns):
lines.append((str(d.layer), float(d.start.x), float(d.start.y), float(d.end.x), float(d.end.y)))
elif vkind == "LWPOLYLINE":
layer = str(ve.dxf.layer)
if not match_any(layer, expand_patterns):
continue
try:
pts = [(float(px), float(py)) for px, py in ve.get_points("xy")]
except Exception:
continue
for a, b in zip(pts, pts[1:]):
lines.append((layer, a[0], a[1], b[0], b[1]))
elif vkind == "INSERT":
collect_insert_lines(ve, depth + 1)
for entity in msp:
kind = entity.dxftype()
if kind == "INSERT":
if block_has_expandable(str(entity.dxf.name)):
collect_insert_lines(entity)
continue
if kind in {"TEXT", "MTEXT"}:
content = entity_text(entity)
if not content or len(content) > 40:
continue
try:
pos = entity.dxf.insert
x, y = float(pos.x), float(pos.y)
except Exception:
continue
# MTEXT stores char_height; asking MTEXT for "height" raises
# DXFAttributeError (only undefined-for-type attributes raise).
try:
height_attr = "char_height" if kind == "MTEXT" else "height"
height = float(entity.dxf.get(height_attr, 0) or 0)
except Exception:
height = 0.0
layer = str(entity.dxf.layer)
if plan_title.search(content) and not (plan_exclude and plan_exclude.search(content)):
if not match_any(layer, title_excludes):
titles.append({"name": content, "x": x, "y": y, "h": height, "layer": layer})
elif OTHER_TITLE.search(content) and not match_any(layer, title_excludes):
others.append({"name": content, "x": x, "y": y, "h": height})
elif kind == "LINE":
d = entity.dxf
lines.append((str(d.layer), float(d.start.x), float(d.start.y), float(d.end.x), float(d.end.y)))
elif kind == "LWPOLYLINE":
try:
pts = [(float(px), float(py)) for px, py in entity.get_points("xy")]
except Exception:
continue
layer = str(entity.dxf.layer)
for a, b in zip(pts, pts[1:]):
lines.append((layer, a[0], a[1], b[0], b[1]))
if not titles:
print(json.dumps({"error": "no plan titles found"}, ensure_ascii=False))
return 1
# Keep, per title name, only instances close to that name's max height
# (drops catalog rows and small title-block copies that survive layer excludes).
by_name: dict[str, list[dict]] = defaultdict(list)
for t in titles:
by_name[t["name"]].append(t)
filtered = []
for name, items in by_name.items():
max_h = max(t["h"] for t in items)
filtered.extend(t for t in items if t["h"] >= max_h * 0.85)
titles = sorted(filtered, key=lambda t: (-t["y"], t["x"]))
# Sheets stack vertically (column pitch from y gaps) or run in rows
# (pitch from x gaps of same-row titles) — support both.
ys = sorted({t["y"] for t in titles}, reverse=True)
y_gaps = [a - b for a, b in zip(ys, ys[1:]) if 20000 < a - b < 400000]
pitch_y = statistics.median(y_gaps) if y_gaps else None
xs_rows: dict[int, list[float]] = defaultdict(list)
for t in titles:
xs_rows[round(t["y"] / 4000)].append(t["x"])
x_gaps = []
for row in xs_rows.values():
row = sorted(row)
x_gaps.extend(b - a for a, b in zip(row, row[1:]) if 8000 < b - a < 400000)
pitch_x = statistics.median(x_gaps) if x_gaps else None
pitch = pitch_y or pitch_x or 98100.0
clip_w = (pitch_x * 0.97) if pitch_x else pitch * args.frame_aspect
clip_h = (pitch_y * 0.97) if pitch_y else (pitch_x or 98100.0) * 2.2
used_keys: set[str] = set()
floors = []
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 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]
clip = None
for group in refine_groups:
found = segments_in(lines, rough, group)
if len(found) >= 10:
xs = [v for s in found for v in (s[0], s[2])]
ys_ = [v for s in found for v in (s[1], s[3])]
margin = pitch * 0.06
clip = [min(xs) - margin, min(ys_) - margin, max(xs) + margin, max(ys_) + margin]
break
if clip is None:
clip = rough
notes.append(f"{t['name']}: no wall/roof geometry in rough clip; using pitch-based clip")
# Axis geometry lives OUTSIDE the wall-tight clip (axis-number stubs sit
# beyond the facade), so collect grid candidates in an expanded window.
axis_margin = pitch * 0.16
axis_clip = [clip[0] - axis_margin, clip[1] - axis_margin, clip[2] + axis_margin, clip[3] + axis_margin]
axes = segments_in(lines, axis_clip, axis_layers)
min_grid_len = pitch * 0.25
# Some sets (13号地块) draw NO through grid lines at all — only ~0.8m
# axis ticks. A tick's position still fingerprints the grid, so accept
# short strictly-axis-parallel stubs alongside full-span lines.
tick_min, tick_max = pitch * 0.004, pitch * 0.05
vert, horiz = [], []
for sx, sy, ex, ey in axes:
dx, dy = abs(ex - sx), abs(ey - sy)
if dx < 2.0 and (dy > min_grid_len or tick_min < dy < tick_max):
vert.append((sx + ex) / 2)
elif dy < 2.0 and (dx > min_grid_len or tick_min < dx < tick_max):
horiz.append((sy + ey) / 2)
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),
})
def ref_rank(f):
return (0 if f["key"] == "F1" else 1, -(len(f["_vx"]) + len(f["_hy"])))
reference = sorted(floors, key=ref_rank)[0]
alignment = []
for f in floors:
if f is reference:
f["offset"] = [0.0, 0.0]
alignment.append(f"{f['key']}: reference frame")
continue
dx, vx = vote_translation(reference["_vx"], f["_vx"], args.grid_bin)
dy, vy = vote_translation(reference["_hy"], f["_hy"], args.grid_bin)
if dx is not None and dy is not None and vx >= 3 and vy >= 3:
f["offset"] = [round(dx, 1), round(dy, 1)]
alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}")
else:
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']} — verify overlay!"
)
for f in floors:
f.pop("_vx"), f.pop("_hy")
config = {
"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": [{k: f[k] for k in ("key", "name", "clip", "offset")} for f in 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"- plan frames: {len(floors)} (sheet pitch ≈ {round(pitch, 1)})",
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']}")
report.extend(["", "## Alignment", ""])
report.extend(f"- {n}" for n in alignment)
report.extend(f"- note: {n}" for n in notes)
if others:
seen = set()
report.extend(["", "## Elevation/Section frames (for floor heights; not floors)", ""])
for o in sorted(others, key=lambda o: -o.get("h", 0)):
key = o["name"]
if key in seen:
continue
seen.add(key)
report.append(f"- {o['name']} @ ({round(o['x'])}, {round(o['y'])})")
# Storey-elevation suggestions: 标高 texts (e.g. 8.100) inside section/
# elevation frames, clustered. Feed floors[].z/height from these.
elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$")
votes: Counter = Counter()
boxes = [(o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, o["x"] + clip_w * 0.6, o["y"] + clip_h)
for o in others]
for entity in msp:
if entity.dxftype() != "TEXT":
continue
content = entity_text(entity)
if not content or not elev_re.match(content):
continue
try:
pos = entity.dxf.insert
except Exception:
continue
if any(b[0] <= pos.x <= b[2] and b[1] <= pos.y <= b[3] for b in boxes):
votes[round(float(content), 3)] += 1
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."])
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))
return 0
if __name__ == "__main__":
raise SystemExit(main())