#!/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 import showcase_schema 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"} CAD_TEXT_FORMAT_RE = re.compile(r"\\[LlOoKk]|%%[UuOoKk]") # Revit/AutoCAD exports often keep the only reliable floor identity in block # names (for example ``...-首层平面图``) while the visible title text lives in # the title block at paper coordinates. Keep the vocabulary deliberately # narrow: arbitrary INSERT names ending in 平面图 must not become floor frames. FLOOR_TOKEN_RE = re.compile( r"机房小屋面|机房屋面|" r"地下[一二三四五六七八九十\d]+层夹层|" r"地下[一二三四五六七八九十\d]+层|" r"[一二三四五六七八九十\d]+层夹层|" r"[一二三四五六七八九十\d]+层|" r"首层|底层|夹层|屋顶层|屋顶|屋面|机房层|电梯机房" ) 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) def normalize_cad_text(text: str) -> str: """Decode CJK escapes and remove common TEXT/MTEXT decoration codes.""" text = decode_mif(text) text = CAD_TEXT_FORMAT_RE.sub("", text) return text.replace("\\P", " ").strip() def floor_titles_from_label(label: str) -> list[str]: """Expand a Chinese plan label into one normalized title per floor. ``主楼首层_二层平面图`` becomes ``主楼首层平面图`` and ``主楼二层平面图``. The building qualifier is retained for the report; floor identity is normalized separately by :func:`floor_base_key`. """ label = normalize_cad_text(label).replace("_", "、") if label.endswith(("机房小屋面", "机房屋面")): return [label] if not label.endswith("平面图") or len(label) > 50: return [] head = label[:-3] matches = list(FLOOR_TOKEN_RE.finditer(head)) if not matches: return [label] qualifier = re.sub(r"[、,,\s]+$", "", head[: matches[0].start()]) # A long prefix is normally an element/family name, not a building label. if len(qualifier) > 12: qualifier = "" return [f"{qualifier}{match.group(0)}平面图" for match in matches] def floor_titles_from_insert_name(name: str) -> list[str]: """Return floor labels encoded in the final component of an INSERT name.""" suffix = normalize_cad_text(name).rsplit("-", 1)[-1].strip() return floor_titles_from_label(suffix) 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"首层"), lambda m: "F1"), (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"), # A bare 夹层 in Chinese architectural sets conventionally means the # mezzanine above the first floor. Keep the key sortable and consistent # with explicit 一层夹层 rather than emitting a nonstandard bare ``M``. (re.compile(r"夹层"), lambda m: "F1M"), ] def _cn(token: str) -> int: """Chinese numeral (1-99, incl. compounds 十一/二十/二十一) or digits to int.""" if token.isdigit(): return int(token) if not token: return 0 if "十" in token: tens, _, ones = token.partition("十") t = CN_NUM.get(tens, 0) if tens else 1 o = CN_NUM.get(ones, 0) if ones else 0 if tens and t == 0: return 0 return t * 10 + o return CN_NUM.get(token, 0) def covered_floor_numbers(name: str) -> list[int]: """Floors covered by a multi-floor plan title, else []. 四、六、八层平面图 -> [4,6,8]; 十一至十四层平面图 -> [11,12,13,14]. One frame standing for N storeys is the norm in Chinese sets — hand-copying N config entries is exactly where floors got silently lost (13号 b2). """ if "地下" in name or "夹层" in name: return [] m = re.search(r"(?P[一二三四五六七八九十\d]+(?:(?:[、,,]|[至~~\-—])[一二三四五六七八九十\d]+)+)层", name) if not m: return [] nums: list[int] = [] for part in re.split(r"[、,,]", m.group("seq")): rng = re.split(r"[至~~\-—]", part) if len(rng) == 2: a, b = _cn(rng[0]), _cn(rng[1]) if not (0 < a < b <= 99 and b - a <= 40): return [] nums.extend(range(a, b + 1)) elif len(rng) == 1: v = _cn(rng[0]) if v <= 0: return [] nums.append(v) else: return [] return nums if len(nums) > 1 else [] 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*,*TTLB*,*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 normalize_cad_text(str(entity.dxf.text or "")) if entity.dxftype() == "MTEXT": return normalize_cad_text(str(entity.plain_text() or "")) except Exception: pass return "" def floor_base_key(name: str) -> str: for pattern, keyfn in FLOOR_NAME_KEY: match = pattern.search(name) if match: return keyfn(match) return re.sub(r"[^0-9A-Za-z]+", "_", name)[:12] or "FLOOR" def floor_key_for(name: str, used: set[str]) -> str: key = floor_base_key(name) 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 plan_geometry_components(entities, layers): """Connected raster components of wall/grid geometry as frame bboxes. Revit exports may flatten two plans side by side and leave their visible titles in the paper title block. Long wall/grid segments still form two disconnected spatial nets. Rasterizing only those structural layers is deliberately simpler and safer than clustering every annotation entity. """ selected = [] lengths = [] for layer, sx, sy, ex, ey in entities: if not match_any(layer, layers): continue length = math.hypot(ex - sx, ey - sy) if length < 500.0: continue selected.append((sx, sy, ex, ey, length)) lengths.append(length) if not selected: return [] cell = max(200.0, min(3000.0, statistics.median(lengths) * 0.75)) occupied = set() for sx, sy, ex, ey, length in selected: steps = max(1, math.ceil(length / cell)) for i in range(steps + 1): t = i / steps occupied.add((round((sx + (ex - sx) * t) / cell), round((sy + (ey - sy) * t) / cell))) components = [] while occupied: seed = occupied.pop() stack = [seed] cells = [seed] while stack: cx, cy = stack.pop() for nx in range(cx - 1, cx + 2): for ny in range(cy - 1, cy + 2): if (nx, ny) in occupied: occupied.remove((nx, ny)) stack.append((nx, ny)) cells.append((nx, ny)) if len(cells) < 10: continue xs = [c[0] for c in cells] ys = [c[1] for c in cells] bbox = [min(xs) * cell, min(ys) * cell, (max(xs) + 1) * cell, (max(ys) + 1) * cell] if bbox[2] - bbox[0] >= cell * 3 and bbox[3] - bbox[1] >= cell * 3: components.append({"bbox": bbox, "cells": len(cells), "cell": cell}) return sorted(components, key=lambda item: item["cells"], reverse=True) def robust_point_bbox(points): """2-98% bbox, trimming sparse title-block/origin outliers.""" if len(points) < 5: return None xs = sorted(p[0] for p in points) ys = sorted(p[1] for p in points) lo = max(0, int(len(points) * 0.02)) hi = min(len(points) - 1, int(len(points) * 0.98)) return [xs[lo], ys[lo], xs[hi], ys[hi]] # 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 insert_title_points: dict[str, list[tuple[float, float]]] = defaultdict(list) insert_title_labels: dict[str, Counter] = defaultdict(Counter) insert_title_lines: dict[str, list[tuple[str, float, float, float, float]]] = defaultdict(list) # 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. refine_patterns = [ pattern.strip() for group in args.refine_fallback_layers.split("|") for pattern in group.split(",") if pattern.strip() ] # Roof-only cached blocks can have no WALL/GRID layer at all. They still # need expansion so roof/railing/floor geometry can seed the frame clip. expand_patterns = axis_layers + wall_layers + refine_patterns 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": name = str(entity.dxf.name) expanded_start = len(lines) if block_has_expandable(name): collect_insert_lines(entity) expanded = lines[expanded_start:] insert_titles = floor_titles_from_insert_name(name) if insert_titles: try: pos = entity.dxf.insert point = (float(pos.x), float(pos.y)) except Exception: point = None for insert_title in insert_titles: key = floor_base_key(insert_title) insert_title_labels[key][insert_title] += 1 if point is not None: insert_title_points[key].append(point) # A large plan/XREF block carries its own transformed wall # geometry. Small family blocks (doors, railings, tags) # are useful as point votes but must not define the clip. if len(expanded) >= 50: insert_title_lines[key].extend(expanded) 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])) # Some Revit exports have no usable plan-title text outside the title # block. Hundreds of INSERT names still end in ``-首层平面图`` / # ``-二层平面图``. Turn those repeated, spatially distributed names into # frame seeds. This is deterministic evidence from the DWG, not a guess # from the filename. component_layers = wall_layers + axis_layers + refine_patterns geometry_components = plan_geometry_components(lines, component_layers) # Assign each floor identity to the geometry component containing the most # same-floor INSERT positions. Greedy by confidence keeps adjacent floors # from both selecting the same plan when Revit reuses a few family blocks # across views. component_choice = {} ranked_keys = [] for key in insert_title_labels: points = insert_title_points.get(key, []) expanded = insert_title_lines.get(key, []) evidence = points if len(points) >= 5 else [((sx + ex) / 2, (sy + ey) / 2) for _, sx, sy, ex, ey in expanded] scores = [] for index, component in enumerate(geometry_components): x1, y1, x2, y2 = component["bbox"] pad = component["cell"] * 2 score = sum(1 for x, y in evidence if x1 - pad <= x <= x2 + pad and y1 - pad <= y <= y2 + pad) scores.append((score, component["cells"], index)) scores.sort(reverse=True) best = scores[0][0] if scores else 0 second = scores[1][0] if len(scores) > 1 else 0 ranked_keys.append((best - second, best, key, scores)) used_components = set() preserve_component_union_keys = set() for _, best, key, scores in sorted(ranked_keys, reverse=True): if best <= 0: continue choice = next((index for score, _, index in scores if score > 0 and index not in used_components), None) if choice is not None: component_choice[key] = geometry_components[choice] used_components.add(choice) if len(insert_title_labels) == 1: only_key = next(iter(insert_title_labels)) if len(geometry_components) == 1: component_choice[only_key] = geometry_components[0] elif len(insert_title_lines.get(only_key, [])) >= 50: # One logical roof floor can contain several disconnected nets # (main roof + machine-room roofs). Keep their expanded union. component_choice.pop(only_key, None) preserve_component_union_keys.add(only_key) for key, labels in insert_title_labels.items(): points = insert_title_points.get(key, []) expanded = insert_title_lines.get(key, []) strong_insert_evidence = len(points) >= 5 or len(expanded) >= 50 or key in component_choice if strong_insert_evidence: titles = [t for t in titles if floor_base_key(t["name"]) != key] elif any(floor_base_key(t["name"]) == key for t in titles): continue label = labels.most_common(1)[0][0] clip_hint = None component = component_choice.get(key) if component is not None: clip_hint = list(component["bbox"]) point_bbox = robust_point_bbox(points) if len(insert_title_labels) == 1 and point_bbox is not None: union = [ min(clip_hint[0], point_bbox[0]), min(clip_hint[1], point_bbox[1]), max(clip_hint[2], point_bbox[2]), max(clip_hint[3], point_bbox[3]), ] if union != clip_hint: clip_hint = union preserve_component_union_keys.add(key) elif len(points) >= 5: clip_hint = robust_point_bbox(points) elif len(expanded) >= 50: xs = [v for _, sx, _, ex, _ in expanded for v in (sx, ex)] ys_ = [v for _, _, sy, _, ey in expanded for v in (sy, ey)] if xs and ys_: clip_hint = [min(xs), min(ys_), max(xs), max(ys_)] if clip_hint is not None: width = max(clip_hint[2] - clip_hint[0], 1.0) height = max(clip_hint[3] - clip_hint[1], 1.0) margin = max(3000.0, min(max(width, height) * 0.08, 15000.0)) clip_hint = [clip_hint[0] - margin, clip_hint[1] - margin, clip_hint[2] + margin, clip_hint[3] + margin] x = (clip_hint[0] + clip_hint[2]) / 2 y = (clip_hint[1] + clip_hint[3]) / 2 elif points: x = statistics.median(p[0] for p in points) y = statistics.median(p[1] for p in points) else: continue titles.append( { "name": label, "x": x, "y": y, "h": 1.0, "layer": "INSERT_NAME", "_clip_hint": clip_hint, "_preserve_component_union": key in preserve_component_union_keys, # Only a small number of large top-level view wrappers can be # used as root INSERT selectors. Repeated family/component # blocks also end in the view name in many Revit exports; using # their suffix as a root filter drops unrelated wall/column # INSERTs from the same floor. **({"_include_block_names": [f"*-{label}"]} if 1 <= len(points) <= 3 and len(expanded) >= 50 else {}), } ) 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.get("_clip_hint") or [ 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 and not t.get("_clip_hint"): # 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 = rough if t.get("_preserve_component_union") else None if clip is 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" ) floor = { "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), } if t.get("_include_block_names"): floor["include_block_names"] = list(t["_include_block_names"]) floors.append(floor) 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") # Identical/near-identical inferred clips for different keys are not two # trustworthy frames. Keep the skeleton for inspection, but say plainly # that cross-floor overlay must resolve which view belongs in the stack. for i, left in enumerate(floors): for right in floors[i + 1 :]: ax1, ay1, ax2, ay2 = left["clip"] bx1, by1, bx2, by2 = right["clip"] overlap = max(0.0, min(ax2, bx2) - max(ax1, bx1)) * max(0.0, min(ay2, by2) - max(ay1, by1)) smaller = min(max((ax2 - ax1) * (ay2 - ay1), 1.0), max((bx2 - bx1) * (by2 - by1), 1.0)) if overlap / smaller >= 0.8: left_blocks = set(left.get("include_block_names", [])) right_blocks = set(right.get("include_block_names", [])) if left_blocks and right_blocks and left_blocks.isdisjoint(right_blocks): notes.append( f"OVERLAPPING clips separated by Revit view identity: {left['key']} uses " f"{sorted(left_blocks)}, {right['key']} uses {sorted(right_blocks)}" ) else: notes.append( f"AMBIGUOUS overlapping inferred frames: {left['key']} and {right['key']} " f"overlap {overlap / smaller:.0%}; resolve by cross-floor overlay and keep/discard " "explicitly — do not model both blindly" ) # Expand multi-floor titles (四、六、八层 / 十一至十四层) into one config # entry per storey sharing the frame's clip/offset — hand-copying N entries # is where floors silently vanished (13号 b2 F11-F16). z/height stay with # the Agent: fill them from the storey-elevation evidence, do not guess. config_floors: list[dict] = [] def _unique_key(key: str) -> str: base, i = key, 2 while any(cf["key"] == key for cf in config_floors): key = f"{base}_{i}" i += 1 return key for f in floors: 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"], **({"include_block_names": f["include_block_names"]} if f.get("include_block_names") else {}), } ) 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"], **({"include_block_names": f["include_block_names"]} if f.get("include_block_names") else {}), } ) view_block_patterns = sorted( {pattern for floor in config_floors for pattern in floor.get("include_block_names", [])} ) 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", **({"expand_block_names": view_block_patterns} if view_block_patterns else {}), "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"- 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() frames_e: list[dict] = [] for o in sorted(others, key=lambda o: -o.get("h", 0)): if o["name"] in seen: continue seen.add(o["name"]) frames_e.append(o) # Storey-elevation evidence: 标高 texts (e.g. 8.100) inside section/ # elevation frames, collected PER FRAME (aggregated lists mix stair # half-landings from 楼梯剖面 into the storey ladder — 27号 1#A lesson). 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 ] 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 for name, x1, y1, x2, y2 in boxes: if x1 <= pos.x <= x2 and y1 <= pos.y <= y2: v = round(float(content), 3) ladders[name].add(v) votes[v] += 1 report.extend(["", "## Elevation/Section frames (for floor heights; not floors)", ""]) for o in frames_e: line = f"- {o['name']} @ ({round(o['x'])}, {round(o['y'])})" vals = sorted(ladders.get(o["name"], ())) if vals: shown = ", ".join(f"{v:+.3f}" for v in vals[:40]) line += f" ladder: {shown}" + (" …" if len(vals) > 40 else "") 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.", ] ) # 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 # 4.5 m storey), so per-frame ladders above are the ground truth. majors = [v for v in levels if -0.5 <= v <= 200] diff_votes: Counter = Counter() for a, b in zip(majors, majors[1:]): d = round(b - a, 2) if 2.5 <= d <= 6.5: diff_votes[d] += 1 if diff_votes: step = diff_votes.most_common(1)[0][0] best_chain: list[float] = [] for v0 in majors: chain, cur = [v0], v0 while True: nxt = [w for w in majors if abs(w - (cur + step)) <= 0.06] if not nxt: break cur = nxt[0] chain.append(cur) if len(chain) > len(best_chain): best_chain = chain if len(best_chain) >= 4: 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)" ) 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())