Compare commits

..

10 Commits

Author SHA1 Message Date
e1bbca3fe7 Organize repo layout for publishing: case docs into references/, add README
- 贝昂CAD诊断与skill优化.md / claudecode_prompt (annotated as archive) /
  beian corrected-config sample moved under references/
- README.md: what this is, pipeline map, layout, verification discipline

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 09:08:55 +08:00
ab5e72daae Leak gates: cross-evidence nets for unseen-project conventions
Mechanical pattern tools WILL miss new dialects; these gates are
ledger/cross-evidence INVARIANTS that hold for conventions never seen:

- frame_ledger (audit --frames <detect out-config>): 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
- area_declared (config declared_areas_m2): model footprint area vs
  经济技术指标表 within ±15% — 1#B lost half the building and only the
  site plan exposed it
- storey_count (config expected_storeys_above_ground): above-ground F<n>
  count vs 总图 labels / elevation ladder
- unknown_layer_dialect (read report): plan file with no *WALL*/*墙* layer
  = unfamiliar institute convention, map layers consciously

All three gates SKIP when unarmed (zero impact on existing projects);
regression suite +8 checks, all green.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 09:04:58 +08:00
fc05464749 Productize site machinery + config automation (session-proven -> scripts/)
- register_site_outlines.py: point-to-edge ICP registration CLI (footprint
  union vs site outline / DIM_COOR corners), manifest-ready output, loud
  warning above 2 m residual
- massing_from_outline.py: honest massing spec CLI (outline x storeys x
  height, labeled 总图轮廓体量), manifest anchors on stdout
- detect_sheet_frames: multi-floor titles (四、六、八 / 十一至十四) expand to
  per-storey config entries sharing clip/offset — the 13号 b2 silent-floor-
  loss class is now prevented at the source; compound CN numerals parsed
  (十一/二十一 no longer collapse to F0 keys); per-frame DIM_ELEV ladders +
  uniform-step storey suggestion in the report (evidence, not auto-filled z)
- 27号 2# real data: 19-storey enumerated title auto-expands, step 3.0 x 11
  suggestion correct; regression suite +11 checks

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 08:28:05 +08:00
9729857549 Land the two deferred gaps: title-block frame clips + cross-floor datum gate
- detect_sheet_frames: title-block INSERTs (A0_V1/A0+0.5_V1/*图框*) define the
  clip window when they contain the title — pitch windows halved elongated
  sheets (13号 加长A0, one frame holding both towers); wall refine is clamped
  inside the frame rect; 13号 b1 real data: all 45 frames rect-clipped
- audit floors_aligned: cross-floor wall-profile datum check catches
  "self-consistent but misplaced" floors (13号 F3 错槽 85.8m that envelope
  centers PASSed); zero-shift guard kills the dense-podium false positive
  (27号 1#A PH matched "better" 1.5m off while already fitting in place)
- 门卫 size mismatch root-caused as representation granularity (gate compound
  vs kiosk symbol), not an extraction bug — closed in the log
- regression suite +6 checks (titleblock / crossdatum bad+good), all three
  projects re-audited with no false positives

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 08:05:57 +08:00
1e11d38fa9 derive: per-cluster footprint hulls — twin-tower floors no longer bridged
concave_hull over all points cannot split disconnected masses: 13号 一号楼
standard floors (A/B towers in one floor key) got ONE 135.6m hull and
use_footprint_slabs laid plates across the 36m void (user-visible as
"triangular links" between towers). Points are now union-find clustered
(footprint_cluster_linkage, 6m grid buckets; segment endpoints forced into
one cluster) and hulled per cluster — real link bridges keep clusters
merged via their walls. F4-F10 now 2x49.8m hulls matching the site-plan
OBB; 黄桥/27号 re-derived with no regression; DoD visual check extended
(look at the AIR between masses in front/side views). Regression: twintower
scenario (+3 checks).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 07:48:22 +08:00
c6df3f6ffb Log: plot-27 complete end-to-end — quality table filled for all three projects
1#A 17F(四层=裙房顶大平层), 1#B 10F(户型块拼装+假x-pitch教训), 2# 22F(参考框
修复后全列对齐); site: EVTR outlines + DIM_COOR corner ICP registration,
3#/4# honest massing from site outlines; campus 7 buildings/100 floors,
all gaps positive; offline viewers browser-verified zero console errors
for 黄桥/13号/27号.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 00:39:32 +08:00
fe3d3cbbee Generalization hardening from 27号 (rounds 5-8): 6 gap fixes, all TDD
- detect_sheet_frames: auxiliary-titled frames (非机动坡道/无障碍改造…) never
  become the alignment reference; wall-profile correlation fallback when a
  frame has no axis geometry (coverage+peak-ratio gated); bogus x-pitch from
  stray same-row titles distrusted (pitch_x < 0.7*pitch_y); plan titles inside
  cached-xref blocks scanned too
- cad_dxf_report: cached_xref_content warning (msp INSERT stubs + in-file
  block cache -> expand_blocks ≈ bind, not a re-export ask)
- derive_showcase_spec: floor_order gaps warn loudly in both directions
- assemble_campus: per-building rotation_deg overrides the global one
- SKILL.md updated; regression suite +14 checks (auxref/nogrid/mixedrow/
  blocktitle/cachedxref/floor_order/rotation scenarios)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-03 00:39:32 +08:00
07e3c12956 Log: plot-13 above-ground complete — hotel tower extracted, campus assembled from site-plan anchors
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 23:22:41 +08:00
967a8a24f5 Log: plot-13 tower block re-anchored — shared-origin + wall-profile correlation; site plan proves 85.8m twin spacing
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 23:10:41 +08:00
f0b225b80e Log: plot-13 unblocked — xref content is CACHED inside the delivered DWGs
X-00-0011 (site plan) holds 5,306 entities and X-01-0200 (elevations)
4,443 as ordinary block definitions; modelspace only has the INSERT stub,
so the report's msp-count flagged near_empty. libredwg drops the xref
flag, ODA keeps xref_path with flags=0 — either way expand_blocks IS the
bind. Site plan is metric surveying coords (55km/57km) with bound-prefix
layers (X-00-0011$0$...) and 40 DIM_COOR callouts. Next round: teach the
report to flag cached-xref blocks instead of asking for re-exports, scan
block content for frame titles, and anchor the tower wings from the dx
outlines + coordinate callouts.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-02 22:29:20 +08:00
14 changed files with 1855 additions and 74 deletions

38
README.md Normal file
View File

@@ -0,0 +1,38 @@
# cad-building-showcase
把中国建筑施工图(DWG/DXF,天正 t3/t8 导出为主)自动转成可交互的 3D 展示模型(GLB + 离线单文件 Web viewer),并支持多栋厂区按总平面装配。Agent-led:脚本负责证据与可重复执行,判读权在 Agent;任何门禁失败即停,不静默出错模型。
## 用法
入口是 `SKILL.md`(操作手册):决策循环、One-Shot Definition of Done 七条门禁、天正图层方言预设、多栋厂区流程。核心链路:
```
cad_dxf_report.py 读图报告(警告:多框图纸/缓存XREF/陌生图层方言…)
detect_sheet_frames.py 图框检测(图签块定框、网格投票/墙剖面互相关对齐、
多层图名展开、逐框标高梯+层高建议)
derive_showcase_spec.py 按 config 提取 building_spec.json(分簇 footprint/楼板/顶盖)
audit_showcase_extraction.py 硬门禁审计(楼层对齐+跨层基准、幕墙、框收支表、
面积/层数互证…),FAIL 即退出码 3
spec_to_glb.py GLB 生成;write_offline_viewer.py 离线单文件 viewer
register_site_outlines.py / massing_from_outline.py / assemble_campus.py
总平面配准(点-边ICP)、无图纸楼体量、厂区装配
```
## 目录
- `scripts/` 全部流水线脚本(自含 CLI,`--help` 有说明)
- `tests/test_extraction_pipeline.py` 回归套件(改任何脚本后必跑)
- `references/` 案例记录与校准资料:`pipeline.md`(详细流程)、
`generalization_test_log.md`(泛化测试与缺口修复清单)、
`贝昂CAD诊断与skill优化.md`(首个案例全程)
- `assets/` Web 模板与离线 viewer 内联库
`work/`、`outputs/`、源 CAD 均不入库(见 `.gitignore`),由脚本从源数据再生。
## 验证纪律
```bash
python3 tests/test_extraction_pipeline.py # 必须全绿
```
已在四套真实图纸上端到端验证:贝昂科技厂区(基线)、黄桥文体中心、13号地块(双塔+酒店厂区)、27号地块(7栋混合厂区)。质量对比表见 `references/generalization_test_log.md`。

View File

@@ -52,11 +52,12 @@ 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; `likely_xref_shell` -> user re-exported with XREFs bound.
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.
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. Never pass `--no-strict-gates` to proceed.
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).
4. No `WARNING topless_group` from derive (roof handled via caps or `roof_specs`), and no `WARNING mesh_from_polygons` from the GLB build (else slabs/roofs silently vanished — install mapbox_earcut).
5. Visual check done by the Agent, not assumed: `verify_showcase.py` previews plus one rendered iso/plan image actually LOOKED AT (floors stacked, roof present, no slab fins beyond facade — default `cap_buffer` 1.3 is for colonnades, use ~0.1 otherwise).
5. Visual check done by the Agent, not assumed: `verify_showcase.py` previews plus one rendered iso/plan image actually LOOKED AT (floors stacked, roof present, no slab fins beyond facade — default `cap_buffer` 1.3 is for colonnades, use ~0.1 otherwise; and check the AIR between separate masses in the front/side views — bridged footprint hulls lay slab plates between twin towers, invisible in top views and to every gate).
6. Campus placement (if 总图/定位图 exists): building envelope dims match the site rect 1:1 (e.g. 面积核算 frame), rotation taken from the rect edge angle, 180° flip disambiguated by an asymmetric feature (machine rooms / basement / entrance), and a top-view overlay image confirms the building inside its site rect. Neighbour gaps measured numerically: no overlaps, 贴建 joints 0.15-0.3 m with corroborating evidence, buildings inside 红线.
7. `tests/test_extraction_pipeline.py` passes after ANY script change.
@@ -76,16 +77,17 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate
- Install missing parser dependencies into the current project work area, not globally:
`python3 -m pip install --target work/vendor ezdxf`
- Inspect the Markdown/JSON report before modeling. Confirm drawings, units, bounding boxes, and the top layers for walls/glazing/roof/columns/beams/railings/doors/detail lines/floor lines/grid.
- Resolve the report's `Warnings` section before modeling. `likely_xref_shell` / `near_empty` means a sheet's real geometry lives in unbound XREFs and will silently become a missing floor: ask the user to bind/insert the XREFs in CAD and re-export that DXF (do not model the shell and report the floor as done).
- `unknown_layer_dialect` warning = a plan file whose layers match no known wall naming (*WALL*/*墙*): a design-institute convention this pipeline has never seen. Build the layer mapping consciously from the top-layers list before modeling — patterns age, and a wrong mapping extracts nothing silently.
- Resolve the report's `Warnings` section before modeling. `cached_xref_content` means the "empty" sheet's INSERT stubs reference block definitions cached INSIDE the file (AutoCAD keeps unbound-XREF content as blocks; both libredwg and ODA export the cache) — expand blocks in detect/derive (`expand_blocks` ≈ bind), no re-export needed. Only `likely_xref_shell` / `near_empty` WITHOUT cached content means geometry truly lives outside: ask the user to bind/insert the XREFs in CAD and re-export that DXF (do not model the shell and report the floor as done).
3. Build the extraction config and `building_spec.json`.
- 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), proposes a wall-bbox-refined `clip` per floor frame, and computes per-floor `offset`s by voting-based grid-line correlation (label-free; TArch grids live on layer `DOTE`, not `AXIS`). 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). Read its report: `WEAK grid match` floors need overlay verification; elevation/section frames are listed for floor heights (`z`/`height` from DIM_ELEV 标高 texts like `8.100`), not as floors.
- 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.
- 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.
- 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.
- Run `scripts/derive_showcase_spec.py` to extract line/polyline geometry into `building_spec.json`.
4. Audit extraction before 3D generation.
@@ -129,11 +131,13 @@ The pipeline is designed so a first pass either succeeds or STOPS at a loud gate
A folder like `建筑-1#厂房 / 2#厂房 / 3#辅房 / 总图` is a CAMPUS: several buildings plus a site plan — NOT floors of one building. Never map "one DWG = one floor" here.
- Model each building separately: one detect-frames pass, one extraction config, one `building_spec.json`/GLB per building DWG. Small structures (机械停车坑/水池) are usually one or two frames.
- Assemble with `scripts/assemble_campus.py`: record each building's transform (model anchor -> surveying anchor + campus rotation) in `site_manifest.json` and let the script do the merge — it also runs the mandatory neighbour-gap check automatically.
- Assemble with `scripts/assemble_campus.py`: record each building's transform (model anchor -> surveying anchor + campus rotation) in `site_manifest.json` and let the script do the merge — it also runs the mandatory neighbour-gap check automatically. Buildings on one campus can face different ways (27号: 4#楼 sits ~27° off its siblings): a per-building `rotation_deg` in the manifest overrides the global one.
- Units differ by sheet type: building plans are almost always millimeters (`scale 0.001`), while 总图 site plans are often METERS at real surveying coordinates (huge x/y like 349xxx/663xxx, texts ~2-4 units tall). The extraction config has a single global `scale`, so never mix a meters site plan and mm building plans in one spec.
- Place buildings with a site manifest: from 总图/定位图 (prefer a "带轴号(可点坐标)" version if present) measure each building's anchor point and rotation, then assemble per-building GLBs in the viewer/scene with those transforms. Record the manifest (building -> position/rotation/source) in the notes file.
- Proven placement recipe (贝昂 case): find the building's envelope rectangle in the site drawing (layer 面积核算/建筑轮廓线) — its edge lengths must equal the model's wall-envelope bbox 1:1 (here 90.2 x 42.2 m exactly), edge angle gives rotation (7.57°), the corner matching the model's (min x, min y) gives translation. Resolve the 180° flip by densest-feature voting (e.g. machine-room walls inside a known sub-rect). Then EITHER merge at spec level (transform all segments/footprints/caps into site-local meters and append a SITE context floor) and export one GLB, OR keep per-building GLBs plus transforms in the manifest. Pick a site-local origin (用地红线 min corner), never raw surveying coordinates — float32 breaks at 349 km.
- Anchor placement on WALL evidence, never roof/eave envelopes: 屋面 outlines include canopies and asymmetric overhangs — concentric placement against one put 2# 0.45 m off (26 cm INSIDE its neighbour). Best anchors, in order: corner coordinate callouts (X=/Y= texts), wall lines, envelope rects whose edges equal the wall bbox exactly.
- Site plans without per-building envelope rects (27号 pattern): building outlines may hide on odd layers (EVTR!) — match each closed polyline to its nearest 楼栋 label, then register the model footprint onto the outline with `scripts/register_site_outlines.py` (point-to-edge ICP: brute-force angle + translation refine, trim worst 10%; emits a manifest-ready placement + residual). Constrain `--angle-window` when the outline is visibly axis-aligned — balcony bumps love a tilted false minimum (2# found a 10.75° pit). A building with NO drawn outline can still be anchored from its DIM_COOR corner callouts alone (pair X=/Y= texts, drop points that fall on the garage outline / fire-pad rects), and registering the UNION of several floors' footprints (`--floors F1 F2 F4`) beats one floor when upper wings overhang. Judge residuals: 0.06 m = outline equals model; 0.5-1 m normal with balconies; >2 m = wrong outline/floors, check the overlay. Surveying convention on both 13号/27号 site plans: drawing x = 测绘Y (east), drawing y = 测绘X (north), meters.
- Buildings named on the site plan but with NO delivered drawings (27号 3#/4#): `scripts/massing_from_outline.py --outline pts.json --storeys 22 --height 3.0` builds an honest massing spec (outline-edge walls, footprint slabs, top cap, description marked 总图轮廓体量) and prints manifest-ready anchors — never silently fake a detailed model. Storey counts come from the `22F` labels next to each outline; heights from the sibling tower's ladder.
- Adjacent-building gap sanity check is mandatory: compute the wall-to-wall gap in the shared-edge frame. ~0.15-0.30 m means 贴建 with an expansion joint (变形缝) — corroborate with the neighbour's roof labeled on this building's roof plan and matching floor elevations. Several metres means fire separation. A NEGATIVE gap (overlap) is always a placement bug. Cross-check the chosen position against the boundary: if a hypothesis (e.g. a 10 m fire gap) pushes the building through 用地红线, the hypothesis is wrong.
- Site context is a deliverable, not decoration — a campus scene with only a few boundary lines reads as broken. Run `scripts/site_context_from_dump.py` on the 总图/定位图 dumps: it emits ready-to-merge floors for ground (用地红线 footprint slab), roads + parking stalls (lines, arcs, block-expanded 车位 INSERTs), fence (围墙 as 1.8 m railings), street trees (行道树 INSERT points as green posts, custom `trees` category), and low-confidence massings for context structures drawn only in the site plan (连廊/门卫/消控室, named by nearest label). It takes one plan-copy window (site sheets usually hold several scheme copies), a per-source unit scale (总图 in meters, 定位图 copies in mm), and an exclude-quad so the real building model replaces its own site outline. Buildings that have their own drawing sets get real models placed by the manifest — never fake them as massings.

View File

@@ -1,3 +1,5 @@
> 归档:skill 早期迭代时使用的工作提示词,仅作历史记录;文中路径以当时的仓库布局为准。
# Claude Code 提示词:CAD 展示模型 skill 剩余改进项
(在 /Users/zhengwr/workspace/cad-building-showcase 目录下启动 claude 后粘贴)

View File

@@ -16,15 +16,19 @@
| 门禁/指标 | 贝昂(基线) | 黄桥 | 13号 | 27号 |
|---|---|---|---|---|
| 读图 Warnings 清零 | PASS | PASS(13/13 ok,ODA 兜底×3) | | |
| 图框网格对齐 votes≥3 | PASS | PASS(7框全对齐 x=14 y≥11) | | |
| audit exit 0(三硬门禁) | PASS | PASS | | |
| 无 topless_group / 三角化失败 | PASS | PASS(补 roof_specs 后) | | |
| 邻栋间距门禁 | PASS(0.19m 贴缝) | n/a 单体 | | |
| 裁剪口径覆盖率 | ~40%(多图框正常) | 56.9% | | |
| 幕墙连续率 | 100% | 100%(6/6 层) | | |
| GLB(Draco) | 0.57MB/121节点 | 0.37MB/42节点 | | |
| 目检(渲染+viewer) | PASS | PASS(console 零消息) | | |
| 读图 Warnings 清零 | PASS | PASS(13/13 ok,ODA 兜底×3) | PASS(18/18 ok,ODA 兜底×8;XREF=缓存块解锁) | PASS(13/13 ok,ODA 兜底×9) |
| 图框网格对齐 votes≥3 | PASS | PASS(7框全对齐 x=14 y≥11) | PASS*(塔楼框 votes=0 是正确结论:图签定位+墙剖面相关人工配方,叠图核验) | PASS(1#A 14框对齐;1#B x=21;2# 修参考框后 x=17 全列;墙相关兜底在 B1 首次自动生效) |
| audit exit 0(三硬门禁) | PASS | PASS | PASS(+block_locked WARN 信息性) | PASS×5栋(1#A 四门禁全 PASS;1#B/2#/配电 glazing 合法 SKIP) |
| 无 topless_group / 三角化失败 | PASS | PASS(补 roof_specs 后) | PASS(roof_specs) | PASS(roof_specs 全覆盖) |
| 邻栋间距门禁 | PASS(0.19m 贴缝) | n/a 单体 | PASS(-1.46m=共享地库坡道咬合,放行留痕) | PASS(全正值,min 1.72m) |
| 裁剪口径覆盖率 | ~40%(多图框正常) | 56.9% | b1 51.5% / b2 48.0% | 1#A 76.4% / 1#B 57.3% / 2# 46.0% / 配电 87.2% / 门卫 73.5% |
| 幕墙连续率 | 100% | 100%(6/6 层) | 100%(厂区 30 层全通过) | 1#A 100%(18层);2# 6/6;住宅塔无幕墙合法 SKIP |
| GLB(Draco) | 0.57MB/121节点 | 0.37MB/42节点 | 5.4MB HTML 离线 viewer/127节点 | 2.75MB Draco/520节点(7栋100层) |
| 目检(渲染+viewer) | PASS | PASS(console 零消息) | PASS(离线 viewer console 零错误) | PASS(离线 viewer console 零错误,鸟瞰布局与总图一致) |
三项目 Web 交付(2026-07-03 浏览器实测均零 console 错误、交互正常):
`outputs/huangqiao/viewer_huangqiao.html`(2.9MB)、`outputs/dikuai13/viewer_dikuai13.html`(5.4MB)、
`outputs/dikuai27/viewer_dikuai27.html`(11.5MB,7栋100层)。
黄桥备注:柱仅 5 段(天正柱为 HATCH 填充,架构图不可提取——SKILL.md 已知
限制,需结构图补柱网);F4 幕墙延伸出墙体范围属实(高大厅通高幕墙出现在
@@ -134,6 +138,203 @@ clip 合并——**该能力已存在**:floor_specs 为列表、buckets 按 ke
detect→config→derive 循环;总平面 DIM_COOR 锚点提取与 site_manifest;
assemble_campus 装配 + viewer 目检。
## 13号 解锁:XREF 内容其实在包内(round 5,用户追问促成)
**修正此前"需要设计院补绑定总图"的结论**——用户反问"你不会自己操作吗"
促使深挖,发现被引用内容以 **AutoCAD 缓存块**形式存于宿主 DWG:
`X-00-0011`(总图)块内 5,306 图元、`X-01-0200`(立面)4,443 图元;
modelspace 只有 INSERT 桩,读图报告按 msp 计数误报 near_empty。
libredwg 丢 xref 标志、ODA 保留 `xref_path=".\\X-01-0200.dwg"` 但 flags=0
——两条转换路径都把缓存内容导成普通块定义,**expand_blocks 即等效绑定**。
证据要点:总图块内层名带 `X-00-0011$0$` 绑定前缀(0-规划道路/0-景观树木/
0-地面停车/0-消防环线/栏杆/DIM_COOR×40);单位为米制测绘坐标
(x≈55km, y≈57km,同贝昂总图形态);楼栋尺度轮廓在 `...$dx` 层。
**待落地的 skill 改进(下一轮 TDD)**:
1. cad_dxf_report 的 near_empty/xref_shell 判定要检查"INSERT 引用的块内
实体数"——桩+大块 = 缓存 XREF,提示 expand_blocks 而非"找用户要文件";
xref_definitions 收集也要识别 flags=0 但 xref_path 非空/块名 X-* 的情况。
2. detect_sheet_frames 的标题扫描要进入此类大块(当前只扫 msp 文本)。
3. 一号楼翼间距锚:总图 dx 层楼栋轮廓 + 40 个 DIM_COOR 坐标标注;
立面块 X-01-0200 可实证层高表。
## 13号 round 6:一号楼全楼重锚完成(2026-07-02 深夜续)
**撤回之撤回:85.8m 双塔间距是对的。** 总平面缓存块 X-00-0011(藏在
A-00-011-099_t3.dwg,msp 只有 3 个桩 + 两个 1:500 A0 框)展开后实测:
- 三塔同转角 157.668°、同长 49.80m:A座 ctr(56728.78,57289.85)、
B座 ctr(56649.42,57322.45)、二号楼 ctr(56585.65,57348.81)(OBB 49.8×22.5/22.2)
- **B→A 中心距 85.80m、横向偏差 0.00m**;B→二号楼 69.00m 同列
- 图纸内 `__2`/`__3` 标准层框 offset 差恰 85,800mm——图内相对位置=真实位置
(全 DXF 共享一个绘图原点)。当时撤回的理由("F1 70m 装不下双塔")错了:
F1 其实画在 **加长A0(178.35×84.1m @1:100)** 上、全楼一张图,检测器按
sheet pitch(≈55m) 的粗窗把它截半了。
- 交叉验证:85.8+49.8=135.6m + 外墙 = 138.6m = B1 提取跨度 ✓
- 其余锚:办公A/B座 10F H=46.55(女儿墙46.40);裙房 2F H=12.30(12.15);
二号楼 16F H=57.95(57.80);±0.00=4.30 绝对标高;测绘惯例图面x=测绘Y。
已固化 outputs/dikuai13/site_anchors.json(含地下室轮廓 70 点)。
**重锚方法(无轴网楼栋的通用配方,已人工验证,待 TDD 进 skill)**:
1. **共享 x 原点判定**:F3 图幕墙 x=[276262..326062] 与 A座标准层逐毫米相等
→ 同列图纸共享 x,offset_x 全部统一为标准层的 268914.9。
2. **墙体 y 剖面互相关**:塔柱列(两塔 x 带)内墙段按 y 直方图(20mm 桶,
长度加权),与标准层互相关取峰 → 每张图的 y 平移。双塔独立求解全部 Δ=0mm
互证;且 F1/F2/F3 行间平移恒等图框行距 85,100mm,再证。
3. 修正量:F1 偏 x+75.6m/y+12.9m;F2 偏 y+18.4m;**F3 错槽 85.8m(A座三层
被锚到 B座)**;PH 偏 y+4.3m;RF 偏 x≈11m/y+11.3m——而旧 audit
floors_aligned 全 PASS(门禁对"自洽但整体错位"失明,需要跨层公共基准)。
4. F2/F3 图面北缘的楼梯/前室大样混入 → clip y 带宽剔除(与黄桥图签图例同族;
isolated-cluster 阈值逮不住 20m 外 6m 大盒)。右侧簇 45 框全是核心筒详图,
当楼层框检出全 WEAK——详图簇要能识别丢弃。
5. 结果:spec 重导 12 层,F4-F10 双塔 135.6×22.5 ✓,F1 158.7m(含两端
地库坡道,与总图"地库入口/出口"位置吻合)✓,门禁 3 PASS +
block_locked WARN(并行会话新门禁,信息性);b1.glb 64 节点重建,
顶视/轴测目检通过(双塔立于裙房、比例正确)。
**新增 skill TODO(本轮实证出的缺口)**:
- detect_sheet_frames 应优先用图签块 INSERT(A0/A1/A2*_V1 + scale)定图框矩形,
pitch 窗口只做兜底——加长A0 被 pitch 截半就是教训。
- "共享原点 + 墙剖面相关"要成为 votes=0 时的自动对齐路径(先验证共享 x,
再 1D y 相关,双塔/双列一致性做置信度)。
- floors_aligned 门禁要加跨层公共基准核验(如标准层墙罩盒 vs 各层同列内容)。
## 13号 round 7:二号楼 + 厂区装配完成(地上部分收口)
**二号楼(A-02-0100)** 图册干净:左列 5 张 A1(1:100)纵排、行距 60,400,
一层/二层/标准层/机房/屋顶各一张;右侧全是核心筒详图(与 b1 同病,检出即弃)。
- 共享 x 逐毫米成立;墙剖面相关的 y 平移 = ±k×60,400 严格整数倍(内容随框恒位)。
- 剖面标高序列实证层高表:F1=0/6.0、F2=6.0/3.4、F3=9.4/3.4(无独立图,
沿用二层平面)、F4–F16=12.8+3.4k、主屋面 57.0、女儿墙 57.8/58.0、
机房顶 61.2、塔冠幕墙 63.4——**与总图标注 63.4 独立吻合**。
- 塔身提取 49.8×22.2 与总图 OBB 完全一致;门禁 3 PASS + block_locked WARN;
b2.glb 63 节点;F2 与标准层轮廓叠图重合。
- 坑:floor_order 从 b1 抄来只有 F1..F10 → F11-F16 被静默滤掉("floors":12
才暴露)。skill TODO:derive 应在 config floors 里出现但 floor_order 缺失时
大声告警而不是静默丢层。
**厂区装配(assemble_campus)**:锚=总图缓存块实测塔心 OBB 中心,
rotation −22.332°;一二号楼包络重叠 −1.46m 经叠图核验为**缝隙共享地库坡道**
(两张一层图各画一半、互补咬合非重复)→ --allow-overlap 放行并留痕。
campus_spec 30 层/2 楼,dikuai13_campus.glb 127 节点,轴测目检与总图排布一致。
产物:site_anchors.json / site_manifest.json / campus_spec.json /
dikuai13_campus.glb / campus_iso.png / stack_check2.png / b2_verify.png。
**范围说明**:地下车库(A-03,B1/B2/夹层多分区)为地下体量,showcase 默认
不展示,本轮不建模;一层两端地库坡道挡墙已随 F1 提取呈现。待需要时按
右簇分区图+人防图纸另行拼接。
## 27号 round 5-8:三大体量 + 总平面配准 + 厂区装配(2026-07-03,全程收口)
**1#综合楼A(17F办公,0908_t3)**:剖面标高梯干净(0/4.5/.../76.5,机房顶79.5,
女儿墙80.1——图框检测聚合列里的 2.25 步进是楼梯半层平台,逐框probe即排除)。
四层是裙房顶大平层(办公区/楼梯/露台标注俱在,2-2剖面止于18.0 证裙房=F1-F4)
——初判"clip 吞邻框"是误判,唯一真污染是 F6 clip 上缘越入 F5 图纸下缘(收紧
y 带解决)。屋顶平面框只有 S-BEAM/单线/落水管,弃用,主屋面 roof_specs 从
F17 出板。18 层四门禁全 PASS,幕墙连续 100%。
**1#B区(10F,租赁_t3)**:标准层平面由**户型块拼装**(hxt11/hxt22 各含 75 段
WALL 线,轴网在 $TD_AUDIT_GENERATED_(6792) 块)——按名单展开丢墙,必须
expand_blocks=true 全展开。首版 clip 被假 x-pitch 砍半(右侧详图簇同排标题
制造 pitch_x≈15.8k),楼被切掉整翼——检测器修复后全宽恢复(44.9×17.3 ↔ 总图
轮廓 40×14.5 ✓)。精修 clip 会吞上一张图纸的层间杂条:按各层墙 y 簇裁带解决。
层高实证 F1/F2=4.5、F3-F9=2.95、F10=2.85、机房顶35.5。
**2#(22F住宅,_t7_t3)**:此前"全 WEAK"的根因是**参考框选错**——检测器把
"非机动坡道一层平面图"当参考(辅助构筑物,轴网与塔楼无关)。修复参考框排序后
主列 votes x=17 y=7 全对齐;墙剖面互相关兜底在 B1 上首次自动生效
(coverage 0.86/0.83)。墙在绑定前缀层(12314$0$WALL)须 *WALL* 通配且
glazing 在 walls 之前匹配。3.0m×22 层梯(0..66,机房顶69)。
**总平面配准(A-00-001定位图)**:图面坐标=测绘米制(x=测绘Y东、y=测绘X北,
与13号同惯例,52 个 X=/Y= 坐标标注对直接验证)。楼栋轮廓藏在 **EVTR 层**
(六栋闭合多段线按最近楼栋标签认领);1#A **没有画轮廓**,只有 DIM_COOR 角点
——剔除车库轮廓线/消防登高场地上的标注点后,用"模型多层 footprint 并集 对
角点集"点-边 ICP 配准(θ=-2.15°,与 1B 的 -2.1° 场地统一倾角互证)。轴对齐
轮廓要锁角度窗(阳台齿会造出 ~10° 的伪极小值——B2 教训)。配电房配准残差
0.063m(轮廓 9.2×19.2 与模型毫米级吻合)。**总图还揭示 3#/4# 两栋 21-22F
住宅无交付图纸**:按 EVTR 轮廓×层数×3.0m 出诚实体量块(spec 标注"总图轮廓
体量")。门卫模型(42.8m)与总图雨篷(17.4m)尺寸不符,按重心放置留痕待查。
**装配**:assemble_campus 新增每栋 rotation_deg(4#楼独自斜置 ~27°);
7栋100层,邻栋间距全正(min 1.72m),dikuai27_campus.glb 520节点/50.6MB
(Draco 2.75MB)。离线 viewer 浏览器实测零 console 错误,鸟瞰与总图一致。
## 泛化缺口与修复清单(27号 round 5-8 新增,全部 TDD 带回归)
12. **辅助构筑物标题抢参考框**(2#全WEAK根因):ref_rank 只认 key=="F1",
"非机动坡道一层平面图"先到先得。修复:标题纯度判定(楼层词+平面图 之外
有前缀=辅助),辅助框永不做参考并在报告标记;纯 F1 族优先。回归 auxref 场景。
13. **votes=0 的墙剖面互相关自动对齐**(13号 round 6 人工配方进代码):
墙位置直方图(长度加权,x/y 独立),coarse 500mm 投票 + fine 50mm 精化,
coverage≥0.35 且峰比≥1.5 才接受(防止坡道对塔楼的伪相关),报告
`wall-correlated` 而非静默 WEAK。回归 nogrid 场景(clip 角点必错 20m)。
14. **散排标题伪造 x-pitch 砍半 clip**(1#B 整翼被切):pitch_y 存在且
pitch_x < 0.7×pitch_y 时判伪弃用(真实 2D 图纸网格的 pitch_x≈图宽,
不会远小于图高)。回归 mixedrow 场景。
15. **缓存 XREF 识别**(13号 round 5 教训进代码):cad_dxf_report 新增
`insert_block_content`(msp INSERT 引用块的实体量),近空 msp + 块内
≥200 实体 → `cached_xref_content` 警告(提示 expand_blocks≈bind),
不再误导"找用户要绑定导出";detect_sheet_frames 标题扫描进展开块
(13号形态:图名也在缓存块内)。回归 cachedxref/blocktitle 场景。
16. **floor_order 缺口静默丢层**(13号 b2 F11-F16 消失教训):derive 对
"drawings 有但 floor_order 没有"与"floor_order 有但无图产出"两个方向
都大声告警。回归 fo_config 场景。
17. **assemble_campus 每栋 rotation_deg**(27号 4#楼独自斜置):manifest
每栋可覆盖全局旋转。回归 90° 旋转场景。
18. **凹包桥接双塔生成横跨楼板**(13号 一号楼,用户 viewer 目检发现):
一层 key 装 A/B 两塔时 concave_hull 对全部点只出一个包,
use_footprint_slabs 在 36m 空隙上逐层铺板(侧视=塔间"三角连接")。
修复:出包前按端点邻近分簇(footprint_cluster_linkage 6m,网格桶并查集,
段两端强制同簇),每簇独立凹包——真连廊因连廊墙自然连通不受影响。
修后 F4-F10 = 2×49.8m 独立塔包(与总图 OBB 一致);黄桥 F4/RF 北侧
1.4m 长条构件也随之脱离主包(更诚实);27号 各楼无回归。回归 twintower
场景(两簇 40m 距,断言 2 包且无 25m+ 跨包)。教训:**门禁与顶视图对
桥接楼板都不敏感,侧视/正视目检必须看"楼间空气"**——已列入 DoD 目检项。
19. **图签块 INSERT 定图框**(留档项③落地,13号 加长A0 教训):detect 预扫
msp 中 A0/A1/A0+0.5_V1/图框/图签 类块名的 INSERT,世界 bbox 通过尺寸/
长宽比合理性检验后作为该框 clip 窗(墙精修结果 clamp 在框内,不吞邻图);
13号 b1 实测 45 框全部由图签矩形定窗。回归 titleblock 场景(加长A0 一框
双塔,pitch 窗必截半)。
20. **floors_aligned 跨层墙基准核验**(留档项⑤落地,13号 F3 错槽教训):
audit 对同组楼层做墙剖面互相关(对墙量最大的参考层),强峰在非零位移
(|shift|>1m,coverage≥0.45,ratio≥1.5)→ FAIL "自洽但整体错位"。
**零位移护栏**:目标层在原位已贴合(zero_cov≥0.7×best)则不报——
密集裙房参考层会让小轮廓层"哪儿都能贴上"(27号 1#A PH 在 1.5m 处
出过伪峰)。回归 crossdatum 场景(错槽 FAIL/对槽 PASS)+ 三项目审计
无误报。
21. **门卫"尺寸不符"溯源结论(非缺陷)**:模型 42.8m 是大门建筑组
(两侧门房 x 0-8/21-29 + 端部围墙 39-42 + 中间门洞幕墙带),总图只画
岗亭符号(2.4m 八边形)+门头雨篷(17.4m)——表达粒度不同,重心放置合理,
结案。
22. **场地机制产品化 + config 自动化**(本轮以会话脚本验证的能力固化进
scripts/):`register_site_outlines.py`(点-边 ICP 配准 CLI,manifest
片段直出,残差>2m 大声告警)、`massing_from_outline.py`(轮廓×层数
体量 spec CLI);detect 三项:多层合并图名自动展开(四、六、八/
十一至十四 → 每层一条 config 条目,13号 b2 静默丢层的根源性预防)、
复合中文数字解析(十一/二十一 不再变 F0 键)、逐框标高梯 + 均匀步进
层高建议(27号 2# 实测:19 层枚举图名自动展开、step 3.0×11 建议命中;
建议只是证据不自动填 z——楼梯剖面的半层节拍是反例)。回归 +11 项。
23. **查漏门禁四件套**("新项目会不会漏"的正面回应——全部是账目/互证型
不变量,对没见过的方言天然有效):
- `frame_ledger`(audit --frames):检出框必须入 config 或列入
`discarded_frames` 带理由——静默弃用的框正是整翼消失的所在;
- `area_declared`(config `declared_areas_m2`):模型 footprint 面积对
经济技术指标表/标注互证(±15% 默认)——1#B 半栋消失只有总图能暴露;
- `storey_count`(config `expected_storeys_above_ground`):地上层数对
总图 22F 标签/标高梯级数互证;
- `unknown_layer_dialect`(读图报告):平面文件无任何 *WALL*/*墙* 类图层
时点名"陌生方言,先自觉建映射"。
三门禁未布防时 SKIP(既有项目零影响),新项目应全部布防。回归 +8 项。
**仍留档**:⑦ 未命名详图簇(核心筒大样)仍靠 clip 带宽人工剔除,标题纯度
只覆盖有名字的辅助框(需要"详图簇 vs 楼层框"的几何判别设计);2# 的
"十九、二十一层平面图"修改单簇(无障碍改造相关)未并入模型(需用户确认
以哪版为准)。
(待续)
3. **消毒步骤误删 XRECORD 的 999 数值行**(发现于苏州博物馆/test3d-8 首跑):

View File

@@ -151,7 +151,11 @@ def main() -> int:
survey = b.get("survey_anchor_m") or b.get("survey_center_m")
if not anchor or not survey:
raise SystemExit(f"{name}: manifest entry needs model_anchor_m + survey_anchor_m")
xf = make_xf(anchor, survey, origin, cos_t, sin_t)
# Buildings on one campus can face different ways (27号: 4#楼 sits ~27°
# off its siblings) — per-building rotation_deg overrides the global.
b_theta = math.radians(float(b.get("rotation_deg", manifest.get("rotation_deg", 0.0))))
b_cos, b_sin = math.cos(b_theta), math.sin(b_theta)
xf = make_xf(anchor, survey, origin, b_cos, b_sin)
floors = transform_floors(spec, xf)
prefix = str(b.get("prefix", ""))
placed.update({prefix + fk: fl for fk, fl in floors.items()})

View File

@@ -43,6 +43,14 @@ def parse_args() -> argparse.Namespace:
action="store_true",
help="Report gate failures without a nonzero exit code",
)
parser.add_argument(
"--frames",
nargs="*",
default=None,
help="detect_sheet_frames out-config JSON(s): enables the frame-ledger gate "
"(every detected plan frame must be in the extraction config or listed "
"in config discarded_frames with a reason)",
)
return parser.parse_args()
@@ -167,7 +175,8 @@ def spec_counts(spec: dict[str, Any]) -> dict[str, dict[str, int]]:
return result
def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path) -> dict[str, Any]:
def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_dir: Path,
frames: list[dict[str, Any]] | None = None) -> dict[str, Any]:
ezdxf, recover = derive.import_ezdxf(vendor_dir)
patterns = derive.layer_patterns(config)
max_chord = float(config.get("curve_chord_source_length", 750.0))
@@ -358,7 +367,7 @@ def audit(dxf_dir: Path, config: dict[str, Any], spec: dict[str, Any], vendor_di
"top_layers": dict(global_layer_counts.most_common(50)),
"agent_questions": agent_questions(unclassified_layers, global_high_risk, global_insert_names),
}
report["gates"] = evaluate_gates(report, spec, config)
report["gates"] = evaluate_gates(report, spec, config, frames)
return report
@@ -401,14 +410,73 @@ def floors_alignment_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[
"detail": worst[1] + ". Floors are not stacked — per-frame offsets are missing or wrong; "
"run detect_sheet_frames.py and use its clip/offset config.",
}
# Cross-floor datum: envelope centers are blind to "self-consistent but
# misplaced" floors (13号 F3 sat one tower-slot off — 85.8 m — and PASSed:
# the merged twin-tower envelope hid it). Correlate each floor's wall
# profile against the group's reference floor: a strong off-zero peak
# means the whole floor sits N meters from the shared wall datum.
try:
sys.path.insert(0, str(Path(__file__).resolve().parent))
from detect_sheet_frames import correlate_shift, wall_profile
except Exception:
correlate_shift = wall_profile = None # type: ignore
if correlate_shift is not None:
wall_segs: dict[str, list[tuple[float, float, float, float]]] = {}
for fk, floor in spec.get("floors", {}).items():
segs = floor.get("segments", {}).get("walls") or []
if len(segs) >= 10:
wall_segs[fk] = [(s["start"][0], s["start"][1], s["end"][0], s["end"][1]) for s in segs]
by_group: dict[str, list[str]] = defaultdict(list)
for fk in wall_segs:
by_group[derive._cap_floor_group(fk, config)].append(fk)
for grp, keys in by_group.items():
if len(keys) < 2:
continue
ref_key = max(keys, key=lambda k: sum(
math.hypot(s[2] - s[0], s[3] - s[1]) for s in wall_segs[k]))
ref_x = wall_profile(wall_segs[ref_key], 0, axis_tol=0.02, min_len=0.4)
ref_y = wall_profile(wall_segs[ref_key], 1, axis_tol=0.02, min_len=0.4)
def zero_cov(ref_prof, prof, tol: float = 0.25) -> float:
total = sum(w for _, w in prof)
if total <= 0:
return 0.0
matched = sum(w for p, w in prof
if any(abs(p - rp) <= tol for rp, _ in ref_prof))
return matched / total
for fk in keys:
if fk == ref_key:
continue
for axis, ref_prof in ((0, ref_x), (1, ref_y)):
prof = wall_profile(wall_segs[fk], axis, axis_tol=0.02, min_len=0.4)
shift, cov, ratio = correlate_shift(ref_prof, prof, coarse=0.5, fine=0.05)
# a floor already matching IN PLACE is not misplaced, however
# attractive some shifted peak looks (dense podium references
# let any small profile "match" somewhere: 27号 1#A PH)
if shift is not None and zero_cov(ref_prof, prof) >= 0.7 * cov:
continue
if (shift is not None and cov >= 0.45 and ratio >= 1.5
and abs(shift) > 1.0):
return {
"name": "floors_aligned",
"status": "FAIL",
"detail": (
f"cross_floor_datum {grp}: {fk} wall profile matches {ref_key} "
f"only when shifted {round(shift, 1)} m in {'xy'[axis]} "
f"(coverage {cov:.2f}, peak ratio {min(ratio, 99):.1f}) — the floor is "
"self-consistent but misplaced (wrong frame offset / wrong tower slot, "
"13号 F3 错槽 pattern). Re-check that frame's offset against the shared datum."
),
}
return {
"name": "floors_aligned",
"status": "PASS",
"detail": "Wall-bbox centers of same-stack floors coincide.",
"detail": "Wall-bbox centers of same-stack floors coincide; cross-floor wall-profile datum consistent.",
}
def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any]) -> list[dict[str, Any]]:
def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[str, Any],
frames: list[dict[str, Any]] | None = None) -> list[dict[str, Any]]:
"""Hard checks that must pass before 3D generation.
A gate FAIL means the extraction is known-incomplete in a way that high
@@ -491,9 +559,135 @@ def evaluate_gates(report: dict[str, Any], spec: dict[str, Any], config: dict[st
),
}
)
gates.append(frame_ledger_gate(config, frames))
gates.append(declared_area_gate(spec, config))
gates.append(storey_count_gate(spec, config))
return gates
def _rect_overlap_ratio(a: list[float], b: list[float]) -> float:
"""Intersection area / area of rect a (a = the detected frame clip)."""
ax0, ay0, ax1, ay1 = min(a[0], a[2]), min(a[1], a[3]), max(a[0], a[2]), max(a[1], a[3])
bx0, by0, bx1, by1 = min(b[0], b[2]), min(b[1], b[3]), max(b[0], b[2]), max(b[1], b[3])
iw = min(ax1, bx1) - max(ax0, bx0)
ih = min(ay1, by1) - max(ay0, by0)
if iw <= 0 or ih <= 0:
return 0.0
area_a = max((ax1 - ax0) * (ay1 - ay0), 1e-9)
return (iw * ih) / area_a
def frame_ledger_gate(config: dict[str, Any], frames: list[dict[str, Any]] | None) -> dict[str, Any]:
"""Every DETECTED plan frame must be in the config or explicitly discarded.
Frames the Agent silently ignores are exactly where whole floors (or whole
wings) go missing on a new project. Pass detect_sheet_frames' out-config
via --frames; account for unused frames in config
`"discarded_frames": [{"name": ..., "reason": ...}]`.
"""
if not frames:
return {"name": "frame_ledger", "status": "SKIP",
"detail": "No --frames given; frame ledger not checked."}
discarded = {str(d.get("name", "")) for d in config.get("discarded_frames", [])}
cfg_by_file: dict[str, list[dict[str, Any]]] = {}
for drawing in config.get("drawings", []) or []:
cfg_by_file.setdefault(str(drawing.get("file", "")), []).extend(drawing.get("floors", []) or [])
unaccounted: list[str] = []
total = 0
for fcfg in frames:
for drawing in fcfg.get("drawings", []) or []:
file = str(drawing.get("file", ""))
cfg_floors = cfg_by_file.get(file, [])
for frame in drawing.get("floors", []) or []:
total += 1
name = str(frame.get("name", ""))
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
):
continue
unaccounted.append(f"{file}: {frame.get('key', '?')} {name}")
if unaccounted:
shown = "; ".join(unaccounted[:12]) + (" …" if len(unaccounted) > 12 else "")
return {
"name": "frame_ledger",
"status": "FAIL",
"detail": (
f"{len(unaccounted)}/{total} detected plan frames are neither used by the config "
f"nor listed in discarded_frames: {shown}. Silently ignored frames are where "
"floors/wings vanish — use them or discard them WITH a reason."
),
}
return {"name": "frame_ledger", "status": "PASS",
"detail": f"All {total} detected plan frames are used or explicitly discarded."}
def declared_area_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
"""Model footprint areas must match declared areas (经济技术指标表/标注).
Cross-evidence beats self-consistency: 1#B passed every internal gate with
half the building missing — the site plan exposed it. Config:
`"declared_areas_m2": {"F1": 812, ...}`, optional
`"declared_area_tolerance"` (default 0.15).
"""
declared = config.get("declared_areas_m2")
if not declared:
return {"name": "area_declared", "status": "SKIP",
"detail": "No declared_areas_m2 in config; area cross-check not requested."}
tol = float(config.get("declared_area_tolerance", 0.15))
problems = []
for key, want in declared.items():
want = float(want)
floor = spec.get("floors", {}).get(str(key))
if floor is None:
problems.append(f"{key}: not in spec")
continue
got = float((floor.get("footprint") or {}).get("area") or 0.0)
if got <= 0:
problems.append(f"{key}: no footprint area in spec")
elif abs(got - want) / want > tol:
problems.append(f"{key}: model {round(got, 1)} m² vs declared {round(want, 1)} m² "
f"({round(100 * (got - want) / want):+d}%)")
if problems:
return {
"name": "area_declared",
"status": "FAIL",
"detail": ("Footprint area disagrees with the declared evidence: "
+ "; ".join(problems)
+ f" (tolerance ±{round(tol * 100)}%). A missing wing / swallowed neighbour "
"sheet moves the area far more than balconies do."),
}
return {"name": "area_declared", "status": "PASS",
"detail": f"{len(declared)} floor area(s) within ±{round(tol * 100)}% of declared values."}
def storey_count_gate(spec: dict[str, Any], config: dict[str, Any]) -> dict[str, Any]:
"""Above-ground storey count must match the declared count (总图 22F 标签 / 标高梯级数).
Config: `"expected_storeys_above_ground": 22`. Counts spec floors keyed
F<n> (mezzanines F<n>M, PH, RF, basements excluded).
"""
expected = config.get("expected_storeys_above_ground")
if expected is None:
return {"name": "storey_count", "status": "SKIP",
"detail": "No expected_storeys_above_ground in config; count cross-check not requested."}
import re as _re
actual = sum(1 for k in spec.get("floors", {}) if _re.fullmatch(r"F\d+", str(k)))
if actual != int(expected):
return {
"name": "storey_count",
"status": "FAIL",
"detail": (f"Spec has {actual} above-ground storeys (F<n> keys) but the declared "
f"count is {expected} (总图 label / elevation ladder). A silently dropped "
"floor_order entry or an unexpanded multi-floor frame is the usual cause."),
}
return {"name": "storey_count", "status": "PASS",
"detail": f"{actual} above-ground storeys match the declared count."}
def agent_questions(unclassified_layers: list[dict], high_risk: Counter, insert_names: Counter) -> list[str]:
questions = []
if unclassified_layers:
@@ -587,7 +781,10 @@ def main() -> int:
args = parse_args()
config = derive.read_json(Path(args.config))
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
report = audit(Path(args.dxf_dir), config, spec, Path(args.vendor_dir))
frames = None
if args.frames:
frames = [json.loads(Path(p).read_text(encoding="utf-8")) for p in args.frames]
report = audit(Path(args.dxf_dir), config, spec, Path(args.vendor_dir), frames)
json_path, md_path = output_paths(Path(args.out))
json_path.parent.mkdir(parents=True, exist_ok=True)
md_path.parent.mkdir(parents=True, exist_ok=True)

View File

@@ -4,6 +4,7 @@
from __future__ import annotations
import argparse
import fnmatch
import json
import os
import shutil
@@ -278,6 +279,28 @@ def count_plan_titles(entities) -> int:
return len(seen)
def insert_block_content(doc, entities) -> list[dict]:
"""Entity counts of blocks referenced by modelspace INSERTs.
AutoCAD stores unbound-XREF content as CACHED block definitions inside the
host DWG (13号: X-00-0011 held 5,306 entities while msp had 3 stubs), and
both libredwg and ODA export that cache as ordinary blocks. A "near empty"
msp made of INSERT stubs therefore often has ALL its geometry in-file —
expand_blocks ≈ bind, no re-export needed.
"""
names = {str(e.dxf.name) for e in entities if e.dxftype() == "INSERT"}
out = []
for name in names:
try:
block = doc.blocks[name]
except Exception:
continue
count = sum(1 for _ in block)
if count >= 100:
out.append({"name": name, "entities": count})
return sorted(out, key=lambda b: -b["entities"])[:8]
def file_warnings(item: dict) -> list[str]:
warnings = []
entities = item.get("modelspace_entities")
@@ -291,7 +314,32 @@ def file_warnings(item: dict) -> list[str]:
"This file holds a whole sheet set — never model it as a single floor and never stack frames "
"without per-floor offsets. Run scripts/detect_sheet_frames.py to generate clip/offset config."
)
if xrefs and entities < NEAR_EMPTY_ENTITY_THRESHOLD:
# Unfamiliar layer dialect: a plan file whose layers match NO known wall
# naming (*WALL*/*墙*/QIANG) means a design institute convention this
# pipeline has never seen — the layer mapping must be built consciously,
# or extraction silently captures nothing (patterns age, invariants don't).
wall_dialects = ("*WALL*", "*墙*", "*QIANG*")
layer_names = [l["name"] for l in item.get("layers", []) if l.get("entity_count", 0) > 0]
if (plan_titles >= 1 and (entities or 0) >= 400
and layer_names
and not any(fnmatch.fnmatch(n.upper(), p.upper()) for n in layer_names for p in wall_dialects)):
tops = ", ".join(l["name"] for l in item.get("top_layers", [])[:8])
warnings.append(
f"unknown_layer_dialect: {plan_titles} plan title(s) but no wall-like layer "
f"(*WALL*/*墙*) among {len(layer_names)} populated layers — an unfamiliar design-institute "
f"convention. Map layers consciously before modeling (top layers: {tops})."
)
cached = item.get("insert_block_content") or []
cached_total = sum(b["entities"] for b in cached)
if entities < NEAR_EMPTY_ENTITY_THRESHOLD and cached_total >= 200:
names = ", ".join(f"{b['name']}({b['entities']})" for b in cached[:4])
warnings.append(
f"cached_xref_content: modelspace is only {entities} entities (INSERT stubs) but "
f"block definitions cached INSIDE this file hold {cached_total} entities ({names}). "
"The referenced content is already in the file — expand blocks in detect/derive "
"(expand_blocks ≈ bind); do NOT ask for a re-exported bound DWG."
)
elif xrefs and entities < NEAR_EMPTY_ENTITY_THRESHOLD:
names = ", ".join(x["name"] for x in xrefs[:4])
warnings.append(
f"likely_xref_shell: only {entities} entities but {len(xrefs)} XREF definition(s) ({names}). "
@@ -365,6 +413,7 @@ def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
"bbox": geometry_bbox,
"messages": messages,
"xref_definitions": xref_definitions(doc),
"insert_block_content": insert_block_content(doc, entities),
}
result["warnings"] = file_warnings(result)
return result

View File

@@ -643,20 +643,70 @@ def generated_footprint(segments: dict[str, list[dict[str, Any]]], config: dict[
if len(unique_points) < 4:
return None
# Cluster points by proximity BEFORE hulling: concave_hull over all points
# can never split disconnected masses, so a twin-tower floor got ONE
# bridged hull and use_footprint_slabs laid plates across the 36 m void
# (13号 一号楼 A/B座). Per-cluster hulls keep genuinely linked wings —
# a real 连廊 contributes walls that join the clusters.
linkage = float(config.get("footprint_cluster_linkage", 6.0))
parent = list(range(len(unique_points)))
def find(a: int) -> int:
while parent[a] != a:
parent[a] = parent[parent[a]]
a = parent[a]
return a
def union(a: int, b: int) -> None:
ra, rb = find(a), find(b)
if ra != rb:
parent[rb] = ra
cell = max(linkage, 1e-6)
buckets: dict[tuple[int, int], list[int]] = {}
for idx, (px, py) in enumerate(unique_points):
buckets.setdefault((int(px // cell), int(py // cell)), []).append(idx)
for (bx, by), members in buckets.items():
for gx in (bx - 1, bx, bx + 1):
for gy in (by - 1, by, by + 1):
for other in buckets.get((gx, gy), []):
union(members[0], other)
for other in members[1:]:
union(members[0], other)
# Segments span their endpoints: both ends of one segment belong together.
seg_pt_index = {pt: i for i, pt in enumerate(unique_points)}
for category in categories:
for segment in segments.get(category, []):
start = segment.get("start")
end = segment.get("end")
if not start or not end:
continue
a = seg_pt_index.get((float(start[0]), float(start[1])))
b = seg_pt_index.get((float(end[0]), float(end[1])))
if a is not None and b is not None:
union(a, b)
clusters: dict[int, list[tuple[float, float]]] = {}
for idx, pt in enumerate(unique_points):
clusters.setdefault(find(idx), []).append(pt)
ratio = float(config.get("footprint_concave_ratio", 0.35))
simplify = float(config.get("footprint_simplify_tolerance", 0.12))
min_area = float(config.get("footprint_min_area", 8.0))
polygons = []
try:
hull = concave_hull(MultiPoint(unique_points), ratio=ratio)
if simplify > 0:
hull = hull.simplify(simplify, preserve_topology=True)
if hull.is_empty or hull.area < min_area:
return None
if hull.geom_type == "Polygon":
polygons = [hull]
elif hull.geom_type == "MultiPolygon":
polygons = list(hull.geoms)
else:
for cluster_pts in clusters.values():
if len(cluster_pts) < 4:
continue
hull = concave_hull(MultiPoint(cluster_pts), ratio=ratio)
if simplify > 0:
hull = hull.simplify(simplify, preserve_topology=True)
if hull.is_empty or hull.area < min_area:
continue
if hull.geom_type == "Polygon":
polygons.append(hull)
elif hull.geom_type == "MultiPolygon":
polygons.extend(hull.geoms)
if not polygons:
return None
except Exception:
return None
@@ -978,6 +1028,23 @@ def finalize_spec(
scale = float(config.get("scale", config.get("scale_to_meters", 0.001)))
origin = source_origin(floor_data, config)
ordered_keys = config.get("floor_order") or sorted(floor_data.keys(), key=floor_sort_key)
# floor_order gaps must be LOUD: a stale floor_order copied from a sibling
# config silently dropped 13号 b2 F11-F16 ("floors":12 was the only tell).
missing_from_order = [k for k in floor_data if k not in ordered_keys]
if missing_from_order:
print(
f"WARNING floor_order missing keys {missing_from_order}: these floors are "
"extracted in config drawings but NOT in floor_order — they would be "
"silently dropped. Add them to floor_order (or remove them from drawings).",
file=sys.stderr,
)
ghost_keys = [k for k in ordered_keys if k not in floor_data]
if ghost_keys:
print(
f"WARNING floor_order ghost keys {ghost_keys}: present in floor_order but "
"no drawing produces them — check for typos or missing drawing entries.",
file=sys.stderr,
)
floors: dict[str, Any] = {}
for index, key in enumerate(ordered_keys):

View File

@@ -73,11 +73,51 @@ FLOOR_NAME_KEY = [
def _cn(token: str) -> int:
"""Chinese numeral (1-99, incl. compounds 十一/二十/二十一) or digits to int."""
if token.isdigit():
return int(token)
if not token:
return 0
if "十" in token:
tens, _, ones = token.partition("十")
t = CN_NUM.get(tens, 0) if tens else 1
o = CN_NUM.get(ones, 0) if ones else 0
if tens and t == 0:
return 0
return t * 10 + o
return CN_NUM.get(token, 0)
def covered_floor_numbers(name: str) -> list[int]:
"""Floors covered by a multi-floor plan title, else [].
四、六、八层平面图 -> [4,6,8]; 十一至十四层平面图 -> [11,12,13,14].
One frame standing for N storeys is the norm in Chinese sets — hand-copying
N config entries is exactly where floors got silently lost (13号 b2).
"""
if "地下" in name or "夹层" in name:
return []
m = re.search(r"(?P<seq>[一二三四五六七八九十\d]+(?:(?:[、,,]|[至~~\-—])[一二三四五六七八九十\d]+)+)层", name)
if not m:
return []
nums: list[int] = []
for part in re.split(r"[、,,]", m.group("seq")):
rng = re.split(r"[至~~\-—]", part)
if len(rng) == 2:
a, b = _cn(rng[0]), _cn(rng[1])
if not (0 < a < b <= 99 and b - a <= 40):
return []
nums.extend(range(a, b + 1))
elif len(rng) == 1:
v = _cn(rng[0])
if v <= 0:
return []
nums.append(v)
else:
return []
return nums if len(nums) > 1 else []
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--dxf", required=True)
@@ -188,6 +228,89 @@ def segments_in(entities, clip, layers):
return out
# A plan title is "pure" when everything before 平面图 is floor vocabulary
# (numbers, 地下/夹层/标准层/机房/屋顶...). Any other prefix (非机动坡道/
# 无障碍住房改造/人防...) marks an auxiliary structure or a revision sheet:
# its grid belongs to a DIFFERENT building, so it must never become the
# alignment reference (27号 2#: the bike-ramp frame grabbed F1 and every
# tower frame went WEAK against it).
PURE_TITLE_RE = re.compile(
r"[0-9一二三四五六七八九十百零两FBM#\s层地下夹标准机房屋顶跃阁避难设备转换裙塔、,,~~至\-—.]*平面图$"
)
def title_qualifier(name: str) -> str:
"""Chars before the floor-word core; nonempty => auxiliary-titled frame."""
m = PURE_TITLE_RE.search(name)
return name if m is None else name[: m.start()]
def wall_profile(segs, axis: int, axis_tol: float = 2.0, min_len: float = 400.0):
"""Length-weighted axis positions of straight walls.
axis=0: vertical segments -> x positions; axis=1: horizontal -> y.
Wall positions fingerprint the plan even when NO axis geometry exists
in the frame (13号 tower / 27号 2#): correlating profiles between
frames recovers the true translation where clip-corner anchoring is
off by whole bays (wall bbox min-corner varies with balconies).
Defaults are mm-scale; pass axis_tol/min_len in meters for spec-space use.
"""
out = []
for sx, sy, ex, ey in segs:
dx, dy = abs(ex - sx), abs(ey - sy)
if axis == 0 and dx < axis_tol and dy > min_len:
out.append(((sx + ex) / 2, dy))
elif axis == 1 and dy < axis_tol and dx > min_len:
out.append(((sy + ey) / 2, dx))
return out
def correlate_shift(ref_pos, src_pos, coarse: float = 500.0, fine: float = 50.0):
"""Best d such that {src + d} overlays {ref}, weighted-histogram voting.
Returns (shift, coverage, ratio): coverage = matched mass / min side mass,
ratio = peak mass / best rival peak >=3 coarse bins away. Both gate
acceptance so unrelated structures (a bike ramp vs the tower) refuse to
correlate instead of snapping to a spurious peak.
"""
if len(ref_pos) < 4 or len(src_pos) < 4:
return None, 0.0, 0.0
ref_h: dict[int, float] = defaultdict(float)
src_h: dict[int, float] = defaultdict(float)
for p, w in ref_pos:
ref_h[round(p / coarse)] += w
for p, w in src_pos:
src_h[round(p / coarse)] += w
votes: dict[int, float] = defaultdict(float)
for rb, rw in ref_h.items():
for sb, sw in src_h.items():
votes[rb - sb] += min(rw, sw)
if not votes:
return None, 0.0, 0.0
best = max(votes, key=lambda k: votes[k])
best_mass = votes[best] + 0.5 * (votes.get(best - 1, 0.0) + votes.get(best + 1, 0.0))
rival = max((m for d, m in votes.items() if abs(d - best) >= 3), default=0.0)
total = min(sum(w for _, w in ref_pos), sum(w for _, w in src_pos))
coverage = best_mass / total if total > 0 else 0.0
ratio = best_mass / rival if rival > 0 else float("inf")
# refine around the coarse peak with exact position pairs
center = best * coarse
fine_votes: dict[int, float] = defaultdict(float)
for rp, rw in ref_pos:
for sp, sw in src_pos:
d = rp - sp
if abs(d - center) <= coarse:
fine_votes[round(d / fine)] += min(rw, sw)
if not fine_votes:
return None, 0.0, 0.0
fb = max(fine_votes, key=lambda k: fine_votes[k])
sel = [(rp - sp, min(rw, sw)) for rp, rw in ref_pos for sp, sw in src_pos
if abs((rp - sp) - fb * fine) <= fine]
mass = sum(w for _, w in sel)
shift = sum(d * w for d, w in sel) / mass if mass else center
return shift, coverage, ratio
def main() -> int:
args = parse_args()
ezdxf, recover = import_ezdxf(Path(args.vendor_dir))
@@ -256,9 +379,64 @@ def main() -> int:
continue
for a, b in zip(pts, pts[1:]):
lines.append((layer, a[0], a[1], b[0], b[1]))
elif vkind in {"TEXT", "MTEXT"}:
# Cached-XREF sheets keep their plan TITLES inside the block
# (13号: msp = INSERT stubs only) — classify them like msp text.
classify_text(ve, vkind)
elif vkind == "INSERT":
collect_insert_lines(ve, depth + 1)
def classify_text(entity, kind) -> None:
content = entity_text(entity)
if not content or len(content) > 40:
return
try:
pos = entity.dxf.insert
x, y = float(pos.x), float(pos.y)
except Exception:
return
# MTEXT stores char_height; asking MTEXT for "height" raises
# DXFAttributeError (only undefined-for-type attributes raise).
try:
height_attr = "char_height" if kind == "MTEXT" else "height"
height = float(entity.dxf.get(height_attr, 0) or 0)
except Exception:
height = 0.0
layer = str(entity.dxf.layer)
if plan_title.search(content) and not (plan_exclude and plan_exclude.search(content)):
if not match_any(layer, title_excludes):
titles.append({"name": content, "x": x, "y": y, "h": height, "layer": layer})
elif OTHER_TITLE.search(content) and not match_any(layer, title_excludes):
others.append({"name": content, "x": x, "y": y, "h": height})
# Title-block frame INSERTs (A0_V1 / A0+0.5_V1 / *图框* …) carry the TRUE
# sheet rect. Pitch-sized windows halve elongated sheets (13号 加长A0 held
# both towers in one frame and F1 lost a tower) — prefer the block rect.
frame_block_re = re.compile(r"(?i)(^A[0-4](\+[0-9.]+)?([_\-]|$))|图框|图签|(^TK([_\-]|$))")
frame_rects: list[tuple[float, float, float, float]] = []
for entity in msp.query("INSERT"):
name = str(entity.dxf.name)
if not frame_block_re.search(name):
continue
xs_fb: list[float] = []
ys_fb: list[float] = []
try:
for ve in entity.virtual_entities():
vk = ve.dxftype()
if vk == "LINE":
for p in (ve.dxf.start, ve.dxf.end):
xs_fb.append(float(p.x)); ys_fb.append(float(p.y))
elif vk == "LWPOLYLINE":
for px, py in ve.get_points("xy"):
xs_fb.append(float(px)); ys_fb.append(float(py))
except Exception:
continue
if not xs_fb:
continue
w, h = max(xs_fb) - min(xs_fb), max(ys_fb) - min(ys_fb)
if w >= 20000 and h >= 15000 and 0.3 <= (w / h) <= 4.0: # plausible sheet
frame_rects.append((min(xs_fb), min(ys_fb), max(xs_fb), max(ys_fb)))
for entity in msp:
kind = entity.dxftype()
if kind == "INSERT":
@@ -266,27 +444,7 @@ def main() -> int:
collect_insert_lines(entity)
continue
if kind in {"TEXT", "MTEXT"}:
content = entity_text(entity)
if not content or len(content) > 40:
continue
try:
pos = entity.dxf.insert
x, y = float(pos.x), float(pos.y)
except Exception:
continue
# MTEXT stores char_height; asking MTEXT for "height" raises
# DXFAttributeError (only undefined-for-type attributes raise).
try:
height_attr = "char_height" if kind == "MTEXT" else "height"
height = float(entity.dxf.get(height_attr, 0) or 0)
except Exception:
height = 0.0
layer = str(entity.dxf.layer)
if plan_title.search(content) and not (plan_exclude and plan_exclude.search(content)):
if not match_any(layer, title_excludes):
titles.append({"name": content, "x": x, "y": y, "h": height, "layer": layer})
elif OTHER_TITLE.search(content) and not match_any(layer, title_excludes):
others.append({"name": content, "x": x, "y": y, "h": height})
classify_text(entity, kind)
elif kind == "LINE":
d = entity.dxf
lines.append((str(d.layer), float(d.start.x), float(d.start.y), float(d.end.x), float(d.end.y)))
@@ -327,6 +485,13 @@ def main() -> int:
row = sorted(row)
x_gaps.extend(b - a for a, b in zip(row, row[1:]) if 8000 < b - a < 400000)
pitch_x = statistics.median(x_gaps) if x_gaps else None
# A couple of stray same-row detail titles can fabricate an x-pitch far
# smaller than the sheet height (27号 1#B: 非机动坡道 row → pitch_x≈15.8k vs
# pitch_y≈59k). A real 2D sheet grid has pitch_x ≈ sheet width, never much
# below pitch_y — distrust the fabricated one or clip windows shrink and
# drop whole building wings.
if pitch_x and pitch_y and pitch_x < pitch_y * 0.7:
pitch_x = None
pitch = pitch_y or pitch_x or 98100.0
clip_w = (pitch_x * 0.97) if pitch_x else pitch * args.frame_aspect
clip_h = (pitch_y * 0.97) if pitch_y else (pitch_x or 98100.0) * 2.2
@@ -343,6 +508,13 @@ def main() -> int:
if pitch_x and not pitch_y:
# row layout: title x may sit anywhere under its frame; centre on it
rough = [t["x"] - clip_w * 0.6, t["y"] - clip_h * 0.04, t["x"] + clip_w * 0.6, t["y"] + clip_h]
frame_rect = next((r for r in frame_rects
if r[0] <= t["x"] <= r[2] and r[1] <= t["y"] <= r[3]), None)
if frame_rect is not None:
fw, fh = frame_rect[2] - frame_rect[0], frame_rect[3] - frame_rect[1]
rough = [frame_rect[0] + fw * 0.01, frame_rect[1] + fh * 0.01,
frame_rect[2] - fw * 0.01, frame_rect[3] - fh * 0.01]
notes.append(f"{t['name']}: frame-block rect used for clip window ({fw / 1000:.1f}x{fh / 1000:.1f} m)")
clip = None
for group in refine_groups:
found = segments_in(lines, rough, group)
@@ -351,10 +523,14 @@ def main() -> int:
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
notes.append(f"{t['name']}: no wall/roof geometry in rough clip; using pitch-based clip")
if frame_rect is None:
notes.append(f"{t['name']}: no wall/roof geometry in rough clip; using pitch-based clip")
# Axis geometry lives OUTSIDE the wall-tight clip (axis-number stubs sit
# beyond the facade), so collect grid candidates in an expanded window.
axis_margin = pitch * 0.16
@@ -372,16 +548,27 @@ def main() -> int:
vert.append((sx + ex) / 2)
elif dy < 2.0 and (dx > min_grid_len or tick_min < dx < tick_max):
horiz.append((sy + ey) / 2)
qualifier = title_qualifier(t["name"])
if qualifier:
notes.append(
f"{t['name']}: auxiliary-titled frame (qualifier '{qualifier}') — likely a "
"separate structure or revision sheet; excluded from reference candidacy"
)
floors.append({
"key": floor_key_for(t["name"], used_keys),
"name": t["name"],
"clip": [round(c, 1) for c in clip],
"_vx": cluster_positions(vert, args.grid_bin),
"_hy": cluster_positions(horiz, args.grid_bin),
"_walls": segments_in(lines, clip, wall_layers),
"_aux": bool(qualifier),
})
def ref_rank(f):
return (0 if f["key"] == "F1" else 1, -(len(f["_vx"]) + len(f["_hy"])))
# never anchor on auxiliary structures (bike ramps, 人防 revisions...);
# prefer a pure ground-floor plan, then the richest grid
f1_family = 0 if re.match(r"^F1(_\d+)?$", f["key"]) else 1
return (1 if f["_aux"] else 0, f1_family, -(len(f["_vx"]) + len(f["_hy"])))
reference = sorted(floors, key=ref_rank)[0]
alignment = []
@@ -392,18 +579,60 @@ def main() -> int:
continue
dx, vx = vote_translation(reference["_vx"], f["_vx"], args.grid_bin)
dy, vy = vote_translation(reference["_hy"], f["_hy"], args.grid_bin)
aux_tag = " [auxiliary-titled frame]" if f["_aux"] else ""
if dx is not None and dy is not None and vx >= 3 and vy >= 3:
f["offset"] = [round(dx, 1), round(dy, 1)]
alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}")
else:
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1),
round(reference["clip"][1] - f["clip"][1], 1)]
alignment.append(f"{f['key']}: grid-aligned, votes x={vx} y={vy}, offset={f['offset']}{aux_tag}")
continue
# Grid voting failed (no axis geometry in this frame). Try wall-profile
# correlation before surrendering to the clip-corner anchor, which is
# off by whole bays whenever wall bboxes differ between floors.
wdx, covx, ratx = correlate_shift(wall_profile(reference["_walls"], 0),
wall_profile(f["_walls"], 0))
wdy, covy, raty = correlate_shift(wall_profile(reference["_walls"], 1),
wall_profile(f["_walls"], 1))
if (wdx is not None and wdy is not None
and covx >= 0.35 and covy >= 0.35 and ratx >= 1.5 and raty >= 1.5):
f["offset"] = [round(wdx, 1), round(wdy, 1)]
alignment.append(
f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']} — verify overlay!"
f"{f['key']}: wall-correlated (votes x={vx} y={vy}; coverage x={covx:.2f} "
f"y={covy:.2f}, ratio x={min(ratx, 99):.1f} y={min(raty, 99):.1f}), "
f"offset={f['offset']}{aux_tag} — verify overlay!"
)
continue
f["offset"] = [round(reference["clip"][0] - f["clip"][0], 1),
round(reference["clip"][1] - f["clip"][1], 1)]
alignment.append(
f"{f['key']}: WEAK grid match (votes x={vx} y={vy}); clip-corner fallback offset={f['offset']}{aux_tag} — verify overlay!"
)
for f in floors:
f.pop("_vx"), f.pop("_hy")
f.pop("_vx"), f.pop("_hy"), f.pop("_walls"), f.pop("_aux")
# Expand multi-floor titles (四、六、八层 / 十一至十四层) into one config
# entry per storey sharing the frame's clip/offset — hand-copying N entries
# is where floors silently vanished (13号 b2 F11-F16). z/height stay with
# the Agent: fill them from the storey-elevation evidence, do not guess.
config_floors: list[dict] = []
def _unique_key(key: str) -> str:
base, i = key, 2
while any(cf["key"] == key for cf in config_floors):
key = f"{base}_{i}"
i += 1
return key
for f in floors:
covers = covered_floor_numbers(f["name"])
if covers:
for n in covers:
config_floors.append({"key": _unique_key(f"F{n}"), "name": f"{n}层({f['name']})",
"clip": f["clip"], "offset": f["offset"]})
notes.append(f"{f['name']}: multi-floor title expanded to "
f"{', '.join('F' + str(n) for n in covers)} (same clip/offset; fill z/height per storey)")
else:
config_floors.append({"key": _unique_key(f["key"]), "name": f["name"],
"clip": f["clip"], "offset": f["offset"]})
config = {
"project_name": path.stem,
@@ -413,7 +642,7 @@ def main() -> int:
"origin_strategy": "min",
"drawings": [{
"file": path.name,
"floors": [{k: f[k] for k in ("key", "name", "clip", "offset")} for f in floors],
"floors": config_floors,
}],
}
out_config = Path(args.out_config)
@@ -433,19 +662,20 @@ def main() -> int:
report.extend(f"- note: {n}" for n in notes)
if others:
seen = set()
report.extend(["", "## Elevation/Section frames (for floor heights; not floors)", ""])
frames_e: list[dict] = []
for o in sorted(others, key=lambda o: -o.get("h", 0)):
key = o["name"]
if key in seen:
if o["name"] in seen:
continue
seen.add(key)
report.append(f"- {o['name']} @ ({round(o['x'])}, {round(o['y'])})")
# Storey-elevation suggestions: 标高 texts (e.g. 8.100) inside section/
# elevation frames, clustered. Feed floors[].z/height from these.
seen.add(o["name"])
frames_e.append(o)
# Storey-elevation evidence: 标高 texts (e.g. 8.100) inside section/
# elevation frames, collected PER FRAME (aggregated lists mix stair
# half-landings from 楼梯剖面 into the storey ladder — 27号 1#A lesson).
elev_re = re.compile(r"^-?\d{1,3}\.\d{3}$")
votes: Counter = Counter()
boxes = [(o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06, o["x"] + clip_w * 0.6, o["y"] + clip_h)
for o in others]
ladders: dict[str, set] = {o["name"]: set() for o in frames_e}
boxes = [(o["name"], o["x"] - clip_w * 0.6, o["y"] - pitch * 0.06,
o["x"] + clip_w * 0.6, o["y"] + clip_h) for o in frames_e]
for entity in msp:
if entity.dxftype() != "TEXT":
continue
@@ -456,14 +686,53 @@ def main() -> int:
pos = entity.dxf.insert
except Exception:
continue
if any(b[0] <= pos.x <= b[2] and b[1] <= pos.y <= b[3] for b in boxes):
votes[round(float(content), 3)] += 1
for name, x1, y1, x2, y2 in boxes:
if x1 <= pos.x <= x2 and y1 <= pos.y <= y2:
v = round(float(content), 3)
ladders[name].add(v)
votes[v] += 1
report.extend(["", "## Elevation/Section frames (for floor heights; not floors)", ""])
for o in frames_e:
line = f"- {o['name']} @ ({round(o['x'])}, {round(o['y'])})"
vals = sorted(ladders.get(o["name"], ()))
if vals:
shown = ", ".join(f"{v:+.3f}" for v in vals[:40])
line += f" ladder: {shown}" + (" …" if len(vals) > 40 else "")
report.append(line)
levels = sorted(v for v, n in votes.items() if n >= 2 or (votes[v] >= 1 and -20 < v < 150))
if levels:
report.extend(["", "## Suggested storey elevations (from 剖面/立面 标高 texts)", "",
"- " + ", ".join(f"{v:+.3f}" for v in levels),
"- Interpret with judgment: entries include 室外地坪/女儿墙/雨棚; "
"storey z = consecutive major levels, height = difference."])
# Uniform-step suggestion: the dominant consecutive difference and
# its longest chain. A SUGGESTION for the Agent to verify against
# the 剖面 — stair sections beat at half-storey rhythm (2.25 for a
# 4.5 m storey), so per-frame ladders above are the ground truth.
majors = [v for v in levels if -0.5 <= v <= 200]
diff_votes: Counter = Counter()
for a, b in zip(majors, majors[1:]):
d = round(b - a, 2)
if 2.5 <= d <= 6.5:
diff_votes[d] += 1
if diff_votes:
step = diff_votes.most_common(1)[0][0]
best_chain: list[float] = []
for v0 in majors:
chain, cur = [v0], v0
while True:
nxt = [w for w in majors if abs(w - (cur + step)) <= 0.06]
if not nxt:
break
cur = nxt[0]
chain.append(cur)
if len(chain) > len(best_chain):
best_chain = chain
if len(best_chain) >= 4:
report.append(
f"- suggested storey table: uniform step {step} m x {len(best_chain) - 1} "
f"storeys, z {best_chain[0]:+.3f} → {best_chain[-1]:+.3f} — verify against "
"剖面/立面 per-frame ladders (podium and machine floors may differ)")
Path(args.out_report).write_text("\n".join(report) + "\n", encoding="utf-8")
print(json.dumps({
"config": str(out_config), "report": args.out_report,

View File

@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Honest massing spec from a site-plan outline x storey count x storey height.
For buildings named on the 总平面 but with NO delivered drawings (27号 3#/4#:
EVTR outlines + `22F`/`21F` labels), the honest showcase move is an outline
extrusion clearly labeled as such — never a silently faked detailed model.
The spec slots straight into assemble_campus (per-floor walls from the
outline edges, footprint slabs, top cap) and prints manifest-ready anchors.
Usage:
python3 massing_from_outline.py --outline outline.json --storeys 22 \
--height 3.0 --name dikuai27_b3 [--label "3#楼 22F住宅"] --out spec.json
outline JSON: [[x,y],...] site-plan meters (or {"points": [...]}). The spec is
localized to the outline's min corner; anchors printed as JSON on stdout:
model_anchor_m (local centroid) + survey_anchor_m (site centroid), rotation 0
(the outline is already site-true).
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--outline", required=True, help="JSON [[x,y],...] site meters")
parser.add_argument("--storeys", type=int, required=True)
parser.add_argument("--height", type=float, default=3.0, help="storey height (m)")
parser.add_argument("--name", required=True, help="project_name for the spec")
parser.add_argument("--label", default="", help="human label for the description")
parser.add_argument("--wall-width", type=float, default=0.25)
parser.add_argument("--out", required=True)
args = parser.parse_args()
raw = json.loads(Path(args.outline).read_text(encoding="utf-8"))
pts = raw.get("points") if isinstance(raw, dict) else raw
outline = [(float(p[0]), float(p[1])) for p in pts]
if len(outline) < 3:
raise SystemExit("outline needs at least 3 points")
if args.storeys < 1:
raise SystemExit("storeys must be >= 1")
xs = [p[0] for p in outline]
ys = [p[1] for p in outline]
ox, oy = min(xs), min(ys)
poly = [[round(x - ox, 3), round(y - oy, 3)] for x, y in outline]
bounds = [0.0, 0.0, round(max(xs) - ox, 3), round(max(ys) - oy, 3)]
top_z = round(args.storeys * args.height, 3)
floors = {}
for i in range(1, args.storeys + 1):
walls = [{"start": a, "end": b, "width": args.wall_width, "layer": "MASSING"}
for a, b in zip(poly, poly[1:] + poly[:1])]
floors[f"F{i}"] = {
"name": f"{i}层(总图轮廓体量)",
"z": round((i - 1) * args.height, 3),
"height": args.height,
"bounds": bounds,
"segments": {"walls": walls},
"footprint": {"source": "site_outline", "polygons": [poly]},
"caps": [{"z": top_z, "polygons": [poly]}] if i == args.storeys else [],
}
label = args.label or args.name
spec = {
"project": args.name,
"description": (f"{label}:无交付图纸,按总平面轮廓×{args.storeys}层×{args.height}m "
"出体量(诚实标注,非详图模型)"),
"units": {"scale": 0.001, "origin_source": [ox, oy]},
"categories": {
"walls": {"label": "墙体(体量)", "color": "#d4cbb8", "width": args.wall_width},
"slab": {"label": "楼板", "color": "#c8ccc2", "width": 0.0},
},
"source": {"config": {"use_footprint_slabs": True, "generate_caps": True,
"roof_specs": [], "project_name": args.name}},
"floors": floors,
}
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(spec, ensure_ascii=False), encoding="utf-8")
ctr = [round(sum(p[0] for p in poly) / len(poly), 3),
round(sum(p[1] for p in poly) / len(poly), 3)]
print(json.dumps({
"out": str(out), "floors": args.storeys, "top_z": top_z,
"model_anchor_m": ctr,
"survey_anchor_m": [round(ctr[0] + ox, 3), round(ctr[1] + oy, 3)],
"rotation_deg": 0.0,
}, ensure_ascii=False))
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Register a building model's footprint onto its site-plan outline / corner
callouts by point-to-edge ICP, and emit a site_manifest-ready placement.
Proven on 27号地块: site outlines can hide on odd layers (EVTR), a building
may have NO drawn outline at all (1#A — only DIM_COOR corner callouts), and
per-building rotations differ. This tool answers: given the model footprint
polygon(s) and a set of site points (outline vertices or corner callouts, in
site-plan meters), what rotation + anchor places the model on the site?
Method: brute-force angle sweep (score = trimmed mean distance from each site
point to the nearest transformed footprint edge) + ICP translation refinement.
Constrain --angle-window when the outline is visibly axis-aligned: balcony
teeth love a tilted false minimum (27号 2# found a 10.75° pit before the
window was clamped). Registering the UNION of several floors' footprints
(--floors F1 F2 F4) beats one floor when upper wings overhang.
Usage:
python3 register_site_outlines.py --spec outputs/x/spec_b1.json \
--floors F4 --site-points outline.json [--angle-window -6 6] \
--out registration.json [--prefix 1B]
site-points JSON: [[x, y], ...] (site-plan meters; surveying convention on
both 13号/27号: drawing x = 测绘Y east, drawing y = 测绘X north), or
{"points": [[x, y], ...]}.
Output JSON includes rotation_deg / model_anchor_m (footprint centroid) /
survey_anchor_m / residual_m plus a ready-to-paste manifest_entry. Judge the
residual: 配电房 hit 0.06 m (outline == model), 0.5-1 m is normal with
balconies, several meters means wrong outline or wrong floors — check the
overlay plot before trusting it.
"""
from __future__ import annotations
import argparse
import json
import math
import sys
from pathlib import Path
def dist_pt_seg(p, a, b) -> float:
ax, ay = a
bx, by = b
px, py = p
dx, dy = bx - ax, by - ay
l2 = dx * dx + dy * dy
if l2 == 0:
return math.hypot(px - ax, py - ay)
t = max(0.0, min(1.0, ((px - ax) * dx + (py - ay) * dy) / l2))
return math.hypot(px - (ax + t * dx), py - (ay + t * dy))
def poly_edges(poly):
return list(zip(poly, poly[1:] + poly[:1]))
def centroid(pts):
return (sum(p[0] for p in pts) / len(pts), sum(p[1] for p in pts) / len(pts))
def rot(p, th, c):
x, y = p[0] - c[0], p[1] - c[1]
ct, st = math.cos(th), math.sin(th)
return (x * ct - y * st, x * st + y * ct)
def register(model_polys, site_pts, angle_window=None, coarse=1.0, refine=0.05,
trim=0.9):
"""Best (theta_deg, translation, score) overlaying model polygons on points.
score = trimmed mean distance from each site point to the nearest
transformed model edge (worst 10% dropped: corner callouts include strays).
"""
all_pts = [p for poly in model_polys for p in poly]
mc = centroid(all_pts)
sc = centroid(site_pts)
edges_m = [e for poly in model_polys for e in poly_edges(poly)]
def score_at(th_deg, t):
th = math.radians(th_deg)
edges = [((rot(a, th, mc)[0] + t[0], rot(a, th, mc)[1] + t[1]),
(rot(b, th, mc)[0] + t[0], rot(b, th, mc)[1] + t[1]))
for a, b in edges_m]
ds = sorted(min(dist_pt_seg(p, a, b) for a, b in edges) for p in site_pts)
k = max(1, int(len(ds) * trim))
return sum(ds[:k]) / k
lo, hi = angle_window if angle_window else (-180.0, 180.0)
best = (lo, sc, 1e9)
th = lo
while th < hi + 1e-9:
s = score_at(th, sc)
if s < best[2]:
best = (th, sc, s)
th += coarse
th0 = best[0]
t = list(best[1])
for _ in range(4):
thr = math.radians(th0)
edges = [((rot(a, thr, mc)[0] + t[0], rot(a, thr, mc)[1] + t[1]),
(rot(b, thr, mc)[0] + t[0], rot(b, thr, mc)[1] + t[1]))
for a, b in edges_m]
vecs = []
for p in site_pts:
dmin, q = 1e9, None
for a, b in edges:
ax, ay = a
bx, by = b
dx, dy = bx - ax, by - ay
l2 = dx * dx + dy * dy or 1e-9
tt = max(0.0, min(1.0, ((p[0] - ax) * dx + (p[1] - ay) * dy) / l2))
qq = (ax + tt * dx, ay + tt * dy)
d = math.hypot(p[0] - qq[0], p[1] - qq[1])
if d < dmin:
dmin, q = d, qq
vecs.append((p[0] - q[0], p[1] - q[1], dmin))
vecs.sort(key=lambda v: v[2])
k = max(1, int(len(vecs) * trim))
t[0] += sum(v[0] for v in vecs[:k]) / k
t[1] += sum(v[1] for v in vecs[:k]) / k
best_f = (th0, score_at(th0, t))
dth = -1.5
while dth <= 1.5 + 1e-9:
cand = th0 + dth
if lo - 1e-9 <= cand <= hi + 1e-9:
s = score_at(cand, t)
if s < best_f[1]:
best_f = (cand, s)
dth += refine
th0 = best_f[0]
return th0, tuple(t), score_at(th0, t), mc
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__,
formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--spec", required=True, help="building_spec.json")
parser.add_argument("--floors", nargs="+", required=True,
help="floor keys whose footprints form the registration target")
parser.add_argument("--site-points", required=True,
help="JSON: [[x,y],...] site outline vertices / corner callouts (m)")
parser.add_argument("--angle-window", nargs=2, type=float, default=None,
metavar=("LO", "HI"), help="restrict rotation search (deg)")
parser.add_argument("--out", required=True)
parser.add_argument("--prefix", default="", help="building prefix for the manifest entry")
args = parser.parse_args()
spec = json.loads(Path(args.spec).read_text(encoding="utf-8"))
polys = []
for fk in args.floors:
floor = spec.get("floors", {}).get(fk)
if floor is None:
raise SystemExit(f"floor {fk!r} not in spec")
polys.extend((floor.get("footprint") or {}).get("polygons") or [])
if not polys:
raise SystemExit("no footprint polygons on the requested floors — "
"enable generate_footprints or pick other floors")
raw = json.loads(Path(args.site_points).read_text(encoding="utf-8"))
site_pts = raw.get("points") if isinstance(raw, dict) else raw
site_pts = [(float(p[0]), float(p[1])) for p in site_pts]
if len(site_pts) < 4:
raise SystemExit("need at least 4 site points")
window = tuple(args.angle_window) if args.angle_window else None
th, t, score, mc = register(polys, site_pts, angle_window=window)
result = {
"spec": args.spec,
"floors": args.floors,
"rotation_deg": round(th, 3),
"model_anchor_m": [round(mc[0], 3), round(mc[1], 3)],
"survey_anchor_m": [round(t[0], 3), round(t[1], 3)],
"residual_m": round(score, 3),
"site_points": len(site_pts),
"manifest_entry": {
"spec": args.spec,
"prefix": args.prefix,
"model_anchor_m": [round(mc[0], 3), round(mc[1], 3)],
"survey_anchor_m": [round(t[0], 3), round(t[1], 3)],
"rotation_deg": round(th, 3),
"registration_residual_m": round(score, 3),
},
}
out = Path(args.out)
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, ensure_ascii=False, indent=1), encoding="utf-8")
print(json.dumps({"out": str(out), "rotation_deg": result["rotation_deg"],
"residual_m": result["residual_m"]}, ensure_ascii=False))
if score > 2.0:
print(f"WARNING residual {score:.2f} m is high — wrong outline, wrong floors, "
"or the site points include strays (garage outline / fire pads); "
"plot the overlay before trusting this placement.", file=sys.stderr)
return 0
if __name__ == "__main__":
raise SystemExit(main())

View File

@@ -13,6 +13,7 @@ Run: python3 tests/test_extraction_pipeline.py
from __future__ import annotations
import json
import math
import shutil
import subprocess
import sys
@@ -230,6 +231,233 @@ def make_rowframe_dxf(path: Path, layer_prefix: str = "", grid_style: str = "lin
doc.saveas(path)
def make_auxref_dxf(path: Path) -> None:
"""27号 2# pattern: an auxiliary structure ("非机动坡道一层平面图") sits ABOVE
the main plans, grabs the F1 key, and must NOT become the alignment
reference — its grid is unrelated to the tower's."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def draw_main(oy: float, title: str) -> None:
outline = [((0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
((40000, 20000), (0, 20000)), ((0, 20000), (0, 0))]
interior = [((8000 * i, 0), (8000 * i, 20000)) for i in range(1, 5)]
interior += [((0, 10000), (40000, 10000)), ((12000, 5000), (28000, 5000))]
for (sx, sy), (ex, ey) in outline + interior:
msp.add_line((sx, sy + oy), (ex, ey + oy), dxfattribs={"layer": "WALL"})
for x in (0, 8000, 19000, 26000, 37000, 40000): # varied bays
msp.add_line((x, -3000 + oy), (x, 26000 + oy), dxfattribs={"layer": "DOTE"})
for y in (0, 6000, 10000, 20000):
msp.add_line((-3000, y + oy), (46000, y + oy), dxfattribs={"layer": "DOTE"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, oy - 6000))
# ramp frame on top: tiny 6x10 structure with its own (unrelated) grid
ry = pitch
for start, end in [((0, 0), (6000, 0)), ((6000, 0), (6000, 10000)),
((6000, 10000), (0, 10000)), ((0, 10000), (0, 0)),
((0, 3300), (6000, 3300)), ((0, 7100), (6000, 7100)),
((2500, 0), (2500, 10000))]:
msp.add_line((start[0], start[1] + ry), (end[0], end[1] + ry), dxfattribs={"layer": "WALL"})
for x in (0, 2500, 6000):
msp.add_line((x, ry - 2600), (x, ry + 12600), dxfattribs={"layer": "DOTE"})
for y in (0, 3300, 10000):
msp.add_line((-2600, y + ry), (8600, y + ry), dxfattribs={"layer": "DOTE"})
msp.add_text("非机动坡道一层平面图", height=800,
dxfattribs={"layer": "PUB_TEXT"}).set_placement((2000, ry - 6000))
draw_main(0.0, "一层平面图")
draw_main(-pitch, "二层平面图")
doc.saveas(path)
def make_nogrid_dxf(path: Path) -> None:
"""27号 2#/13号 pattern: frames carry NO axis geometry at all, and floor wall
bboxes differ (F2 covers half the building) — clip-corner fallback is
off by 20 m in x; only wall-profile correlation recovers the offset."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "PUB_TEXT"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def draw_frame(oy: float, title: str, full_walls: bool) -> None:
wall_x0 = 0 if full_walls else 20000
outline = [((wall_x0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
((40000, 20000), (wall_x0, 20000)), ((wall_x0, 20000), (wall_x0, 0))]
# varied interior bays shared by both floors (the correlation fingerprint)
interior = [((26000, 0), (26000, 20000)), ((31000, 0), (31000, 20000)),
((37000, 0), (37000, 20000)), ((20000, 0), (20000, 20000)),
((23000, 0), (23000, 20000)),
((20000, 6000), (40000, 6000)), ((20000, 9400), (40000, 9400)),
((20000, 15000), (40000, 15000))]
if full_walls:
interior += [((6000, 0), (6000, 20000)), ((11000, 0), (11000, 20000)),
((0, 6000), (20000, 6000)), ((0, 15000), (20000, 15000))]
for (sx, sy), (ex, ey) in outline + interior:
msp.add_line((sx, sy + oy), (ex, ey + oy), dxfattribs={"layer": "WALL"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, oy - 6000))
draw_frame(0.0, "一层平面图", True)
draw_frame(-pitch, "二层平面图", False)
doc.saveas(path)
def make_blocktitle_dxf(path: Path) -> None:
"""13号 cached-XREF pattern: each sheet lives in ONE block (msp = INSERT
stubs), so plan TITLES are inside blocks too — title scan must expand."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def make_sheet(idx: int, title: str) -> str:
blk = doc.blocks.new(name=f"X-00-00{idx}")
outline = [((0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
((40000, 20000), (0, 20000)), ((0, 20000), (0, 0))]
interior = [((8000 * i, 0), (8000 * i, 20000)) for i in range(1, 5)]
interior += [((0, 10000), (40000, 10000)), ((12000, 5000), (28000, 5000))]
for (sx, sy), (ex, ey) in outline + interior:
blk.add_line((sx, sy), (ex, ey), dxfattribs={"layer": "WALL"})
for x in (0, 8000, 19000, 26000, 37000, 40000):
blk.add_line((x, -3000), (x, 26000), dxfattribs={"layer": "DOTE"})
for y in (0, 6000, 10000, 20000):
blk.add_line((-3000, y), (46000, y), dxfattribs={"layer": "DOTE"})
blk.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, -6000))
return blk.name
msp.add_blockref(make_sheet(1, "一层平面图"), (0, 0))
msp.add_blockref(make_sheet(2, "二层平面图"), (0, -pitch))
doc.saveas(path)
def make_titleblock_dxf(path: Path) -> None:
"""13号 加长A0 pattern: one ELONGATED sheet holds two towers far apart; the
pitch-sized rough window sees only the tower above the title and the clip
truncates the sheet. Title-block INSERTs (A0+0.5_V1 …) carry the true
frame rect and must define the clip."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT", "TK"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def tower(ox: float, oy: float, bays: tuple) -> None:
outline = [((ox, oy), (ox + 40000, oy)), ((ox + 40000, oy), (ox + 40000, oy + 20000)),
((ox + 40000, oy + 20000), (ox, oy + 20000)), ((ox, oy + 20000), (ox, oy))]
for (sx, sy), (ex, ey) in outline:
msp.add_line((sx, sy), (ex, ey), dxfattribs={"layer": "WALL"})
for b in bays:
msp.add_line((ox + b, oy), (ox + b, oy + 20000), dxfattribs={"layer": "WALL"})
for x in (0, 8000, 19000, 26000, 37000, 40000):
msp.add_line((ox + x, oy - 3000), (ox + x, oy + 26000), dxfattribs={"layer": "DOTE"})
for y in (0, 6000, 10000, 20000):
msp.add_line((ox - 3000, oy + y), (ox + 43000, oy + y), dxfattribs={"layer": "DOTE"})
def frame_block(name: str, w: float, h: float) -> str:
if name not in doc.blocks:
blk = doc.blocks.new(name=name)
blk.add_lwpolyline([(0, 0), (w, 0), (w, h), (0, h)], close=True,
dxfattribs={"layer": "TK"})
return name
# F1: elongated sheet, twin towers 110 m apart inside ONE frame
tower(0.0, 0.0, (8000, 19000, 26000))
tower(110000.0, 0.0, (5000, 14000, 33000))
msp.add_blockref(frame_block("A0+0.5_V1", 179000, 85100), (-12000, -22000))
msp.add_text("一层平面图", height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, -9000))
# F2: normal sheet below, single tower
tower(0.0, -pitch, (8000, 19000, 26000))
msp.add_blockref(frame_block("A1_V1", 85100, 60400), (-12000, -pitch - 22000))
msp.add_text("二层平面图", height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, -pitch - 9000))
doc.saveas(path)
def make_ladder_dxf(path: Path) -> None:
"""Storey-table automation: a multi-floor title (三、五层平面图) must expand
into per-floor config entries, and the 剖面图 frame's DIM_ELEV ladder must
yield per-frame ladders + a uniform-step storey suggestion."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT", "DIM_ELEV"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def draw_frame(oy: float, title: str) -> None:
outline = [((0, 0), (40000, 0)), ((40000, 0), (40000, 20000)),
((40000, 20000), (0, 20000)), ((0, 20000), (0, 0))]
interior = [((8000 * i, 0), (8000 * i, 20000)) for i in range(1, 5)]
interior += [((0, 10000), (40000, 10000))]
for (sx, sy), (ex, ey) in outline + interior:
msp.add_line((sx, sy + oy), (ex, ey + oy), dxfattribs={"layer": "WALL"})
for x in (0, 8000, 19000, 26000, 37000, 40000):
msp.add_line((x, -3000 + oy), (x, 26000 + oy), dxfattribs={"layer": "DOTE"})
for y in (0, 6000, 10000, 20000):
msp.add_line((-3000, y + oy), (46000, y + oy), dxfattribs={"layer": "DOTE"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((18000, oy - 6000))
draw_frame(0.0, "一层平面图")
draw_frame(-pitch, "三、五层平面图")
draw_frame(-2 * pitch, "十一至十四层平面图")
# section frame with an elevation ladder: 0..21 step 3.0 + noise values
sx0 = 120000.0
msp.add_text("1-1剖面图", height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((sx0 + 8000, -6000))
for k in range(8):
v = 3.0 * k
msp.add_text(f"{v:.3f}", height=350,
dxfattribs={"layer": "DIM_ELEV"}).set_placement((sx0 + 2000, 1000 + k * 3000))
for noise in ("0.150", "22.500"):
msp.add_text(noise, height=350,
dxfattribs={"layer": "DIM_ELEV"}).set_placement((sx0 + 6000, 2000))
doc.saveas(path)
def make_mixedrow_dxf(path: Path) -> None:
"""27号 1#B pattern: main plans stack in a COLUMN, but a couple of stray
same-row detail titles fabricate a bogus (much smaller) x-pitch. clip_w
then shrinks to that x-pitch and the refine window drops the building's
second wing (unit-block plans: one wing's midpoint falls outside)."""
doc = ezdxf.new("R2010", setup=True)
for layer in ("WALL", "DOTE", "PUB_TEXT"):
doc.layers.add(layer)
msp = doc.modelspace()
pitch = 98100.0
def draw_frame(oy: float, title: str) -> None:
# two wings: x 0..30000 and 50000..80000 (gap between); title under the LEFT wing
for x0 in (0.0, 50000.0):
outline = [((x0, 0), (x0 + 30000, 0)), ((x0 + 30000, 0), (x0 + 30000, 14000)),
((x0 + 30000, 14000), (x0, 14000)), ((x0, 14000), (x0, 0))]
interior = [((x0 + d, 0), (x0 + d, 14000)) for d in (6000, 13000, 21000)]
for (sx, sy), (ex, ey) in outline + interior:
msp.add_line((sx, sy + oy), (ex, ey + oy), dxfattribs={"layer": "WALL"})
for x in (0, 8000, 19000, 30000, 50000, 61000, 72000, 80000):
msp.add_line((x, -3000 + oy), (x, 17000 + oy), dxfattribs={"layer": "DOTE"})
for y in (0, 5200, 9000, 14000):
msp.add_line((-3000, y + oy), (83000, y + oy), dxfattribs={"layer": "DOTE"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((12000, oy - 6000))
draw_frame(0.0, "一层平面图")
draw_frame(-pitch, "二层平面图")
# stray detail frames titled 平面图 in ONE row of their own, 15 m apart:
# their x-gap is the only same-row gap and must NOT define the clip width
# for the main column (real 1#B: 非机动坡道 frames row made pitch_x≈15.8k)
sy = -250000.0
for i, title in enumerate(("电梯机房平面图", "水箱间平面图")):
ox = 300000.0 + i * 15000.0
for start, end in [((ox, sy), (ox + 8000, sy)), ((ox + 8000, sy), (ox + 8000, sy + 6000)),
((ox + 8000, sy + 6000), (ox, sy + 6000)), ((ox, sy + 6000), (ox, sy)),
((ox + 4000, sy), (ox + 4000, sy + 6000)), ((ox, sy + 3000), (ox + 8000, sy + 3000)),
((ox + 2000, sy), (ox + 2000, sy + 6000)), ((ox + 6000, sy + 3000), (ox + 6000, sy + 6000)),
((ox + 1000, sy + 1500), (ox + 7000, sy + 1500)), ((ox + 1000, sy + 4500), (ox + 7000, sy + 4500))]:
msp.add_line(start, end, dxfattribs={"layer": "WALL"})
msp.add_text(title, height=800, dxfattribs={"layer": "PUB_TEXT"}).set_placement((ox + 1000, sy - 6000))
doc.saveas(path)
def run(cmd: list[str]) -> subprocess.CompletedProcess:
return subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True)
@@ -242,6 +470,19 @@ def main() -> int:
make_plan_dxf(dxf_dir / "plan.dxf")
make_xref_shell_dxf(dxf_dir / "roof.dxf")
# cached-xref sheet (13号 pattern): msp holds only INSERT stubs, the real
# content is CACHED as a block definition inside the same file
cx_doc = ezdxf.new("R2010")
cx_doc.layers.add("WALL")
cx_blk = cx_doc.blocks.new(name="X-00-0011")
for i in range(300):
cx_blk.add_line((i * 100, 0), (i * 100, 5000), dxfattribs={"layer": "WALL"})
cx_msp = cx_doc.modelspace()
cx_msp.add_text("总平面图", dxfattribs={"layer": "PUB_TEXT"})
for i in range(3):
cx_msp.add_blockref("X-00-0011", (i * 50000, 0))
cx_doc.saveas(dxf_dir / "cachedxref.dxf")
# --- cad_dxf_report: XREF shell must be flagged, plan must not ---
proc = run([
sys.executable, "scripts/cad_dxf_report.py",
@@ -254,6 +495,9 @@ def main() -> int:
roof_warnings = " ".join(by_file.get("roof.dxf", {}).get("warnings", []))
check("roof.dxf flagged as XREF shell", "likely_xref_shell" in roof_warnings, roof_warnings)
check("plan.dxf has no warnings", not by_file.get("plan.dxf", {}).get("warnings"), str(by_file.get("plan.dxf", {}).get("warnings")))
cx_warnings = " ".join(by_file.get("cachedxref.dxf", {}).get("warnings", []))
check("cached-xref stub sheet points at expand_blocks", "cached_xref_content" in cx_warnings and "expand_blocks" in cx_warnings, cx_warnings)
check("cached-xref not misreported as re-export ask", "likely_xref_shell" not in cx_warnings and "near_empty" not in cx_warnings, cx_warnings)
md = (WORK / "read_report" / "cad_read_report.md").read_text(encoding="utf-8")
check("markdown has warnings section", "Warnings (resolve before modeling)" in md)
@@ -645,6 +889,416 @@ def main() -> int:
ok_bg = "F2" in bg_off and abs(bg_off["F2"][0]) <= 120 and abs(bg_off["F2"][1] - 98100.0) <= 120
check("block-grid correlation beats clip-corner fallback", ok_bg, str(bg_off))
# --- auxiliary-titled frame must not become the reference (27号 2#) ---
aux_dir = WORK / "dxf_auxref"
aux_dir.mkdir(parents=True, exist_ok=True)
make_auxref_dxf(aux_dir / "auxref.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(aux_dir / "auxref.dxf"), "--out-config", str(WORK / "frames_aux.json"),
"--out-report", str(WORK / "frames_aux.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles aux-titled frames", proc.returncode == 0, proc.stderr[-600:])
if proc.returncode == 0:
aux_md = (WORK / "frames_aux.md").read_text(encoding="utf-8")
ref_line = next((l for l in aux_md.splitlines() if l.startswith("- reference frame:")), "")
check("aux title is not the reference", "非机动坡道" not in ref_line, ref_line)
check("plain 一层平面图 is the reference", "(一层平面图)" in ref_line, ref_line)
frames_aux = json.loads((WORK / "frames_aux.json").read_text(encoding="utf-8"))
aux_off = {f["name"]: f["offset"] for f in frames_aux["drawings"][0]["floors"]}
f2 = aux_off.get("二层平面图")
ok_aux = f2 is not None and abs(f2[0]) <= 120 and abs(f2[1] - 98100.0) <= 120
check("main F2 aligns to main F1 (not ramp)", ok_aux, str(aux_off))
check("aux frame flagged in report", "auxiliary" in aux_md, aux_md[-400:])
# --- gridless frames: wall-profile correlation beats clip-corner (27号 2#/13号) ---
ng_dir = WORK / "dxf_nogrid"
ng_dir.mkdir(parents=True, exist_ok=True)
make_nogrid_dxf(ng_dir / "nogrid.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(ng_dir / "nogrid.dxf"), "--out-config", str(WORK / "frames_ng.json"),
"--out-report", str(WORK / "frames_ng.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles gridless frames", proc.returncode == 0, proc.stderr[-600:])
if proc.returncode == 0:
frames_ng = json.loads((WORK / "frames_ng.json").read_text(encoding="utf-8"))
ng_off = {f["name"]: f["offset"] for f in frames_ng["drawings"][0]["floors"]}
ng_md = (WORK / "frames_ng.md").read_text(encoding="utf-8")
f2 = ng_off.get("二层平面图")
ok_ng = f2 is not None and abs(f2[0]) <= 120 and abs(f2[1] - 98100.0) <= 120
check("wall-profile correlation recovers offset", ok_ng, str(ng_off))
check("wall correlation reported (not silent WEAK)", "wall-correlated" in ng_md, ng_md[-500:])
# --- plan titles inside cached-xref blocks (13号: msp = INSERT stubs only) ---
bt_dir = WORK / "dxf_blocktitle"
bt_dir.mkdir(parents=True, exist_ok=True)
make_blocktitle_dxf(bt_dir / "blocktitle.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(bt_dir / "blocktitle.dxf"), "--out-config", str(WORK / "frames_bt.json"),
"--out-report", str(WORK / "frames_bt.md"), "--vendor-dir", str(VENDOR),
])
bt_ok = proc.returncode == 0
check("detect finds titles inside blocks", bt_ok, (proc.stdout + proc.stderr)[-400:])
if bt_ok:
frames_bt = json.loads((WORK / "frames_bt.json").read_text(encoding="utf-8"))
bt = {f["name"]: f for f in frames_bt["drawings"][0]["floors"]}
check("both block-wrapped frames detected", set(bt) == {"一层平面图", "二层平面图"}, str(set(bt)))
f2 = bt.get("二层平面图")
ok_bt = f2 is not None and abs(f2["offset"][0]) <= 120 and abs(f2["offset"][1] - 98100.0) <= 120
check("block-wrapped frames aligned", ok_bt, str(f2 and f2["offset"]))
# --- title-block INSERTs define clips; elongated sheets must not be halved (13号 加长A0) ---
tb_dir = WORK / "dxf_titleblock"
tb_dir.mkdir(parents=True, exist_ok=True)
make_titleblock_dxf(tb_dir / "titleblock.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(tb_dir / "titleblock.dxf"), "--out-config", str(WORK / "frames_tb.json"),
"--out-report", str(WORK / "frames_tb.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles title-block frames", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
frames_tb = json.loads((WORK / "frames_tb.json").read_text(encoding="utf-8"))
tb = {f["name"]: f for f in frames_tb["drawings"][0]["floors"]}
f1 = tb.get("一层平面图")
ok_tb = f1 is not None and f1["clip"][0] <= 0 and f1["clip"][2] >= 149000
check("elongated-A0 clip spans both towers", ok_tb, str(f1 and f1["clip"]))
tb_md = (WORK / "frames_tb.md").read_text(encoding="utf-8")
check("frame-block clips reported", "frame-block" in tb_md, tb_md[-300:])
# --- cross-floor datum: self-consistent but misplaced floor must FAIL audit (13号 F3 错槽) ---
cd_dir = WORK / "dxf_crossdatum"
cd_dir.mkdir(parents=True, exist_ok=True)
cd_doc = ezdxf.new("R2010", setup=True)
cd_doc.layers.add("WALL")
cd_msp = cd_doc.modelspace()
def cd_tower(ox: float, bays: tuple) -> None:
for start, end in [((ox, 0), (ox + 20000, 0)), ((ox + 20000, 0), (ox + 20000, 10000)),
((ox + 20000, 10000), (ox, 10000)), ((ox, 10000), (ox, 0))]:
cd_msp.add_line(start, end, dxfattribs={"layer": "WALL"})
for b in bays:
cd_msp.add_line((ox + b, 0), (ox + b, 10000), dxfattribs={"layer": "WALL"})
cd_msp.add_line((ox + 2000, 5200), (ox + 18000, 5200), dxfattribs={"layer": "WALL"})
cd_msp.add_line((ox + 1000, 2600), (ox + 19000, 2600), dxfattribs={"layer": "WALL"})
cd_msp.add_line((ox + bays[0] + 800, 0), (ox + bays[0] + 800, 10000), dxfattribs={"layer": "WALL"})
# F1 sheet: towers A (distinct bays) + B, 36 m apart. F2 sheet at x=100000:
# tower-A pattern that belongs in the A slot.
cd_tower(0.0, (3200, 7500, 16100))
cd_tower(36000.0, (4900, 12300, 17700))
cd_tower(100000.0, (3200, 7500, 16100))
cd_doc.saveas(cd_dir / "crossdatum.dxf")
def cd_audit(tag: str, offset_x: float) -> tuple[int, str]:
cfg = {
"scale": 0.001, "generate_footprints": True,
"drawings": [{"file": "crossdatum.dxf", "floors": [
{"key": "F1", "name": "一层", "z": 0.0, "height": 3.0,
"clip": [-2000.0, -2000.0, 58000.0, 12000.0], "offset": [0.0, 0.0]},
{"key": "F2", "name": "二层", "z": 3.0, "height": 3.0,
"clip": [98000.0, -2000.0, 122000.0, 12000.0], "offset": [offset_x, 0.0]},
]}],
}
cfg_path = WORK / f"cd_config_{tag}.json"
cfg_path.write_text(json.dumps(cfg, ensure_ascii=False), encoding="utf-8")
spec_path = WORK / f"cd_spec_{tag}.json"
run([sys.executable, "scripts/derive_showcase_spec.py",
"--dxf-dir", str(cd_dir), "--config", str(cfg_path),
"--out", str(spec_path), "--vendor-dir", str(VENDOR)])
proc = run([sys.executable, "scripts/audit_showcase_extraction.py",
"--dxf-dir", str(cd_dir), "--config", str(cfg_path),
"--spec", str(spec_path), "--out", str(WORK / f"cd_audit_{tag}"),
"--vendor-dir", str(VENDOR)])
md = (WORK / f"cd_audit_{tag}" / "extraction_audit.json").read_text(encoding="utf-8")
return proc.returncode, md
rc_bad, md_bad = cd_audit("bad", -64000.0) # A-pattern lands in the B slot (36 m off)
check("misplaced floor FAILs cross-floor datum", rc_bad != 0 and "cross_floor" in md_bad, md_bad[-400:] if rc_bad == 0 else "")
rc_good, md_good = cd_audit("good", -100000.0) # correct slot
check("correct slot PASSes cross-floor datum", rc_good == 0, md_good[-400:] if rc_good != 0 else "")
# --- multi-floor titles expand; per-frame ladders + storey suggestion (27号/13号 config 手写之痛) ---
ld_dir = WORK / "dxf_ladder"
ld_dir.mkdir(parents=True, exist_ok=True)
make_ladder_dxf(ld_dir / "ladder.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(ld_dir / "ladder.dxf"), "--out-config", str(WORK / "frames_ld.json"),
"--out-report", str(WORK / "frames_ld.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles ladder/multi-floor sheet", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
frames_ld = json.loads((WORK / "frames_ld.json").read_text(encoding="utf-8"))
ld = {f["key"]: f for f in frames_ld["drawings"][0]["floors"]}
check("enumerated title expands (三、五层)", "F3" in ld and "F5" in ld
and ld["F3"]["clip"] == ld["F5"]["clip"], str(sorted(ld)))
check("range title expands (十一至十四层)", all(f"F{n}" in ld for n in (11, 12, 13, 14)),
str(sorted(ld)))
check("compound CN numerals parsed (no F0 keys)", not any(k.startswith("F0") for k in ld),
str(sorted(ld)))
ld_md = (WORK / "frames_ld.md").read_text(encoding="utf-8")
check("per-frame elevation ladder reported", "1-1剖面图" in ld_md and "ladder:" in ld_md, ld_md[-500:])
check("uniform storey step suggested", "suggested storey table: uniform step 3.0" in ld_md, ld_md[-600:])
# --- register_site_outlines.py: ICP registration recovers rotation+translation ---
reg_dir = WORK / "register"
reg_dir.mkdir(parents=True, exist_ok=True)
# model footprint: 30x12 rect with an asymmetric notch (pins the 180° flip)
model_poly = [[0, 0], [30, 0], [30, 12], [8, 12], [8, 9], [0, 9]]
reg_spec = {
"project": "reg", "units": {"scale": 0.001}, "categories": {},
"source": {"config": {}},
"floors": {"F1": {"name": "F1", "z": 0.0, "height": 3.0,
"bounds": [0, 0, 30, 12],
"segments": {"walls": []},
"footprint": {"polygons": [model_poly]}, "caps": []}},
}
(reg_dir / "spec.json").write_text(json.dumps(reg_spec), encoding="utf-8")
th = math.radians(30.0)
site_pts = [[round(x * math.cos(th) - y * math.sin(th) + 500.0, 3),
round(x * math.sin(th) + y * math.cos(th) + 200.0, 3)] for x, y in model_poly]
(reg_dir / "pts.json").write_text(json.dumps(site_pts), encoding="utf-8")
proc = run([
sys.executable, "scripts/register_site_outlines.py",
"--spec", str(reg_dir / "spec.json"), "--floors", "F1",
"--site-points", str(reg_dir / "pts.json"), "--out", str(reg_dir / "reg.json"),
])
check("register_site_outlines runs", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
reg = json.loads((reg_dir / "reg.json").read_text(encoding="utf-8"))
d_rot = abs((reg["rotation_deg"] - 30.0 + 180) % 360 - 180)
check("registration recovers rotation", d_rot <= 0.5, str(reg))
check("registration residual small", reg["residual_m"] <= 0.15, str(reg))
check("manifest fragment emitted", "model_anchor_m" in reg.get("manifest_entry", {}), str(reg.keys()))
# --- massing_from_outline.py: honest massing spec from site outline ---
proc = run([
sys.executable, "scripts/massing_from_outline.py",
"--outline", str(reg_dir / "pts.json"), "--storeys", "5", "--height", "3.0",
"--name", "test_massing", "--out", str(reg_dir / "massing.json"),
])
check("massing_from_outline runs", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
ms = json.loads((reg_dir / "massing.json").read_text(encoding="utf-8"))
fl = ms["floors"]
top = fl[max(fl, key=lambda k: fl[k]["z"])]
check("massing has N floors with walls+footprint",
len(fl) == 5 and all(f["segments"]["walls"] and f["footprint"]["polygons"] for f in fl.values()),
str({k: len(v['segments']['walls']) for k, v in fl.items()}))
check("massing top floor capped", bool(top["caps"]), str(top.get("caps")))
check("massing marked as outline volume", "体量" in ms.get("description", ""), ms.get("description", ""))
# --- bogus x-pitch from stray same-row titles must not shrink clips (27号 1#B) ---
mx_dir = WORK / "dxf_mixedrow"
mx_dir.mkdir(parents=True, exist_ok=True)
make_mixedrow_dxf(mx_dir / "mixedrow.dxf")
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(mx_dir / "mixedrow.dxf"), "--out-config", str(WORK / "frames_mx.json"),
"--out-report", str(WORK / "frames_mx.md"), "--vendor-dir", str(VENDOR),
])
check("detect handles mixed row/column titles", proc.returncode == 0, proc.stderr[-600:])
if proc.returncode == 0:
frames_mx = json.loads((WORK / "frames_mx.json").read_text(encoding="utf-8"))
mx = {f["name"]: f for f in frames_mx["drawings"][0]["floors"]}
f1 = mx.get("一层平面图")
ok_span = f1 is not None and f1["clip"][0] <= 0 and f1["clip"][2] >= 80000
check("clip spans both wings despite stray x-pitch", ok_span, str(f1 and f1["clip"]))
f2 = mx.get("二层平面图")
ok_mx = f2 is not None and abs(f2["offset"][0]) <= 120 and abs(f2["offset"][1] - 98100.0) <= 120
check("mixed layout offset recovered", ok_mx, str(f2 and f2["offset"]))
# --- twin-tower floors must get SEPARATE footprint hulls (13号 一号楼: 凹包桥接
# 两塔, use_footprint_slabs 在 36m 空隙上生成横跨飘板) ---
tt_dir = WORK / "dxf_twintower"
tt_dir.mkdir(parents=True, exist_ok=True)
tt_doc = ezdxf.new("R2010", setup=True)
tt_doc.layers.add("I-WALL")
tt_msp = tt_doc.modelspace()
for ox in (0.0, 60000.0): # two 20m x 10m towers, 40 m of void between
for start, end in [((ox, 0), (ox + 20000, 0)), ((ox + 20000, 0), (ox + 20000, 10000)),
((ox + 20000, 10000), (ox, 10000)), ((ox, 10000), (ox, 0)),
((ox + 7000, 0), (ox + 7000, 10000)), ((ox + 13000, 0), (ox + 13000, 10000)),
((ox, 5000), (ox + 20000, 5000))]:
tt_msp.add_line(start, end, dxfattribs={"layer": "I-WALL"})
tt_doc.saveas(tt_dir / "twin.dxf")
tt_config = {
"scale": 0.001, "generate_footprints": True, "use_footprint_slabs": True,
"drawings": [{"file": "twin.dxf", "floors": [{"key": "F4", "name": "标准层", "z": 12.0, "height": 4.2}]}],
}
tt_cfg = WORK / "tt_config.json"
tt_cfg.write_text(json.dumps(tt_config, ensure_ascii=False), encoding="utf-8")
proc = run([
sys.executable, "scripts/derive_showcase_spec.py",
"--dxf-dir", str(tt_dir), "--config", str(tt_cfg),
"--out", str(WORK / "tt_spec.json"), "--vendor-dir", str(VENDOR),
])
check("derive twin-tower floor runs", proc.returncode == 0, proc.stderr[-400:])
if proc.returncode == 0:
tt_spec = json.loads((WORK / "tt_spec.json").read_text(encoding="utf-8"))
polys = tt_spec["floors"]["F4"]["footprint"]["polygons"]
spans = [max(p[0] for p in poly) - min(p[0] for p in poly) for poly in polys]
check("two separate footprint hulls", len(polys) == 2, f"n={len(polys)} spans={spans}")
check("no hull bridges the void", all(s < 25.0 for s in spans), f"spans={spans}")
# --- leak gates: frame ledger — every detected frame in config OR explicitly discarded ---
fl_frames = WORK / "frames_ledger_probe.json"
proc = run([
sys.executable, "scripts/detect_sheet_frames.py",
"--dxf", str(mf_path), "--out-config", str(fl_frames),
"--out-report", str(WORK / "frames_ledger_probe.md"), "--vendor-dir", str(VENDOR),
])
check("ledger probe detect runs", proc.returncode == 0, proc.stderr[-300:])
fl_detected = json.loads(fl_frames.read_text(encoding="utf-8"))["drawings"][0]["floors"]
fl_f1 = next(f for f in fl_detected if f["name"] == "一层平面图")
def ledger_audit(tag: str, extra: dict) -> tuple[int, str]:
cfg = {
"scale": 0.001,
"drawings": [{"file": "multiframe.dxf", "floors": [
{"key": "F1", "name": "一层平面图", "z": 0.0, "height": 4.2,
"clip": fl_f1["clip"], "offset": fl_f1["offset"]},
]}],
**extra,
}
cfg_path = WORK / f"ledger_cfg_{tag}.json"
cfg_path.write_text(json.dumps(cfg, ensure_ascii=False), encoding="utf-8")
spec_path = WORK / f"ledger_spec_{tag}.json"
run([sys.executable, "scripts/derive_showcase_spec.py",
"--dxf-dir", str(dxf_dir), "--config", str(cfg_path),
"--out", str(spec_path), "--vendor-dir", str(VENDOR)])
proc = run([sys.executable, "scripts/audit_showcase_extraction.py",
"--dxf-dir", str(dxf_dir), "--config", str(cfg_path),
"--spec", str(spec_path), "--out", str(WORK / f"ledger_audit_{tag}"),
"--vendor-dir", str(VENDOR), "--frames", str(fl_frames)])
body = (WORK / f"ledger_audit_{tag}" / "extraction_audit.json").read_text(encoding="utf-8")
return proc.returncode, body
rc_miss, md_miss = ledger_audit("miss", {})
check("unaccounted frame FAILs ledger", rc_miss != 0 and "frame_ledger" in md_miss and "二层平面图" in md_miss,
md_miss[-400:] if rc_miss == 0 else "")
rc_ok, md_ok = ledger_audit("ok", {"discarded_frames": [{"name": "二层平面图", "reason": "测试弃用"}]})
check("explicit discard PASSes ledger", rc_ok == 0, md_ok[-400:] if rc_ok != 0 else "")
# --- leak gates: declared areas + storey count cross-checks (twin-tower scenario) ---
tt_spec_data = json.loads((WORK / "tt_spec.json").read_text(encoding="utf-8"))
tt_area = sum(float(f["footprint"].get("area", 0.0)) for f in tt_spec_data["floors"].values())
def tt_audit(tag: str, extra: dict) -> tuple[int, str]:
cfg = dict(tt_config, **extra)
cfg_path = WORK / f"tt_cfg_{tag}.json"
cfg_path.write_text(json.dumps(cfg, ensure_ascii=False), encoding="utf-8")
proc = run([sys.executable, "scripts/audit_showcase_extraction.py",
"--dxf-dir", str(tt_dir), "--config", str(cfg_path),
"--spec", str(WORK / "tt_spec.json"), "--out", str(WORK / f"tt_audit_{tag}"),
"--vendor-dir", str(VENDOR)])
body = (WORK / f"tt_audit_{tag}" / "extraction_audit.json").read_text(encoding="utf-8")
return proc.returncode, body
rc, body = tt_audit("good", {"declared_areas_m2": {"F4": round(tt_area)},
"expected_storeys_above_ground": 1})
check("area+storey cross-checks PASS on truth", rc == 0, body[-400:] if rc != 0 else "")
rc, body = tt_audit("badarea", {"declared_areas_m2": {"F4": round(tt_area * 2)}})
check("declared-area mismatch FAILs", rc != 0 and "area_declared" in body, body[-400:] if rc == 0 else "")
rc, body = tt_audit("badcount", {"expected_storeys_above_ground": 5})
check("storey-count mismatch FAILs", rc != 0 and "storey_count" in body, body[-400:] if rc == 0 else "")
# --- leak warning: unfamiliar layer dialect must be called out ---
dial_dir = WORK / "dxf_dialect"
dial_dir.mkdir(parents=True, exist_ok=True)
dial_doc = ezdxf.new("R2010")
for layer in ("XQTB-QT", "PUB_TEXT"):
dial_doc.layers.add(layer)
dial_msp = dial_doc.modelspace()
for i in range(500):
dial_msp.add_line((i * 100, 0), (i * 100, 4000), dxfattribs={"layer": "XQTB-QT"})
dial_msp.add_text("一层平面图", dxfattribs={"layer": "PUB_TEXT", "height": 800}).set_placement((20000, -5000))
dial_doc.saveas(dial_dir / "dialect.dxf")
proc = run([
sys.executable, "scripts/cad_dxf_report.py",
"--input", str(dial_dir), "--work", str(WORK / "dialect_work"),
"--output", str(WORK / "dialect_report"), "--vendor-dir", str(VENDOR),
])
check("dialect report runs", proc.returncode == 0, proc.stderr[-400:])
if proc.returncode == 0:
drep = json.loads((WORK / "dialect_report" / "cad_read_report.json").read_text(encoding="utf-8"))
dw = " ".join({i["file"]: i for i in drep["files"]}.get("dialect.dxf", {}).get("warnings", []))
check("unknown layer dialect warned", "unknown_layer_dialect" in dw, dw)
# --- floor_order gaps must warn loudly, not silently drop floors (13号 b2: F11-F16 消失) ---
fo_config = {
"scale": 0.001,
"floor_order": ["1F", "GHOST"],
"drawings": [{"file": "plan.dxf", "floors": [
{"key": "1F", "name": "首层", "z": 0.0, "height": 4.2},
{"key": "2F", "name": "二层", "z": 4.2, "height": 4.2},
]}],
}
fo_path = WORK / "fo_config.json"
fo_path.write_text(json.dumps(fo_config, ensure_ascii=False), encoding="utf-8")
proc = run([
sys.executable, "scripts/derive_showcase_spec.py",
"--dxf-dir", str(dxf_dir), "--config", str(fo_path),
"--out", str(WORK / "fo_spec.json"), "--vendor-dir", str(VENDOR),
])
check("derive with floor_order gaps runs", proc.returncode == 0, proc.stderr[-400:])
check("missing-from-order floor warns", "floor_order" in proc.stderr and "2F" in proc.stderr, proc.stderr[-300:])
check("ghost order key warns", "GHOST" in proc.stderr, proc.stderr[-300:])
# --- assemble_campus: per-building rotation_deg (27号: 4#楼独自斜置) ---
asm_dir = WORK / "assemble"
asm_dir.mkdir(parents=True, exist_ok=True)
def mini_spec(tag: str) -> str:
walls = []
for (sx, sy), (ex, ey) in [((0, 0), (10, 0)), ((10, 0), (10, 20)),
((10, 20), (0, 20)), ((0, 20), (0, 0))]:
walls.append({"start": [sx, sy], "end": [ex, ey], "width": 0.2, "layer": "WALL"})
spec = {
"project": tag, "units": {"scale": 0.001},
"categories": {"walls": {"label": "墙", "color": "#ccc"}},
"source": {"config": {"use_footprint_slabs": True, "roof_specs": []}},
"floors": {"F1": {"name": "F1", "z": 0.0, "height": 3.0,
"bounds": [0, 0, 10, 20],
"segments": {"walls": walls},
"footprint": {"polygons": [[[0, 0], [10, 0], [10, 20], [0, 20]]]},
"caps": []}},
}
p = asm_dir / f"spec_{tag}.json"
p.write_text(json.dumps(spec), encoding="utf-8")
return str(p)
manifest = {
"campus_origin_surveying_m": [0.0, 0.0],
"rotation_deg": 0.0,
"buildings": {
"A": {"spec": mini_spec("a"), "prefix": "A", "model_anchor_m": [0.0, 0.0],
"survey_anchor_m": [0.0, 0.0]},
"B": {"spec": mini_spec("b"), "prefix": "B", "model_anchor_m": [0.0, 0.0],
"survey_anchor_m": [50.0, 0.0], "rotation_deg": 90.0},
},
}
mpath = asm_dir / "manifest.json"
mpath.write_text(json.dumps(manifest), encoding="utf-8")
proc = run([
sys.executable, "scripts/assemble_campus.py",
"--manifest", str(mpath), "--out", str(asm_dir / "campus.json"),
"--project-name", "rot-test", "--allow-overlap",
])
check("assemble_campus per-building rotation runs", proc.returncode == 0, proc.stderr[-500:])
if proc.returncode == 0:
campus = json.loads((asm_dir / "campus.json").read_text(encoding="utf-8"))
bb = campus["floors"]["BF1"]["bounds"]
ok_rot = (abs(bb[0] - 30.0) < 0.01 and abs(bb[1] - 0.0) < 0.01
and abs(bb[2] - 50.0) < 0.01 and abs(bb[3] - 10.0) < 0.01)
check("per-building rotation applied (90deg)", ok_rot, str(bb))
ab = campus["floors"]["AF1"]["bounds"]
ok_a = abs(ab[0]) < 0.01 and abs(ab[2] - 10.0) < 0.01 and abs(ab[3] - 20.0) < 0.01
check("unrotated sibling unaffected", ok_a, str(ab))
# --- isolated legend clusters (黄桥图签窗图例 -> footprint 细三角飘板) ---
iso_dir = WORK / "dxf_isolated"
iso_dir.mkdir(parents=True, exist_ok=True)