diff --git a/SKILL.md b/SKILL.md index 6329bac..ab77006 100644 --- a/SKILL.md +++ b/SKILL.md @@ -43,8 +43,9 @@ Read only the branches needed for the current task: 2. Select the branch. - Use standard line extraction for architectural DWG/DXF plans. - - Use `detect_sheet_frames.py` for multi-frame sheets. - - Treat detector clips as proposals. If two titles share the same clip, split the common sheet by title/wall clusters; the area and cross-floor gates must pass before modeling. + - Use `detect_sheet_frames.py` for multi-frame sheets. If the source report finds two or more plan identities in one drawing, `--frames` is mandatory; do not let `frame_ledger` become `NOT_APPLICABLE`. + - Treat detector clips as proposals. If Revit views share world coordinates, keep the detector's per-floor `include_block_names` plus top-level `expand_block_names`; clips alone cannot separate overlapping views. For non-Revit overlap, split by title/wall clusters. Area and cross-floor gates must pass before modeling. + - Keep `屋面平面图` (`RF`) and `机房小屋面` (`PH`) as distinct source identities. One overlapping RF clip may not satisfy both; resolve their view-suffixed blocks, heights, and roof-cap roles from the drawing evidence. - Model each building separately before campus assembly. - For multi-building/campus requests, write `scope_manifest.json` before modeling. Copy every requested building ID from the user/source inventory; never shrink scope to the easiest drawing set. - Use `--converter oda` plus `extract_3d_solids.py` for known 3DSOLID/ACIS drawings. @@ -64,6 +65,7 @@ Read only the branches needed for the current task: - A waiver must be explicitly approved by the user. The Agent must not invent one, and must never use one when the user says “no waivers/不要豁免”. - Search all source sheets for economic-index tables, storey labels, and elevation ladders before declaring area/storey evidence absent. If a typical plan represents repeated floors, instantiate the source-supported repetitions; a final full-building model may not jump from F2 directly to F16. - Open the SVG overlays. Iterate if red/unclassified geometry forms walls, glazing, columns, beams, grids, stairs, slabs, roofs, or whole building wings. + - Resolve every `disconnected_footprints` failure. A small remote polygon is usually a leaked sheet component that becomes a floating fin; only record `allowed_disconnected_footprints` when the source visibly proves a legitimate detached stair/canopy and include the reason. - Treat every geometry-loss warning from derive (`isolated_cluster`, `unsupported_roof`, `floor_order`, `topless_group`) as a stop condition. Tune the config or restore/model the geometry; do not accept a successful exit code with these warnings. 5. Verify actual deliverables. @@ -84,17 +86,18 @@ Do not hand over a model unless every applicable item has evidence: 1. `cad_read_report.json.gate.status == PASS`; no unresolved conversion/read failure. A reasoned partial `WARN` is usable only with a user-approved `cad_source_report` waiver and must remain visible in evidence. 2. Config and spec pass their versioned JSON Schemas. 3. Every configured source exists, every floor key is unique, every floor is nonempty, and `floor_order` has no gaps/ghosts. -4. Multi-frame projects pass `frame_ledger`; every detected plan frame is used or appears in `discarded_frames` with a reason. +4. Multi-frame projects pass `frame_ledger`; `--frames` is mandatory when the source reports multiple plan identities, and every detected frame key and required block selector is mapped one-to-one or appears in `discarded_frames` with a reason. `RF` and `PH` cannot satisfy each other merely because their clips overlap. 5. A required single-building/campus `scope_manifest.json` matches the requested scope and its artifacts exist. 6. Numbered floors are vertically continuous; representative typical-floor drawings are repeated into source-supported storeys instead of leaving large empty gaps. 7. Audit exits 0 and every gate is `PASS`; `WARN`/`SKIP` block delivery unless a named, user-approved waiver is recorded in evidence. 8. Derive emits no `WARNING topless_group`; GLB build emits no `WARNING mesh_from_polygons`. 9. Campus output contains every requested building and the site as `PASS`, with existing artifacts; a `BLOCKED` entry means the campus request is not complete. 10. Campus output has proven transforms, no unexplained overlap, numeric neighbour gaps, boundary containment, and a top-view placement image. -11. `verify_delivery.py` writes `evidence_manifest.json` with overall `PASS`; `BLOCKED`/`FAIL` must never be described as complete, and a human has looked at the render. -12. Served Web delivery includes a passing desktop/mobile browser smoke report whose viewport checks prove 1440×900 and 390×844. If Chromium cannot run, report `BLOCKED`; do not substitute the offline viewer for the requested Web template. -13. Offline delivery includes a passing `file://` browser smoke report proving the readiness marker, canvas, and first render; an embedded payload check alone is insufficient. -14. After any script/schema/template change, run: +11. `disconnected_footprints` passes; iso/front/side/plan review shows no floating fins, orphan slabs, duplicated roof volumes, or unexplained detached geometry. +12. `verify_delivery.py` writes `evidence_manifest.json` with overall `PASS`; `BLOCKED`/`FAIL` must never be described as complete, and a human has looked at the render. +13. Served Web delivery includes a passing desktop/mobile browser smoke report whose viewport checks prove 1440×900 and 390×844. If Chromium cannot run, report `BLOCKED`; do not substitute the offline viewer for the requested Web template. +14. Offline delivery includes a passing `file://` browser smoke report proving the readiness marker, canvas, and first render; an embedded payload check alone is insufficient. +15. After any script/schema/template change, run: - `pytest tests/test_contracts.py tests/test_delivery.py` - `python3 tests/test_extraction_pipeline.py` - `ruff format --check scripts tests && ruff check scripts tests` diff --git a/assets/web-showcase-template/app.js b/assets/web-showcase-template/app.js index 92ad0dc..598860f 100644 --- a/assets/web-showcase-template/app.js +++ b/assets/web-showcase-template/app.js @@ -774,7 +774,7 @@ function updateStats() { ["楼层", `${activeFloors}/${(metadata.floors || []).length}`], ["构件", `${activeCategories}/${categoryOrder.length}`], ["顶点", vertices.toLocaleString("zh-CN")], - ["Draw Calls", drawCalls.toString()], + ["绘制批次", drawCalls.toString()], ]) { const cell = document.createElement("div"); cell.innerHTML = `
${item[0]}
${item[1]}
`; diff --git a/package-lock.json b/package-lock.json index 343e256..adf0cd7 100644 --- a/package-lock.json +++ b/package-lock.json @@ -4,6 +4,7 @@ "requires": true, "packages": { "": { + "name": "cad-building-showcase", "dependencies": { "@gltf-transform/core": "^4.4.1", "@gltf-transform/extensions": "^4.4.1", diff --git a/package.json b/package.json index 5756bac..76822ff 100644 --- a/package.json +++ b/package.json @@ -1,4 +1,6 @@ { + "name": "cad-building-showcase", + "private": true, "scripts": { "check:js": "node --check assets/web-showcase-template/app.js && node --check scripts/dwg_dump_json.mjs && node --check scripts/web_smoke_test.mjs && node --check scripts/offline_viewer_smoke.mjs && node --check tools/compress.mjs", "smoke:web": "node scripts/web_smoke_test.mjs", diff --git a/schemas/extraction_config.schema.json b/schemas/extraction_config.schema.json index 07a1642..4deb64f 100644 --- a/schemas/extraction_config.schema.json +++ b/schemas/extraction_config.schema.json @@ -31,6 +31,18 @@ "additionalProperties": false } }, + "allowed_disconnected_footprints": { + "type": "array", + "items": { + "type": "object", + "required": ["floor_key", "reason"], + "properties": { + "floor_key": {"type": "string", "minLength": 1}, + "reason": {"type": "string", "minLength": 1} + }, + "additionalProperties": false + } + }, "layers": {"$ref": "#/$defs/patternMap"}, "categories": { "type": "object", @@ -142,7 +154,9 @@ "clip": {"$ref": "#/$defs/rect"}, "offset": {"$ref": "#/$defs/point"}, "side": {"type": "string"}, - "split_x": {"type": "number"} + "split_x": {"type": "number"}, + "include_block_names": {"$ref": "#/$defs/stringList"}, + "exclude_block_names": {"$ref": "#/$defs/stringList"} }, "additionalProperties": false }, @@ -154,6 +168,8 @@ "clip": {"$ref": "#/$defs/rect"}, "offset": {"$ref": "#/$defs/point"}, "split_x": {"type": "number"}, + "include_block_names": {"$ref": "#/$defs/stringList"}, + "exclude_block_names": {"$ref": "#/$defs/stringList"}, "floors": {"type": "array", "items": {"$ref": "#/$defs/floor"}} }, "additionalProperties": false diff --git a/scripts/audit_showcase_extraction.py b/scripts/audit_showcase_extraction.py index 89aca45..411c212 100755 --- a/scripts/audit_showcase_extraction.py +++ b/scripts/audit_showcase_extraction.py @@ -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 (经济技术指标表/标注). diff --git a/scripts/build_showcase_variants.py b/scripts/build_showcase_variants.py index 6e0c0b2..6bf6ef7 100644 --- a/scripts/build_showcase_variants.py +++ b/scripts/build_showcase_variants.py @@ -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, }, ] diff --git a/scripts/cad_dxf_report.py b/scripts/cad_dxf_report.py index c724623..3d7bcfe 100755 --- a/scripts/cad_dxf_report.py +++ b/scripts/cad_dxf_report.py @@ -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]: diff --git a/scripts/cad_showcase.py b/scripts/cad_showcase.py index 6d66883..90980ca 100644 --- a/scripts/cad_showcase.py +++ b/scripts/cad_showcase.py @@ -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( diff --git a/scripts/derive_showcase_spec.py b/scripts/derive_showcase_spec.py index 97d06e7..2f7d432 100755 --- a/scripts/derive_showcase_spec.py +++ b/scripts/derive_showcase_spec.py @@ -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"))) diff --git a/scripts/detect_sheet_frames.py b/scripts/detect_sheet_frames.py index 8d8a9dd..0422eec 100644 --- a/scripts/detect_sheet_frames.py +++ b/scripts/detect_sheet_frames.py @@ -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[一二三四五六七八九十\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: "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"), ] @@ -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, diff --git a/tests/test_contracts.py b/tests/test_contracts.py index 8276f7c..ab69e8f 100644 --- a/tests/test_contracts.py +++ b/tests/test_contracts.py @@ -129,6 +129,81 @@ def test_unarmed_cross_evidence_gates_are_not_applicable() -> None: assert audit_showcase_extraction.storey_count_gate(spec, {})["status"] == "NOT_APPLICABLE" +def test_multi_frame_source_requires_detector_ledger() -> None: + report = { + "files": [ + {"file": "A212.dxf", "status": "ok", "plan_title_count": 2}, + {"file": "A213.dxf", "status": "ok", "plan_title_count": 1}, + ] + } + assert cad_showcase.multi_frame_source_files(report) == ["A212.dxf"] + + +def test_frame_ledger_requires_distinct_floor_identity_even_when_roof_clips_overlap() -> None: + frames = [ + { + "drawings": [ + { + "file": "A212.dxf", + "floors": [ + { + "key": "RF", + "name": "屋面平面图", + "clip": [0, 0, 100, 100], + "include_block_names": ["*-屋面平面图"], + }, + { + "key": "PH", + "name": "机房小屋面", + "clip": [0, 0, 100, 100], + "include_block_names": ["*-机房小屋面"], + }, + ], + } + ] + } + ] + config = { + "drawings": [ + { + "file": "A212.dxf", + "floors": [ + {"key": "RF", "clip": [0, 0, 100, 100]}, + {"key": "PH", "clip": [0, 0, 100, 100]}, + ], + } + ] + } + gate = audit_showcase_extraction.frame_ledger_gate(config, frames) + assert gate["status"] == "FAIL" + assert "屋面平面图" in gate["detail"] + + config["drawings"][0]["floors"][0]["include_block_names"] = ["*-屋面平面图"] + config["drawings"][0]["floors"][1]["include_block_names"] = ["*-机房小屋面"] + assert audit_showcase_extraction.frame_ledger_gate(config, frames)["status"] == "PASS" + + +def test_revit_view_block_selector_separates_overlapping_floor_views() -> None: + rf = {"include_block_names": ["*-屋面平面图"]} + drawing: dict = {} + assert derive_showcase_spec.block_matches_floor("墙族-123-屋面平面图", rf, drawing) + assert not derive_showcase_spec.block_matches_floor("墙族-456-机房小屋面", rf, drawing) + assert not derive_showcase_spec.block_matches_floor("", rf, drawing) + + +def test_disconnected_footprint_island_fails_until_explicitly_explained() -> None: + spec = minimal_spec() + spec["floors"]["F1"]["footprint"]["polygons"].append([[25.0, 0.0], [26.0, 0.0], [26.0, 1.0], [25.0, 1.0]]) + failed = audit_showcase_extraction.disconnected_footprints_gate(spec, {}) + assert failed["status"] == "FAIL" + assert "F1" in failed["detail"] + accepted = audit_showcase_extraction.disconnected_footprints_gate( + spec, + {"allowed_disconnected_footprints": [{"floor_key": "F1", "reason": "独立雨棚,有柱网证据"}]}, + ) + assert accepted["status"] == "PASS" + + def test_annotation_is_waivable_warn_and_absent_glazing_is_not_applicable() -> None: report = { "spec_counts": {"F1": {"glazing": 0}}, diff --git a/tests/test_extraction_pipeline.py b/tests/test_extraction_pipeline.py index 61f1158..7abf6d1 100644 --- a/tests/test_extraction_pipeline.py +++ b/tests/test_extraction_pipeline.py @@ -163,6 +163,79 @@ 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 @@ -745,6 +818,117 @@ 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") + roof_frames = json.loads((WORK / "frames_revit_roof.json").read_text(encoding="utf-8")) + roof_by_key = {floor["key"]: floor for floor in roof_frames["drawings"][0]["floors"]} + check( + "overlapping Revit roof views get block selectors", + roof_by_key.get("RF", {}).get("include_block_names") == ["*-屋面平面图"] + and roof_by_key.get("PH", {}).get("include_block_names") == ["*-机房小屋面"], + str(roof_by_key), + ) + check( + "overlapping roof clips are resolved by view identity", + "OVERLAPPING clips separated by Revit view identity" in roof_report + and "AMBIGUOUS overlapping inferred frames" not 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")