fix: enforce Revit roof views and orphan geometry gates
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled

This commit is contained in:
2026-07-21 13:10:04 +08:00
13 changed files with 857 additions and 67 deletions

View File

@@ -568,6 +568,7 @@ def evaluate_gates(
}
)
gates.append(frame_ledger_gate(config, frames))
gates.append(disconnected_footprints_gate(spec, config))
gates.append(vertical_storey_continuity_gate(spec))
gates.append(declared_area_gate(spec, config))
gates.append(storey_count_gate(spec, config))
@@ -610,15 +611,30 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
for drawing in fcfg.get("drawings", []) or []:
file = str(drawing.get("file", ""))
cfg_floors = cfg_by_file.get(file, [])
used_cfg: set[int] = set()
for frame in drawing.get("floors", []) or []:
total += 1
name = str(frame.get("name", ""))
key = str(frame.get("key", ""))
clip = frame.get("clip")
if name in discarded:
continue
if clip and any(fl.get("clip") and _rect_overlap_ratio(clip, fl["clip"]) >= 0.3 for fl in cfg_floors):
matches = [
index
for index, floor in enumerate(cfg_floors)
if index not in used_cfg
and str(floor.get("key", "")) == key
and set(frame.get("include_block_names", []) or []).issubset(
set(floor.get("include_block_names", []) or [])
)
and clip
and floor.get("clip")
and _rect_overlap_ratio(clip, floor["clip"]) >= 0.3
]
if matches:
used_cfg.add(matches[0])
continue
unaccounted.append(f"{file}: {frame.get('key', '?')} {name}")
unaccounted.append(f"{file}: {key or '?'} {name}")
if unaccounted:
shown = "; ".join(unaccounted[:12]) + (" …" if len(unaccounted) > 12 else "")
return {
@@ -637,6 +653,93 @@ def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | Non
}
def _polygon_area(points: list[list[float]]) -> float:
if len(points) < 3:
return 0.0
return (
abs(
sum(
float(points[index][0]) * float(points[(index + 1) % len(points)][1])
- float(points[(index + 1) % len(points)][0]) * float(points[index][1])
for index in range(len(points))
)
)
/ 2.0
)
def _polygon_bounds(points: list[list[float]]) -> list[float]:
xs = [float(point[0]) for point in points]
ys = [float(point[1]) for point in points]
return [min(xs), min(ys), max(xs), max(ys)]
def _bounds_gap(a: list[float], b: list[float]) -> float:
dx = max(0.0, max(a[0] - b[2], b[0] - a[2]))
dy = max(0.0, max(a[1] - b[3], b[1] - a[3]))
return math.hypot(dx, dy)
def disconnected_footprints_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
"""Reject small, remote footprint islands unless they are explained.
A stray but substantial curtain-wall/component cluster can survive the
line-level isolated-cluster filter and become a tall floating fin. The
generated footprint exposes it deterministically. Legitimate detached
stairs/canopies must be acknowledged with a floor key and reason.
"""
allowed = {
str(item.get("floor_key", ""))
for item in config.get("allowed_disconnected_footprints", []) or []
if isinstance(item, dict) and str(item.get("reason", "")).strip()
}
problems: list[str] = []
checked = 0
for floor_key, floor in spec.get("floors", {}).items():
polygons = [
polygon
for polygon in (floor.get("footprint") or {}).get("polygons", []) or []
if isinstance(polygon, list) and len(polygon) >= 3
]
if len(polygons) < 2 or str(floor_key) in allowed:
continue
checked += 1
measured = sorted(
[(_polygon_area(polygon), _polygon_bounds(polygon)) for polygon in polygons],
key=lambda item: item[0],
reverse=True,
)
main_area, main_bounds = measured[0]
if main_area <= 0:
continue
for area, bounds in measured[1:]:
ratio = area / main_area
gap = _bounds_gap(main_bounds, bounds)
if ratio < 0.05 and gap > 2.0:
problems.append(
f"{floor_key}: {area:.1f} m² island is {ratio:.1%} of the main footprint and {gap:.1f} m away"
)
if problems:
return {
"name": "disconnected_footprints",
"status": "FAIL",
"detail": (
"Small remote footprint islands would render as floating/orphan building parts: "
+ "; ".join(problems)
+ ". Fix the clip/layer/block mapping, or document a legitimate detached element in "
"allowed_disconnected_footprints with floor_key and reason."
),
}
return {
"name": "disconnected_footprints",
"status": "PASS",
"detail": (
f"No unexplained small remote footprint islands across {len(spec.get('floors', {}))} floor(s)"
+ (f" ({checked} multi-component floor(s) checked)." if checked else ".")
),
}
def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
"""Model footprint areas must match declared areas (经济技术指标表/标注).

View File

@@ -25,19 +25,19 @@ VARIANTS = [
{
"key": "overview",
"label": "总览轻量版",
"description": "Walls, glazing, roofs, columns, beams, and generated slabs.",
"description": "保留墙体、玻璃幕墙、屋顶、柱梁和楼板,适合快速总览。",
"categories": ["walls", "glazing", "roof", "columns", "beams"],
},
{
"key": "standard",
"label": "展示标准版",
"description": "Default Web presentation model with railings and doors.",
"description": "标准网页展示模型,包含栏杆和门等主要细节。",
"categories": ["walls", "glazing", "roof", "columns", "beams", "railings", "doors"],
},
{
"key": "detail",
"label": "完整审图版",
"description": "Full extracted linework for audit and review.",
"description": "保留完整提取线条,适合细节查看和复核。",
"categories": None,
},
]

View File

@@ -12,7 +12,7 @@ import re
import shutil
import subprocess
import sys
from collections import Counter
from collections import Counter, defaultdict
from pathlib import Path
@@ -250,6 +250,16 @@ def xref_definitions(doc) -> list[dict]:
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
@@ -273,27 +283,77 @@ 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]:

View File

@@ -316,6 +316,26 @@ def preflight_waiver_targets(
]
def multi_frame_source_files(source_report: dict[str, Any]) -> list[str]:
"""Return source drawings that require a detector-backed frame ledger.
A single modelspace can contain several floor plans. In that case a
hand-written extraction config is not enough evidence: every detected
frame must be mapped or explicitly discarded. Accept either the structured
count or the compatible warning emitted by older source inspectors.
"""
required: list[str] = []
for item in source_report.get("files", []) or []:
if not isinstance(item, dict) or item.get("status") != "ok":
continue
warnings = [str(value) for value in item.get("warnings", []) or []]
if int(item.get("plan_title_count", 0) or 0) >= 2 or any(
"multi_frame_sheet" in warning for warning in warnings
):
required.append(str(item.get("file", "?")))
return required
def available_port() -> int:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as stream:
stream.bind(("127.0.0.1", 0))
@@ -534,6 +554,14 @@ def run_pipeline(args: argparse.Namespace) -> int:
file=sys.stderr,
)
return 3
multi_frame_files = multi_frame_source_files(report)
if multi_frame_files and not frame_inputs:
print(
"GATE FAIL [frame_ledger_required]: multi-plan source drawing(s) require "
"detect_sheet_frames output via --frames: " + ", ".join(multi_frame_files),
file=sys.stderr,
)
return 3
out_dir = Path(args.out_dir).resolve()
out_dir.mkdir(parents=True, exist_ok=True)
pipeline = Pipeline(

View File

@@ -244,6 +244,23 @@ def match_patterns(value: str, patterns: list[str]) -> bool:
return any(fnmatch.fnmatch(upper_value, str(pattern).upper()) for pattern in patterns)
def block_matches_floor(block_name: str, floor: dict[str, Any], drawing: dict[str, Any]) -> bool:
"""Apply source-view block selectors before expanding a Revit sheet.
Revit DXF exports can place several views at identical world coordinates;
their top-level INSERT names retain the view suffix (for example
``-屋面平面图`` vs ``-机房小屋面``). A clip cannot separate those views, so
the floor config must be able to select the corresponding block family.
"""
includes = list(floor.get("include_block_names", drawing.get("include_block_names", [])) or [])
excludes = list(floor.get("exclude_block_names", drawing.get("exclude_block_names", [])) or [])
if includes and (not block_name or not match_patterns(block_name, includes)):
return False
if excludes and block_name and match_patterns(block_name, excludes):
return False
return True
def block_category(block_name: str, config: dict[str, Any]) -> str | None:
for category, patterns in config.get("block_name_categories", {}).items():
if match_patterns(block_name, list(patterns)):
@@ -527,6 +544,12 @@ def collect_raw_segments(
ignored_by_type: dict[str, int] = defaultdict(int)
for entity in entities:
root_block_name = (
str(entity.dxf.name) if entity.dxftype() == "INSERT" and entity.dxf.hasattr("name") else ""
)
eligible_floors = [item for item in floor_specs if block_matches_floor(root_block_name, item[0], drawing)]
if not eligible_floors:
continue
for extracted_entity, fallback_layer, block_name in iter_model_entities(entity, config):
layer = entity_layer(extracted_entity)
category = category_for_entity(
@@ -547,7 +570,7 @@ def collect_raw_segments(
min_source = min_source_by_category.get(category, min_source_length)
min_meters = min_meters_by_category.get(category, min_meters_length)
for start, end in segments:
for floor, key, offset in floor_specs:
for floor, key, offset in eligible_floors:
if not segment_matches_floor(start, end, floor, drawing):
continue
trimmed = clip_segment_to_rect(start, end, floor.get("clip", drawing.get("clip")))

View File

@@ -30,6 +30,7 @@ from __future__ import annotations
import argparse
import fnmatch
import json
import math
import re
import statistics
import sys
@@ -46,6 +47,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:
@@ -63,15 +78,56 @@ def decode_mif(text: str) -> str:
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"),
]
@@ -131,7 +187,7 @@ def parse_args() -> argparse.Namespace:
"--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(
@@ -173,22 +229,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}"
@@ -239,6 +297,67 @@ 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:
@@ -246,7 +365,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层地下夹标准机房屋顶面跃阁避难设备转换裙塔、,,~~至\-—.]*平面图$"
)
@@ -339,13 +458,24 @@ 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:
@@ -452,8 +582,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)
@@ -469,6 +619,109 @@ 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,
"_include_block_names": [f"*-{label}"],
}
)
if not titles:
print(json.dumps({"error": "no plan titles found"}, ensure_ascii=False))
return 1
@@ -517,8 +770,13 @@ def main() -> int:
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 if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None)
@@ -531,22 +789,23 @@ def main() -> int:
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:
@@ -574,17 +833,18 @@ def main() -> int:
f"{t['name']}: auxiliary-titled frame (qualifier '{qualifier}') — likely a "
"separate structure or revision sheet; excluded from reference candidacy"
)
floors.append(
{
"key": floor_key_for(t["name"], used_keys),
"name": t["name"],
"clip": [round(c, 1) for c in clip],
"_vx": cluster_positions(vert, args.grid_bin),
"_hy": cluster_positions(horiz, args.grid_bin),
"_walls": segments_in(lines, clip, wall_layers),
"_aux": bool(qualifier),
}
)
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...);
@@ -628,6 +888,30 @@ 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:
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
@@ -651,6 +935,7 @@ def main() -> int:
"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(
@@ -659,9 +944,18 @@ def main() -> int:
)
else:
config_floors.append(
{"key": _unique_key(f["key"]), "name": f["name"], "clip": f["clip"], "offset": f["offset"]}
{
"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,
@@ -669,6 +963,7 @@ def main() -> int:
"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,