fix: detect Revit floor frames deterministically
This commit is contained in:
4
SKILL.md
4
SKILL.md
@@ -52,7 +52,7 @@ The Agent owns interpretation. Scripts are tools for evidence and repeatable exe
|
||||
|
||||
The pipeline is designed so a first pass either succeeds or STOPS at a loud gate. Do not hand over a model unless every line below has evidence (a report line, a gate status, or an image):
|
||||
|
||||
1. Read report clean: every `Warnings` entry resolved. `multi_frame_sheet` -> ran `detect_sheet_frames.py` and used its clip/offset config; `cached_xref_content` -> the XREF content is CACHED as in-file block definitions, expand blocks (≈bind) instead of asking for a re-export; `likely_xref_shell` (no cached content) -> user re-exported with XREFs bound.
|
||||
1. Read report clean: every `Warnings` entry resolved by the Agent. `multi_frame_sheet` -> ran `detect_sheet_frames.py` and used its clip/offset config; `cached_xref_content` -> the XREF content is CACHED as in-file block definitions, expand blocks (≈bind) instead of asking for a re-export; `likely_xref_shell` (no cached content) -> user re-exported with XREFs bound. Detection warnings are internal work signals, not a human approval queue: only ask the user when the drawing itself lacks the source/XREF or two materially different interpretations remain after all deterministic checks.
|
||||
2. Frame alignment proven: detect report shows `grid-aligned, votes x>=3 y>=3` per floor (any `WEAK grid match` floor was verified on its overlay SVG).
|
||||
3. Audit exit code 0, and gates `floors_aligned` / `glazing_captured` / `no_annotation_layers_classified` all PASS. `floors_aligned` also cross-checks every floor's wall profile against the group's reference floor (a strong correlation peak at a non-zero shift = "self-consistent but misplaced", the 13号 F3 错槽 pattern that envelope centers cannot see). Never pass `--no-strict-gates` to proceed.
|
||||
Leak gates (SKIP unless armed — arm them on every new project, they are the cross-evidence net): `--frames <detect out-config>` arms `frame_ledger` (every detected plan frame must be used by the config or listed in `discarded_frames` with a reason — silently ignored frames are where wings vanish); config `declared_areas_m2` arms `area_declared` (model footprint area vs 经济技术指标表/标注, ±15% default — 1#B lost half the building and only the site plan showed it); config `expected_storeys_above_ground` arms `storey_count` (vs 总图 `22F` labels / elevation ladder).
|
||||
@@ -84,7 +84,7 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate
|
||||
- Use `references/pipeline.md` and `references/building_spec_schema.md`.
|
||||
- Map CAD layers to normalized categories: `walls`, `glazing`, `roof`, `columns`, `beams`, `railings`, `doors`, `detail_lines`, `floor_lines`, and `grid`.
|
||||
- Identify one drawing per floor or split sheets that contain multiple floor plans side by side.
|
||||
- MULTI-FRAME SHEETS (the common Chinese pattern: one DWG per building holding ALL its plans + elevations + sections stacked in modelspace): run `scripts/detect_sheet_frames.py` on the sanitized DXF. It finds `XX平面图` title texts (filtering catalog rows and title-block copies; titles INSIDE cached-xref blocks are scanned too), prefers title-block frame INSERTs (`A0_V1`/`A0+0.5_V1`/`*图框*`… world bboxes) as clip windows — pitch-sized windows halve elongated sheets (13号 加长A0 held two towers in one frame) — refines each clip to the wall bbox inside it, and computes per-floor `offset`s by voting-based grid-line correlation (label-free; TArch grids live on layer `DOTE`, not `AXIS`). When a frame has NO axis geometry at all, it falls back to wall-profile correlation (length-weighted wall-position histograms, x and y independently, coverage+peak-ratio gated) before surrendering to the clip-corner anchor — clip corners track wall bboxes and drift by whole bays when balconies differ. Auxiliary-titled frames (非机动坡道/无障碍改造/人防…) are flagged and never become the alignment reference (a bike-ramp frame once anchored a whole tower to nothing). Never model such a file as one floor (all sheets superimpose) and never stack frames without offsets (floors staircase away diagonally — the classic broken output). Multi-floor titles (四、六、八层平面图 / 十一至十四层平面图) are expanded into one config entry per storey sharing the frame's clip/offset — hand-copying N entries is where floors silently vanished (13号 b2). Read its report: `WEAK grid match` floors need overlay verification; `wall-correlated` floors deserve one overlay check too; elevation/section frames are listed for floor heights with a PER-FRAME `ladder:` of DIM_ELEV values plus a `suggested storey table` line (uniform-step chain) — the suggestion is evidence, not a decision: fill `z`/`height` yourself after checking the 剖面 ladder (stair sections beat at half-storey rhythm; podium/machine floors differ). Frame clips can swallow the sheet above/below (refine bbox includes between-sheet strips): if a floor's footprint depth is ~2-4x its siblings, cluster its wall y-midpoints and cut the clip band to the plan's own row.
|
||||
- MULTI-FRAME SHEETS (the common Chinese pattern: one DWG per building holding ALL its plans + elevations + sections stacked in modelspace): run `scripts/detect_sheet_frames.py` on the sanitized DXF. It finds `XX平面图` title texts (filtering catalog rows and title-block copies; titles INSIDE cached-xref blocks are scanned too), and for Revit exports it automatically falls back to floor identities encoded in INSERT names when title-block text sits at paper coordinates. It prefers title-block frame INSERTs (`A0_V1`/`A0+0.5_V1`/`*图框*`… world bboxes) as clip windows — pitch-sized windows halve elongated sheets (13号 加长A0 held two towers in one frame) — refines each clip to the wall bbox inside it, and computes per-floor `offset`s by voting-based grid-line correlation (label-free; TArch grids live on layer `DOTE`, not `AXIS`). When a frame has NO axis geometry at all, it falls back to wall-profile correlation (length-weighted wall-position histograms, x and y independently, coverage+peak-ratio gated) before surrendering to the clip-corner anchor — clip corners track wall bboxes and drift by whole bays when balconies differ. Auxiliary-titled frames (非机动坡道/无障碍改造/人防…) are flagged and never become the alignment reference (a bike-ramp frame once anchored a whole tower to nothing). Never model such a file as one floor (all sheets superimpose) and never stack frames without offsets (floors staircase away diagonally — the classic broken output). Multi-floor titles (四、六、八层平面图 / 十一至十四层平面图) are expanded into one config entry per storey sharing the frame's clip/offset — hand-copying N entries is where floors silently vanished (13号 b2). Read its report: `WEAK grid match` floors need overlay verification; `wall-correlated` floors deserve one overlay check too. `AMBIGUOUS overlapping inferred frames` must be resolved by the CAD Agent with cross-floor overlays and an explicit keep/discard reason in the config; it is not a user-facing soft warning and must not be modeled twice blindly. Elevation/section frames are listed for floor heights with a PER-FRAME `ladder:` of DIM_ELEV values plus a `suggested storey table` line (uniform-step chain) — the suggestion is evidence, not a decision: fill `z`/`height` yourself after checking the 剖面 ladder (stair sections beat at half-storey rhythm; podium/machine floors differ). Frame clips can swallow the sheet above/below (refine bbox includes between-sheet strips): if a floor's footprint depth is ~2-4x its siblings, cluster its wall y-midpoints and cut the clip band to the plan's own row.
|
||||
- Align floors by structural grid or repeated control axes. Use millimeters-to-meters scale (`0.001`) unless the report proves the CAD is already in meters.
|
||||
- Floor keys: `floor_sort_key` treats a leading `B` as basement (sorted below ground). Do not invent keys like `B1F` for "Building 1 Floor" — use per-building specs instead, and set explicit `floor_order` whenever keys are nonstandard.
|
||||
- When CAD linework has enough exterior/interior boundary signal, enable generated footprints for floor slabs and roof caps. Prefer footprint polygons over rectangular floor bounds for visual/digital-twin presentation. Footprints are hulled PER proximity cluster (`footprint_cluster_linkage`, 6 m): a floor holding two disconnected masses (13号 twin towers in one floor key) gets separate hulls — a single concave hull would bridge the void and `use_footprint_slabs` would lay plates across it; genuinely linked wings stay merged because the 连廊 walls connect the clusters.
|
||||
|
||||
@@ -11,7 +11,7 @@ import os
|
||||
import shutil
|
||||
import subprocess
|
||||
import sys
|
||||
from collections import Counter
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
@@ -244,6 +244,16 @@ import re as _re
|
||||
|
||||
PLAN_TITLE_RE = _re.compile(r"平面图$")
|
||||
PLAN_TITLE_EXCLUDE_RE = _re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
|
||||
PLAN_TITLE_EXCLUDE_LAYERS = ("*图签*", "*PUB_TAB*", "*TTLB*", "*TK*", "*图框*", "*目录*")
|
||||
CAD_TEXT_FORMAT_RE = _re.compile(r"\\[LlOoKk]|%%[UuOoKk]")
|
||||
FLOOR_TOKEN_RE = _re.compile(
|
||||
r"机房小屋面|机房屋面|"
|
||||
r"地下[一二三四五六七八九十\d]+层夹层|"
|
||||
r"地下[一二三四五六七八九十\d]+层|"
|
||||
r"[一二三四五六七八九十\d]+层夹层|"
|
||||
r"[一二三四五六七八九十\d]+层|"
|
||||
r"首层|底层|夹层|屋顶层|屋顶|屋面|机房层|电梯机房"
|
||||
)
|
||||
|
||||
# AutoCAD MIF escapes (\M+5XXXX): CJK text in pre-Unicode DWGs survives
|
||||
# DXF conversion as literal escape sequences, so title matching must decode
|
||||
@@ -267,27 +277,78 @@ def decode_mif(text: str) -> str:
|
||||
return MIF_RE.sub(repl, text)
|
||||
|
||||
|
||||
def normalize_cad_text(text: str) -> str:
|
||||
text = CAD_TEXT_FORMAT_RE.sub("", decode_mif(text))
|
||||
return text.replace("\\P", " ").strip()
|
||||
|
||||
|
||||
def floor_identities(label: str) -> list[tuple[str, str]]:
|
||||
"""``(building qualifier, floor)`` identities from labels/INSERT names."""
|
||||
label = normalize_cad_text(label).replace("_", "、")
|
||||
if label.endswith(("机房小屋面", "机房屋面")):
|
||||
return [("", "PH")]
|
||||
if not label.endswith("平面图") or len(label) > 50:
|
||||
return []
|
||||
head = label[:-3]
|
||||
matches = list(FLOOR_TOKEN_RE.finditer(head))
|
||||
tokens = [match.group(0) for match in matches]
|
||||
qualifier = _re.sub(r"[、,,\s]+$", "", head[:matches[0].start()]) if matches else ""
|
||||
if len(qualifier) > 12:
|
||||
qualifier = ""
|
||||
out = []
|
||||
for token in tokens:
|
||||
if token in {"屋顶层", "屋顶", "屋面"}:
|
||||
out.append("RF")
|
||||
elif token in {"机房小屋面", "机房屋面", "机房层", "电梯机房"}:
|
||||
out.append("PH")
|
||||
elif token == "首层":
|
||||
out.append("F1")
|
||||
elif token == "底层":
|
||||
out.append("B1")
|
||||
elif token == "夹层":
|
||||
out.append("F1M")
|
||||
else:
|
||||
out.append(token)
|
||||
return [(qualifier, identity) for identity in out] or [("", label)]
|
||||
|
||||
|
||||
def count_plan_titles(entities) -> int:
|
||||
"""Distinct plan-frame titles in modelspace (multi-frame sheet detector)."""
|
||||
seen = set()
|
||||
"""Distinct plan floors from visible titles and Revit INSERT-name suffixes."""
|
||||
floor_qualifiers: dict[str, set[str]] = defaultdict(set)
|
||||
for entity in entities:
|
||||
kind = entity.dxftype()
|
||||
if kind == "INSERT":
|
||||
try:
|
||||
suffix = str(entity.dxf.name).rsplit("-", 1)[-1]
|
||||
except Exception:
|
||||
continue
|
||||
for qualifier, floor in floor_identities(suffix):
|
||||
floor_qualifiers[floor].add(qualifier)
|
||||
continue
|
||||
if kind not in {"TEXT", "MTEXT"}:
|
||||
continue
|
||||
try:
|
||||
layer = str(entity.dxf.layer)
|
||||
except Exception:
|
||||
layer = ""
|
||||
if any(fnmatch.fnmatch(layer.upper(), pattern.upper()) for pattern in PLAN_TITLE_EXCLUDE_LAYERS):
|
||||
continue
|
||||
try:
|
||||
text = str(entity.dxf.text if kind == "TEXT" else entity.plain_text() or "").strip()
|
||||
except Exception:
|
||||
continue
|
||||
text = decode_mif(text)
|
||||
text = normalize_cad_text(text)
|
||||
if not text or len(text) > 40:
|
||||
continue
|
||||
if PLAN_TITLE_RE.search(text) and not PLAN_TITLE_EXCLUDE_RE.search(text):
|
||||
try:
|
||||
pos = entity.dxf.insert
|
||||
seen.add((text, round(float(pos.x) / 5000), round(float(pos.y) / 5000)))
|
||||
except Exception:
|
||||
seen.add((text, 0, 0))
|
||||
return len(seen)
|
||||
for qualifier, floor in floor_identities(text):
|
||||
floor_qualifiers[floor].add(qualifier)
|
||||
# Revit repeats the same floor suffix across hundreds of family INSERTs;
|
||||
# a sheet-title block may add ``主楼`` while families remain unqualified.
|
||||
# Count that as one frame, but retain two genuinely different qualified
|
||||
# buildings that both contain (say) an F1 plan in the same modelspace.
|
||||
return sum(max(1, len({q for q in qualifiers if q}))
|
||||
for qualifiers in floor_qualifiers.values())
|
||||
|
||||
|
||||
def insert_block_content(doc, entities) -> list[dict]:
|
||||
|
||||
@@ -45,6 +45,20 @@ OTHER_TITLE = re.compile(r"(立面图|剖面图)$")
|
||||
# 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:
|
||||
@@ -60,15 +74,58 @@ def decode_mif(text: str) -> str:
|
||||
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<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: "PH"),
|
||||
(re.compile(r"屋顶|屋面|顶板"), lambda m: "RF"),
|
||||
(re.compile(r"首层"), lambda m: "F1"),
|
||||
(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"),
|
||||
# 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"),
|
||||
]
|
||||
|
||||
|
||||
@@ -127,7 +184,7 @@ def parse_args() -> argparse.Namespace:
|
||||
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*,*图框*,*目录*")
|
||||
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*",
|
||||
@@ -162,22 +219,24 @@ def match_any(value: str, patterns: list[str]) -> bool:
|
||||
def entity_text(entity) -> str:
|
||||
try:
|
||||
if entity.dxftype() == "TEXT":
|
||||
return decode_mif(str(entity.dxf.text or "").strip())
|
||||
return normalize_cad_text(str(entity.dxf.text or ""))
|
||||
if entity.dxftype() == "MTEXT":
|
||||
return decode_mif(str(entity.plain_text() or "").strip())
|
||||
return normalize_cad_text(str(entity.plain_text() or ""))
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def floor_key_for(name: str, used: set[str]) -> str:
|
||||
def floor_base_key(name: 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"
|
||||
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}"
|
||||
@@ -228,6 +287,69 @@ def segments_in(entities, clip, layers):
|
||||
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:
|
||||
@@ -235,7 +357,7 @@ def segments_in(entities, clip, layers):
|
||||
# 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层地下夹标准机房屋顶跃阁避难设备转换裙塔、,,~~至\-—.]*平面图$"
|
||||
r"[0-9一二三四五六七八九十百零两FBM#\s层地下夹标准机房屋顶面跃阁避难设备转换裙塔、,,~~至\-—.]*平面图$"
|
||||
)
|
||||
|
||||
|
||||
@@ -329,13 +451,23 @@ def main() -> int:
|
||||
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.
|
||||
expand_patterns = axis_layers + wall_layers
|
||||
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:
|
||||
@@ -440,8 +572,28 @@ def main() -> int:
|
||||
for entity in msp:
|
||||
kind = entity.dxftype()
|
||||
if kind == "INSERT":
|
||||
if block_has_expandable(str(entity.dxf.name)):
|
||||
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)
|
||||
@@ -457,6 +609,102 @@ def main() -> int:
|
||||
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})
|
||||
|
||||
if not titles:
|
||||
print(json.dumps({"error": "no plan titles found"}, ensure_ascii=False))
|
||||
return 1
|
||||
@@ -504,8 +752,8 @@ def main() -> int:
|
||||
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:
|
||||
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
|
||||
@@ -515,18 +763,19 @@ def main() -> int:
|
||||
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
|
||||
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:
|
||||
@@ -609,6 +858,23 @@ def main() -> int:
|
||||
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:
|
||||
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
|
||||
|
||||
@@ -148,6 +148,77 @@ def make_multiframe_dxf(path: Path, mif_titles: bool = False) -> None:
|
||||
doc.saveas(path)
|
||||
|
||||
|
||||
def make_revit_named_frames_dxf(path: Path) -> None:
|
||||
"""Two side-by-side plans whose floor identity exists only in INSERT names.
|
||||
|
||||
Mirrors Revit exports where visible titles are decoration-coded text on
|
||||
G-ANNO-TTLB at paper coordinates, while door/window family block names end
|
||||
in ``-首层平面图`` or ``-二层平面图`` at the real model coordinates.
|
||||
"""
|
||||
doc = ezdxf.new("R2010", setup=True)
|
||||
for layer in ("I-WALL", "S-GRID", "A-DOOR", "G-ANNO-TTLB"):
|
||||
doc.layers.add(layer)
|
||||
msp = doc.modelspace()
|
||||
|
||||
for title, ox in (("首层平面图", 0.0), ("二层平面图", 70000.0)):
|
||||
outline = [((0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
|
||||
((40000, 20000), (0, 20000)), ((0, 20000), (0, 0))]
|
||||
interior = [((4000 * i, 0), (4000 * i, 20000)) for i in range(1, 10)]
|
||||
for (sx, sy), (ex, ey) in outline + interior:
|
||||
msp.add_line((sx + ox, sy), (ex + ox, ey), dxfattribs={"layer": "I-WALL"})
|
||||
for y in (0, 7000, 13000, 20000):
|
||||
msp.add_line((ox - 2000, y), (ox + 42000, y), dxfattribs={"layer": "S-GRID"})
|
||||
|
||||
block_name = f"门族-001-{title}"
|
||||
door = doc.blocks.new(name=block_name)
|
||||
door.add_line((0, 0), (900, 0), dxfattribs={"layer": "A-DOOR"})
|
||||
# Distributed INSERT positions are robust frame seeds; include the
|
||||
# extrema so the proposed clip covers the complete wall outline.
|
||||
for i in range(12):
|
||||
x = ox + (40000 * i / 11)
|
||||
y = 20000 * (i % 4) / 3
|
||||
msp.add_blockref(block_name, (x, y))
|
||||
|
||||
# This text must not become a third frame or leak the AutoCAD underline
|
||||
# control code into keys such as ``_L_``.
|
||||
msp.add_text(r"\L主楼首层_二层平面图", height=800,
|
||||
dxfattribs={"layer": "G-ANNO-TTLB"}).set_placement((0, 80000))
|
||||
doc.saveas(path)
|
||||
|
||||
|
||||
def make_revit_overlapping_roof_dxf(path: Path) -> None:
|
||||
"""Roof and machine-room-roof labels vote for the same geometry frame."""
|
||||
doc = ezdxf.new("R2010", setup=True)
|
||||
for layer in ("I-WALL", "S-GRID", "A-DOOR"):
|
||||
doc.layers.add(layer)
|
||||
msp = doc.modelspace()
|
||||
for i in range(12):
|
||||
x = 4000.0 * i
|
||||
msp.add_line((x, 0), (x, 24000), dxfattribs={"layer": "I-WALL"})
|
||||
for y in (0, 8000, 16000, 24000):
|
||||
msp.add_line((0, y), (44000, y), dxfattribs={"layer": "S-GRID"})
|
||||
for title in ("屋面平面图", "机房小屋面"):
|
||||
block = doc.blocks.new(name=f"屋面构件-{title}")
|
||||
block.add_line((0, 0), (900, 0), dxfattribs={"layer": "A-DOOR"})
|
||||
for i in range(12):
|
||||
msp.add_blockref(block.name, (4000.0 * i, 2000.0 * (i % 10)))
|
||||
doc.saveas(path)
|
||||
|
||||
|
||||
def make_same_floor_two_buildings_dxf(path: Path) -> None:
|
||||
"""Two building-qualified F1 plans must not collapse into one frame."""
|
||||
doc = ezdxf.new("R2010", setup=True)
|
||||
for layer in ("WALL", "A-TEXT"):
|
||||
doc.layers.add(layer)
|
||||
msp = doc.modelspace()
|
||||
for title, ox in (("1#楼一层平面图", 0.0), ("2#楼一层平面图", 70000.0)):
|
||||
msp.add_text(title, height=800, dxfattribs={"layer": "A-TEXT"}).set_placement((ox, 25000))
|
||||
for i in range(16):
|
||||
msp.add_line((ox + 2000 * i, 0), (ox + 2000 * i, 20000),
|
||||
dxfattribs={"layer": "WALL"})
|
||||
doc.saveas(path)
|
||||
|
||||
|
||||
def make_blockgrid_dxf(path: Path) -> None:
|
||||
"""黄桥 pattern: plan grids live inside anonymous wrapper blocks (A$C...),
|
||||
NOT in modelspace, and floor wall bboxes differ (F2 covers half the
|
||||
@@ -600,6 +671,64 @@ def main() -> int:
|
||||
ok_offset = abs(off["F2"][0] - 0.0) <= 120 and abs(off["F2"][1] - 98100.0) <= 120
|
||||
check("grid alignment recovers frame offset", ok_offset, str(off))
|
||||
|
||||
# --- Revit export: title block lies, INSERT-name floor evidence wins ---
|
||||
revit_dir = WORK / "dxf_revit_named"
|
||||
revit_dir.mkdir(parents=True, exist_ok=True)
|
||||
revit_path = revit_dir / "A208 - 主楼首层、二层平面图.dxf"
|
||||
make_revit_named_frames_dxf(revit_path)
|
||||
proc = run([
|
||||
sys.executable, "scripts/cad_dxf_report.py",
|
||||
"--input", str(revit_dir), "--work", str(WORK / "report_work_revit"),
|
||||
"--output", str(WORK / "read_report_revit"), "--vendor-dir", str(VENDOR),
|
||||
])
|
||||
check("Revit INSERT-name report runs", proc.returncode == 0, proc.stderr[-600:])
|
||||
revit_report = json.loads((WORK / "read_report_revit" / "cad_read_report.json").read_text(encoding="utf-8"))
|
||||
revit_item = revit_report["files"][0]
|
||||
check("Revit floor count ignores TTLB duplicate", revit_item.get("plan_title_count") == 2, str(revit_item))
|
||||
check("Revit two-floor sheet raises multi-frame warning",
|
||||
any("multi_frame_sheet" in w for w in revit_item.get("warnings", [])), str(revit_item.get("warnings")))
|
||||
|
||||
proc = run([
|
||||
sys.executable, "scripts/detect_sheet_frames.py",
|
||||
"--dxf", str(revit_path), "--out-config", str(WORK / "frames_revit.json"),
|
||||
"--out-report", str(WORK / "frames_revit.md"), "--vendor-dir", str(VENDOR),
|
||||
])
|
||||
check("detect uses Revit INSERT-name evidence", proc.returncode == 0, proc.stderr[-600:])
|
||||
if proc.returncode == 0:
|
||||
revit_frames = json.loads((WORK / "frames_revit.json").read_text(encoding="utf-8"))
|
||||
revit_floors = revit_frames["drawings"][0]["floors"]
|
||||
revit_keys = sorted(f["key"] for f in revit_floors)
|
||||
check("Revit title formatting yields F1/F2 only", revit_keys == ["F1", "F2"], str(revit_keys))
|
||||
revit_clips = {f["key"]: f["clip"] for f in revit_floors}
|
||||
separated = (revit_clips.get("F1", [0, 0, 0, 0])[2]
|
||||
< revit_clips.get("F2", [0, 0, 0, 0])[0])
|
||||
check("Revit INSERT-name clips stay spatially separated", separated, str(revit_clips))
|
||||
|
||||
roof_path = revit_dir / "A212 - 主楼屋顶平面图.dxf"
|
||||
make_revit_overlapping_roof_dxf(roof_path)
|
||||
proc = run([
|
||||
sys.executable, "scripts/detect_sheet_frames.py",
|
||||
"--dxf", str(roof_path), "--out-config", str(WORK / "frames_revit_roof.json"),
|
||||
"--out-report", str(WORK / "frames_revit_roof.md"), "--vendor-dir", str(VENDOR),
|
||||
])
|
||||
check("detect handles overlapping Revit roof identities", proc.returncode == 0, proc.stderr[-600:])
|
||||
roof_report = (WORK / "frames_revit_roof.md").read_text(encoding="utf-8")
|
||||
check("overlapping roof frames demand Agent resolution",
|
||||
"AMBIGUOUS overlapping inferred frames" in roof_report, roof_report[-800:])
|
||||
|
||||
twin_path = revit_dir / "same-floor-two-buildings.dxf"
|
||||
make_same_floor_two_buildings_dxf(twin_path)
|
||||
proc = run([
|
||||
sys.executable, "scripts/cad_dxf_report.py",
|
||||
"--input", str(revit_dir), "--work", str(WORK / "report_work_revit_twin"),
|
||||
"--output", str(WORK / "read_report_revit_twin"), "--vendor-dir", str(VENDOR),
|
||||
])
|
||||
check("same-floor two-building report runs", proc.returncode == 0, proc.stderr[-600:])
|
||||
twin_report = json.loads((WORK / "read_report_revit_twin" / "cad_read_report.json").read_text(encoding="utf-8"))
|
||||
twin_item = next(item for item in twin_report["files"] if item["file"] == twin_path.name)
|
||||
check("same floor in two qualified buildings counts as two frames",
|
||||
twin_item.get("plan_title_count") == 2, str(twin_item))
|
||||
|
||||
frames.update({"scale": 0.001, "layers": {"walls": ["WALL"], "grid": ["DOTE"]}})
|
||||
aligned_cfg = WORK / "config_frames.json"
|
||||
aligned_cfg.write_text(json.dumps(frames, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
Reference in New Issue
Block a user