#!/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[一二三四五六七八九十\d]+)层夹层"), lambda m: f"B{_cn(m.group('n'))}M"), (re.compile(r"地下(?P[一二三四五六七八九十\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[一二三四五六七八九十\d]+)层夹层"), lambda m: f"F{_cn(m.group('n'))}M"), (re.compile(r"(?P[一二三四五六七八九十\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 # A plan title is "pure" when everything before 平面图 is floor vocabulary # (numbers, 地下/夹层/标准层/机房/屋顶...). Any other prefix (非机动坡道/ # 无障碍住房改造/人防...) marks an auxiliary structure or a revision sheet: # its grid belongs to a DIFFERENT building, so it must never become the # alignment reference (27号 2#: the bike-ramp frame grabbed F1 and every # tower frame went WEAK against it). PURE_TITLE_RE = re.compile( r"[0-9一二三四五六七八九十百零两FBM#\s层地下夹标准机房屋顶跃阁避难设备转换裙塔、,,~~至\-—.]*平面图$" ) def title_qualifier(name: str) -> str: """Chars before the floor-word core; nonempty => auxiliary-titled frame.""" m = PURE_TITLE_RE.search(name) return name if m is None else name[: m.start()] def wall_profile(segs, axis: int, axis_tol: float = 2.0, min_len: float = 400.0): """Length-weighted axis positions of straight walls. axis=0: vertical segments -> x positions; axis=1: horizontal -> y. Wall positions fingerprint the plan even when NO axis geometry exists in the frame (13号 tower / 27号 2#): correlating profiles between frames recovers the true translation where clip-corner anchoring is off by whole bays (wall bbox min-corner varies with balconies). Defaults are mm-scale; pass axis_tol/min_len in meters for spec-space use. """ out = [] for sx, sy, ex, ey in segs: dx, dy = abs(ex - sx), abs(ey - sy) if axis == 0 and dx < axis_tol and dy > min_len: out.append(((sx + ex) / 2, dy)) elif axis == 1 and dy < axis_tol and dx > min_len: out.append(((sy + ey) / 2, dx)) return out def correlate_shift(ref_pos, src_pos, coarse: float = 500.0, fine: float = 50.0): """Best d such that {src + d} overlays {ref}, weighted-histogram voting. Returns (shift, coverage, ratio): coverage = matched mass / min side mass, ratio = peak mass / best rival peak >=3 coarse bins away. Both gate acceptance so unrelated structures (a bike ramp vs the tower) refuse to correlate instead of snapping to a spurious peak. """ if len(ref_pos) < 4 or len(src_pos) < 4: return None, 0.0, 0.0 ref_h: dict[int, float] = defaultdict(float) src_h: dict[int, float] = defaultdict(float) for p, w in ref_pos: ref_h[round(p / coarse)] += w for p, w in src_pos: src_h[round(p / coarse)] += w votes: dict[int, float] = defaultdict(float) for rb, rw in ref_h.items(): for sb, sw in src_h.items(): votes[rb - sb] += min(rw, sw) if not votes: return None, 0.0, 0.0 best = max(votes, key=lambda k: votes[k]) best_mass = votes[best] + 0.5 * (votes.get(best - 1, 0.0) + votes.get(best + 1, 0.0)) rival = max((m for d, m in votes.items() if abs(d - best) >= 3), default=0.0) total = min(sum(w for _, w in ref_pos), sum(w for _, w in src_pos)) coverage = best_mass / total if total > 0 else 0.0 ratio = best_mass / rival if rival > 0 else float("inf") # refine around the coarse peak with exact position pairs center = best * coarse fine_votes: dict[int, float] = defaultdict(float) for rp, rw in ref_pos: for sp, sw in src_pos: d = rp - sp if abs(d - center) <= coarse: fine_votes[round(d / fine)] += min(rw, sw) 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] 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 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 in {"TEXT", "MTEXT"}: # Cached-XREF sheets keep their plan TITLES inside the block # (13号: msp = INSERT stubs only) — classify them like msp text. classify_text(ve, vkind) elif vkind == "INSERT": collect_insert_lines(ve, depth + 1) def classify_text(entity, kind) -> None: content = entity_text(entity) if not content or len(content) > 40: return try: pos = entity.dxf.insert x, y = float(pos.x), float(pos.y) except Exception: return # 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}) # Title-block frame INSERTs (A0_V1 / A0+0.5_V1 / *图框* …) carry the TRUE # sheet rect. Pitch-sized windows halve elongated sheets (13号 加长A0 held # both towers in one frame and F1 lost a tower) — prefer the block rect. frame_block_re = re.compile(r"(?i)(^A[0-4](\+[0-9.]+)?([_\-]|$))|图框|图签|(^TK([_\-]|$))") frame_rects: list[tuple[float, float, float, float]] = [] for entity in msp.query("INSERT"): name = str(entity.dxf.name) if not frame_block_re.search(name): continue xs_fb: list[float] = [] ys_fb: list[float] = [] try: for ve in entity.virtual_entities(): 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)) elif vk == "LWPOLYLINE": for px, py in ve.get_points("xy"): xs_fb.append(float(px)); ys_fb.append(float(py)) except Exception: continue if not xs_fb: continue w, h = max(xs_fb) - min(xs_fb), max(ys_fb) - min(ys_fb) if w >= 20000 and h >= 15000 and 0.3 <= (w / h) <= 4.0: # plausible sheet frame_rects.append((min(xs_fb), min(ys_fb), max(xs_fb), max(ys_fb))) 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"}: classify_text(entity, kind) 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 # A couple of stray same-row detail titles can fabricate an x-pitch far # smaller than the sheet height (27号 1#B: 非机动坡道 row → pitch_x≈15.8k vs # pitch_y≈59k). A real 2D sheet grid has pitch_x ≈ sheet width, never much # below pitch_y — distrust the fabricated one or clip windows shrink and # drop whole building wings. if pitch_x and pitch_y and pitch_x < pitch_y * 0.7: pitch_x = 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] 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] 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: 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] 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])] break if clip is None: clip = rough if frame_rect is None: 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) qualifier = title_qualifier(t["name"]) if qualifier: notes.append( 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), }) 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 = [] 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) aux_tag = " [auxiliary-titled frame]" if f["_aux"] else "" 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']}{aux_tag}") continue # 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): f["offset"] = [round(wdx, 1), round(wdy, 1)] alignment.append( f"{f['key']}: wall-correlated (votes x={vx} y={vy}; coverage x={covx:.2f} " f"y={covy:.2f}, ratio x={min(ratx, 99):.1f} y={min(raty, 99):.1f}), " 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)] alignment.append( f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']}{aux_tag} — verify overlay!" ) for f in floors: f.pop("_vx"), f.pop("_hy"), f.pop("_walls"), f.pop("_aux") 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())