Files
cad-building-showcase/scripts/cad_dxf_report.py
zhengwr 9d7d3cb973
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled
fix: enforce Revit roof views and orphan geometry gates
2026-07-21 13:10:04 +08:00

738 lines
31 KiB
Python
Executable File

#!/usr/bin/env python3
"""Batch convert/read CAD drawings and generate a DXF inventory report."""
from __future__ import annotations
import argparse
import glob
import fnmatch
import json
import os
import re
import shutil
import subprocess
import sys
from collections import Counter, defaultdict
from pathlib import Path
CAD_SUFFIXES = {".dwg", ".dxf"}
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, help="Folder containing DWG/DXF files")
parser.add_argument("--work", default="work/cad_showcase", help="Intermediate work folder")
parser.add_argument("--output", default="outputs/cad_read_report", help="Output path stem or folder")
parser.add_argument("--vendor-dir", default="work/vendor", help="Optional Python vendor dir containing ezdxf")
parser.add_argument(
"--no-convert", action="store_true", help="Skip DWG conversion and only read existing DXF files"
)
parser.add_argument(
"--converter",
choices=("auto", "libredwg", "oda"),
default="auto",
help="auto=libredwg then ODA fallback; choose oda explicitly for 3DSOLID/ACIS drawings",
)
parser.add_argument("--allow-partial", action="store_true", help="Write a partial report instead of failing")
parser.add_argument("--partial-reason", help="Required justification when --allow-partial is used")
return parser.parse_args()
def import_ezdxf(vendor_dir: Path):
if vendor_dir.exists():
sys.path.insert(0, str(vendor_dir.resolve()))
try:
import ezdxf # type: ignore
from ezdxf import bbox, recover # type: ignore
except ImportError as exc:
raise SystemExit(
f"Missing dependency: ezdxf. Install locally with:\n python3 -m pip install --target {vendor_dir} ezdxf"
) from exc
return ezdxf, bbox, recover
def safe_name(path: Path, used: set[str]) -> str:
stem = path.stem
candidate = f"{stem}.dxf"
index = 2
while candidate in used:
candidate = f"{stem}-{index}.dxf"
index += 1
used.add(candidate)
return candidate
def find_cad_files(input_dir: Path) -> list[Path]:
return sorted(path for path in input_dir.rglob("*") if path.is_file() and path.suffix.lower() in CAD_SUFFIXES)
def run_dwg2dxf(source: Path, dest: Path) -> dict:
exe = shutil.which("dwg2dxf")
if not exe:
return {
"source": str(source),
"dest": str(dest),
"status": "missing_dwg2dxf",
"message": "Install LibreDWG or use ODA/QCAD/FreeCAD to convert DWG to DXF.",
}
dest.parent.mkdir(parents=True, exist_ok=True)
cmd = [exe, "-y", "-o", str(dest), str(source)]
# libredwg echoes CJK layer/file names in the platform encoding (GBK on
# Chinese drawings), so strict UTF-8 text mode crashes; decode leniently.
proc = subprocess.run(cmd, capture_output=True)
stdout = proc.stdout.decode("utf-8", errors="replace")
stderr = proc.stderr.decode("utf-8", errors="replace")
return {
"source": str(source),
"dest": str(dest),
"status": "ok" if proc.returncode == 0 and dest.exists() else "failed",
"returncode": proc.returncode,
"stdout": stdout[-2000:],
"stderr": stderr[-2000:],
}
def oda_converter() -> str | None:
"""ODA File Converter: env ODA_CONVERTER > PATH > macOS app-bundle default."""
override = os.environ.get("ODA_CONVERTER")
if override:
return override if Path(override).exists() else None
found = shutil.which("ODAFileConverter")
if found:
return found
if sys.platform == "win32":
hits = sorted(
glob.glob(r"C:/Program Files/ODA/*/ODAFileConverter.exe")
+ glob.glob(r"C:/Program Files (x86)/ODA/*/ODAFileConverter.exe")
)
if hits:
return hits[-1]
default = Path("/Applications/ODAFileConverter.app/Contents/MacOS/ODAFileConverter")
return str(default) if default.exists() else None
def run_oda_batch(sources: list[Path], work_dir: Path) -> dict[Path, Path]:
"""Convert DWGs via ODA File Converter; returns {source: produced_dxf}.
ODA converts whole directories with absolute paths and reports bad
arguments via GUI dialogs (silent exit-0), so sources are staged under
ASCII names in a scratch in-dir and results matched back by stem.
"""
exe = oda_converter()
if not exe or not sources:
return {}
in_dir = work_dir / "oda_in"
out_dir = work_dir / "oda_out"
shutil.rmtree(in_dir, ignore_errors=True)
shutil.rmtree(out_dir, ignore_errors=True)
in_dir.mkdir(parents=True)
out_dir.mkdir(parents=True)
mapping: dict[str, Path] = {}
for index, src in enumerate(sources):
stem = f"oda{index:03d}"
shutil.copy2(src, in_dir / f"{stem}.dwg")
mapping[stem] = src
try:
subprocess.run(
[exe, str(in_dir.resolve()), str(out_dir.resolve()), "ACAD2018", "DXF", "0", "1", "*.dwg"],
capture_output=True,
timeout=1800,
)
except (subprocess.TimeoutExpired, OSError):
return {}
produced: dict[Path, Path] = {}
for stem, src in mapping.items():
out = out_dir / f"{stem}.dxf"
if out.exists() and out.stat().st_size > 0:
produced[src] = out
return produced
def sanitize_dxf_comments(source: Path, dest: Path) -> int:
"""Remove DXF group code 999 comment pairs that can break brittle importers.
Operates on BYTES: pre-2007 DXF from libredwg/TArch stores CJK text in the
$DWGCODEPAGE encoding (ANSI_936/GBK). A UTF-8 round-trip with
errors="ignore" silently drops those bytes, mangling every CJK layer/text
("一层平面图" -> "一平图") and breaking plan-title detection downstream, so
the file content must pass through unchanged apart from the comment pairs.
"""
lines = source.read_bytes().splitlines(keepends=True)
dest.parent.mkdir(parents=True, exist_ok=True)
cleaned: list[bytes] = []
removed = 0
index = 0
# DXF is a strict alternation of group-code line / value line, so walk in
# pairs: a bare "999" VALUE (e.g. an integer inside an ODA XRECORD) must
# not be mistaken for a comment group code, or the pair removal shifts
# every following tag and corrupts the file.
while index + 1 < len(lines):
if lines[index].strip() == b"999":
removed += 1
index += 2
continue
cleaned.append(lines[index])
cleaned.append(lines[index + 1])
index += 2
cleaned.extend(lines[index:])
dest.write_bytes(b"".join(cleaned))
return removed
def bbox_tuple(box) -> dict | None:
if not box or not box.has_data:
return None
extmin = box.extmin
extmax = box.extmax
return {
"min": [round(extmin.x, 3), round(extmin.y, 3), round(extmin.z, 3)],
"max": [round(extmax.x, 3), round(extmax.y, 3), round(extmax.z, 3)],
"size": [
round(extmax.x - extmin.x, 3),
round(extmax.y - extmin.y, 3),
round(extmax.z - extmin.z, 3),
],
}
def guess_unit_scale(bbox_data: dict | None, insunits: int) -> dict:
if insunits == 6:
return {"source_units": "meters", "scale_to_meters": 1.0, "confidence": "header"}
if insunits == 4:
return {"source_units": "millimeters", "scale_to_meters": 0.001, "confidence": "header"}
if not bbox_data:
return {"source_units": "unknown", "scale_to_meters": 1.0, "confidence": "none"}
sx, sy, _ = bbox_data.get("size", [0, 0, 0])
largest = max(abs(sx), abs(sy))
if largest > 1000:
return {"source_units": "millimeters", "scale_to_meters": 0.001, "confidence": "bbox_heuristic"}
return {"source_units": "meters_or_unknown", "scale_to_meters": 1.0, "confidence": "bbox_heuristic"}
def read_doc(path: Path, ezdxf, recover):
try:
return ezdxf.readfile(path), []
except (ezdxf.DXFError, ValueError):
# Strict reads can also raise plain ValueError on quirky-but-
# recoverable files (e.g. an XRECORD holding "{ACAD_REACTORS" where a
# handle is expected); recover skips those records.
doc, auditor = recover.readfile(path)
return doc, [str(error) for error in auditor.errors]
# A floor-plan sheet whose real geometry lives in unbound XREFs exports as a
# near-empty shell (a few dozen annotation entities). Modeling it silently
# produces a missing floor, so it must be flagged before extraction.
NEAR_EMPTY_ENTITY_THRESHOLD = 60
BLK_XREF_FLAGS = 4 | 8 # BLK_XREF | BLK_XREF_OVERLAY
def xref_definitions(doc) -> list[dict]:
xrefs = []
for block in doc.blocks:
try:
head = block.block
flags = int(head.dxf.get("flags", 0))
is_xref = bool(flags & BLK_XREF_FLAGS) or bool(getattr(block.block_record, "is_xref", False))
if is_xref:
xrefs.append(
{
"name": str(block.name),
"path": str(head.dxf.get("xref_path", "") or ""),
"overlay": bool(flags & 8),
}
)
except Exception:
continue
return xrefs
PLAN_TITLE_RE = re.compile(r"平面图$")
PLAN_TITLE_EXCLUDE_RE = re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)")
PLAN_TITLE_EXCLUDE_LAYERS = ("*图签*", "*PUB_TAB*", "*TTLB*", "*TK*", "*图框*", "*目录*")
CAD_TEXT_FORMAT_RE = re.compile(r"\\[LlOoKk]|%%[UuOoKk]")
FLOOR_TOKEN_RE = re.compile(
r"机房小屋面|机房屋面|"
r"地下[一二三四五六七八九十\d]+层夹层|"
r"地下[一二三四五六七八九十\d]+层|"
r"[一二三四五六七八九十\d]+层夹层|"
r"[一二三四五六七八九十\d]+层|"
r"首层|底层|夹层|屋顶层|屋顶|屋面|机房层|电梯机房"
)
# AutoCAD MIF escapes (\M+5XXXX): CJK text in pre-Unicode DWGs survives
# DXF conversion as literal escape sequences, so title matching must decode
# them first. The digit selects the codepage; XXXX is the hex byte pair.
MIF_RE = re.compile(r"\\M\+([1-5])([0-9A-Fa-f]{4})")
MIF_CODEPAGES = {"1": "cp932", "2": "big5", "3": "cp949", "4": "johab", "5": "gbk"}
def decode_mif(text: str) -> str:
if "\\M+" not in text:
return text
def repl(match: "re.Match[str]") -> str:
value = int(match.group(2), 16)
raw = value.to_bytes(2, "big") if value > 0xFF else value.to_bytes(1, "big")
try:
return raw.decode(MIF_CODEPAGES.get(match.group(1), "gbk"))
except (UnicodeDecodeError, LookupError):
return match.group(0)
return MIF_RE.sub(repl, text)
def normalize_cad_text(text: str) -> str:
text = CAD_TEXT_FORMAT_RE.sub("", decode_mif(text))
return text.replace("\\P", " ").strip()
def floor_identities(label: str) -> list[tuple[str, str]]:
"""``(building qualifier, floor)`` identities from labels/INSERT names."""
label = normalize_cad_text(label).replace("_", "、")
if label.endswith(("机房小屋面", "机房屋面")):
return [("", "PH")]
if not label.endswith("平面图") or len(label) > 50:
return []
head = label[:-3]
matches = list(FLOOR_TOKEN_RE.finditer(head))
tokens = [match.group(0) for match in matches]
qualifier = re.sub(r"[、,,\s]+$", "", head[: matches[0].start()]) if matches else ""
if len(qualifier) > 12:
qualifier = ""
out = []
for token in tokens:
if token in {"屋顶层", "屋顶", "屋面"}:
out.append("RF")
elif token in {"机房小屋面", "机房屋面", "机房层", "电梯机房"}:
out.append("PH")
elif token == "首层":
out.append("F1")
elif token == "底层":
out.append("B1")
elif token == "夹层":
out.append("F1M")
else:
out.append(token)
return [(qualifier, identity) for identity in out] or [("", label)]
def count_plan_titles(entities) -> int:
"""Distinct plan floors from visible titles and Revit INSERT-name suffixes."""
floor_qualifiers: dict[str, set[str]] = defaultdict(set)
for entity in entities:
kind = entity.dxftype()
if kind == "INSERT":
try:
suffix = str(entity.dxf.name).rsplit("-", 1)[-1]
except Exception:
continue
for qualifier, floor in floor_identities(suffix):
floor_qualifiers[floor].add(qualifier)
continue
if kind not in {"TEXT", "MTEXT"}:
continue
try:
layer = str(entity.dxf.layer)
except Exception:
layer = ""
if any(fnmatch.fnmatch(layer.upper(), pattern.upper()) for pattern in PLAN_TITLE_EXCLUDE_LAYERS):
continue
try:
text = str(entity.dxf.text if kind == "TEXT" else entity.plain_text() or "").strip()
except Exception:
continue
text = normalize_cad_text(text)
if not text or len(text) > 40:
continue
if PLAN_TITLE_RE.search(text) and not PLAN_TITLE_EXCLUDE_RE.search(text):
for qualifier, floor in floor_identities(text):
floor_qualifiers[floor].add(qualifier)
# Revit repeats the same floor suffix across hundreds of family INSERTs;
# a sheet-title block may add ``主楼`` while families remain unqualified.
# Count that as one frame, but retain two genuinely different qualified
# buildings that both contain (say) an F1 plan in the same modelspace.
return sum(max(1, len({q for q in qualifiers if q})) for qualifiers in floor_qualifiers.values())
def insert_block_content(doc, entities) -> list[dict]:
"""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")
xrefs = item.get("xref_definitions", [])
if entities is None:
return warnings
plan_titles = item.get("plan_title_count", 0)
if plan_titles >= 2:
warnings.append(
f"multi_frame_sheet: {plan_titles} plan-frame titles (XX平面图) found in ONE modelspace. "
"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."
)
# 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 = [layer["name"] for layer in item.get("layers", []) if layer.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(layer["name"] for layer 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}). "
"Real geometry lives in the external reference. Bind/insert the XREFs in CAD and re-export this DXF "
"before modeling, otherwise this sheet contributes an empty floor."
)
elif entities < NEAR_EMPTY_ENTITY_THRESHOLD:
warnings.append(
f"near_empty: only {entities} entities (annotation shell?). "
"Confirm with the user whether this sheet should contain geometry; if it is a plan, "
"the source export is incomplete (unbound XREF or wrong layout)."
)
elif xrefs:
names = ", ".join(x["name"] for x in xrefs[:4])
warnings.append(
f"has_xref_definitions: {len(xrefs)} XREF definition(s) ({names}). "
"Entities inside unbound XREFs are NOT in modelspace; verify nothing essential is referenced externally."
)
return warnings
def inspect_file(path: Path, ezdxf, bbox, recover) -> dict:
messages: list[str] = []
try:
doc, recover_messages = read_doc(path, ezdxf, recover)
messages.extend(recover_messages)
msp = doc.modelspace()
entities = list(msp)
type_counts = Counter(entity.dxftype() for entity in entities)
layer_counts = Counter(str(entity.dxf.layer) for entity in entities if entity.dxf.hasattr("layer"))
try:
geometry_bbox = bbox_tuple(bbox.extents(entities, fast=True))
except Exception as exc: # bbox can fail on unsupported proxy geometry.
geometry_bbox = None
messages.append(f"bbox failed: {exc}")
layers = []
for layer in doc.layers:
name = layer.dxf.name
layers.append(
{
"name": name,
"color": int(layer.dxf.color),
"is_off": bool(layer.is_off()),
"is_frozen": bool(layer.is_frozen()),
"entity_count": layer_counts.get(name, 0),
}
)
header = doc.header
insunits = int(header.get("$INSUNITS", 0) or 0)
result = {
"file": path.name,
"path": str(path),
"status": "ok",
"acadver": str(header.get("$ACADVER", "")),
"insunits": insunits,
"measurement": int(header.get("$MEASUREMENT", 0) or 0),
"unit_guess": guess_unit_scale(geometry_bbox, insunits),
"modelspace_entities": len(entities),
"plan_title_count": count_plan_titles(entities),
"entity_types": dict(type_counts.most_common()),
"top_layers": [{"name": name, "entity_count": count} for name, count in layer_counts.most_common(30)],
"layer_count": len(layers),
"layers": sorted(layers, key=lambda item: (-item["entity_count"], item["name"])),
"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
except Exception as exc:
return {"file": path.name, "path": str(path), "status": "failed", "messages": [str(exc)]}
def markdown_report(results: list[dict], conversions: list[dict], input_dir: Path) -> str:
lines = [
"# CAD Read Report",
"",
f"Input: `{input_dir}`",
"",
]
all_warnings = [(item["file"], warning) for item in results for warning in item.get("warnings", [])]
if all_warnings:
lines.extend(["## Warnings (resolve before modeling)", ""])
for file_name, warning in all_warnings:
lines.append(f"- `{file_name}`: {warning}")
lines.append("")
lines.extend(
[
"## Files",
"",
"| File | Status | Entities | Layers | Size X | Size Y | Unit Guess | Main Types |",
"| --- | --- | ---: | ---: | ---: | ---: | --- | --- |",
]
)
for item in results:
bbox_data = item.get("bbox") or {}
size = bbox_data.get("size", ["", "", ""])
unit = item.get("unit_guess", {})
unit_text = f"{unit.get('source_units', '')} x{unit.get('scale_to_meters', '')}"
types = ", ".join(f"{k}:{v}" for k, v in list(item.get("entity_types", {}).items())[:5])
lines.append(
f"| {item['file']} | {item.get('status', '')} | {item.get('modelspace_entities', '')} | "
f"{item.get('layer_count', '')} | {size[0]} | {size[1]} | {unit_text} | {types} |"
)
if conversions:
lines.extend(["", "## DWG Conversion", ""])
for conv in conversions:
lines.append(f"- `{Path(conv['source']).name}` -> `{Path(conv['dest']).name}`: {conv['status']}")
lines.extend(["", "## Top Layers", ""])
for item in results:
lines.append(f"### {item['file']}")
for layer in item.get("top_layers", [])[:12]:
lines.append(f"- `{layer['name']}`: {layer['entity_count']}")
for message in item.get("messages", [])[:8]:
lines.append(f"- message: `{message}`")
lines.append("")
return "\n".join(lines)
def output_paths(output: Path) -> tuple[Path, Path]:
if output.suffix:
return output.with_suffix(".json"), output.with_suffix(".md")
output.mkdir(parents=True, exist_ok=True)
return output / "cad_read_report.json", output / "cad_read_report.md"
def scrub_surrogates(value):
"""Make report data JSON-writable when ezdxf's recover mode leaks
surrogate-escaped bytes (broken files read with errors="surrogateescape").
CJK bytes are recovered via GBK where possible; the batch never dies on
one corrupt drawing."""
if isinstance(value, str):
try:
value.encode("utf-8")
return value
except UnicodeEncodeError:
raw = value.encode("utf-8", errors="surrogateescape")
try:
return raw.decode("gbk")
except UnicodeDecodeError:
return raw.decode("utf-8", errors="replace")
if isinstance(value, dict):
return {scrub_surrogates(k): scrub_surrogates(v) for k, v in value.items()}
if isinstance(value, list):
return [scrub_surrogates(item) for item in value]
return value
def main() -> int:
args = parse_args()
input_dir = Path(args.input)
work_dir = Path(args.work)
raw_dir = work_dir / "dxf_raw"
clean_dir = work_dir / "dxf_sanitized"
vendor_dir = Path(args.vendor_dir)
ezdxf, bbox, recover = import_ezdxf(vendor_dir)
if not input_dir.exists():
raise SystemExit(f"Input folder not found: {input_dir}")
if args.allow_partial and not (args.partial_reason or "").strip():
raise SystemExit("--allow-partial requires --partial-reason")
# These folders are generated intermediates. Recreate them so a source
# removed between runs cannot survive as a stale DXF and enter modeling.
shutil.rmtree(raw_dir, ignore_errors=True)
shutil.rmtree(clean_dir, ignore_errors=True)
raw_dir.mkdir(parents=True, exist_ok=True)
clean_dir.mkdir(parents=True, exist_ok=True)
cad_files = find_cad_files(input_dir)
used_names: set[str] = set()
conversions: list[dict] = []
raw_dxfs: list[Path] = []
assigned = [(source, raw_dir / safe_name(source, used_names)) for source in cad_files]
oda_outputs: dict[Path, Path] = {}
if args.converter == "oda" and not args.no_convert:
oda_outputs = run_oda_batch(
[source for source, _dest in assigned if source.suffix.lower() == ".dwg"],
work_dir,
)
for source, dest in assigned:
if source.suffix.lower() == ".dwg":
if args.no_convert:
continue
if args.converter == "oda":
produced = oda_outputs.get(source)
if produced:
dest.parent.mkdir(parents=True, exist_ok=True)
shutil.copy2(produced, dest)
conversion = {"source": str(source), "dest": str(dest), "status": "oda_ok"}
else:
conversion = {"source": str(source), "dest": str(dest), "status": "oda_failed"}
else:
conversion = run_dwg2dxf(source, dest)
conversions.append(conversion)
if conversion["status"] in {"ok", "oda_ok"}:
raw_dxfs.append(dest)
else:
if source.resolve() != dest.resolve():
shutil.copy2(source, dest)
raw_dxfs.append(dest)
sanitized: list[Path] = []
for raw in raw_dxfs:
dest = clean_dir / raw.name
removed = sanitize_dxf_comments(raw, dest)
sanitized.append(dest)
if removed:
conversions.append({"source": str(raw), "dest": str(dest), "status": f"sanitized_{removed}_comments"})
results = [inspect_file(path, ezdxf, bbox, recover) for path in sorted(sanitized)]
# ODA auto-fallback: libredwg chokes on some TArch DWGs (duplicate handles,
# missing ENDBLK/EOF) or yields an empty modelspace even when the drawing
# is full — the 黄桥 plans sheet read 0 entities via dwg2dxf but 21k via
# ODA. Reconvert those sources through ODA when it is available.
dwg_dest_to_source = {
Path(c["dest"]).name: Path(c["source"])
for c in conversions
if str(c.get("source", "")).lower().endswith(".dwg") and c.get("dest")
}
retry: dict[str, Path] = {}
for item in results:
src = dwg_dest_to_source.get(item.get("file", ""))
if src and (item.get("status") == "failed" or item.get("modelspace_entities") == 0):
retry[item["file"]] = src
for c in list(conversions):
if c.get("status") in {"failed", "missing_dwg2dxf"} and str(c.get("source", "")).lower().endswith(".dwg"):
name = Path(c["dest"]).name if c.get("dest") else Path(c["source"]).with_suffix(".dxf").name
retry.setdefault(name, Path(c["source"]))
if retry and args.converter == "auto":
produced = run_oda_batch(list(retry.values()), work_dir)
for name, src in retry.items():
out = produced.get(src)
if not out:
conversions.append({"source": str(src), "dest": "", "status": "oda_fallback_failed"})
continue
raw_dest = raw_dir / name
shutil.copy2(out, raw_dest)
clean_dest = clean_dir / name
sanitize_dxf_comments(raw_dest, clean_dest)
item = inspect_file(clean_dest, ezdxf, bbox, recover)
replaced = False
for i, existing in enumerate(results):
if existing.get("file") == name:
results[i] = item
replaced = True
break
if not replaced:
results.append(item)
conversions.append({"source": str(src), "dest": str(raw_dest), "status": "oda_fallback_ok"})
results.sort(key=lambda r: r.get("file", ""))
json_path, md_path = output_paths(Path(args.output))
json_path.parent.mkdir(parents=True, exist_ok=True)
md_path.parent.mkdir(parents=True, exist_ok=True)
payload = {
"report_version": 1,
"input": str(input_dir.resolve()),
"work": str(work_dir.resolve()),
"dxf_sanitized": str(clean_dir.resolve()),
"conversions": conversions,
"files": results,
}
# --no-convert is a diagnostic convenience, not permission to silently
# exclude DWGs from the source ledger. A mixed folder therefore fails the
# hard gate until every DWG is converted or the run is explicitly partial.
dwg_sources = {str(path) for path in cad_files if path.suffix.lower() == ".dwg"}
successful_dwg_sources = {
str(item.get("source")) for item in conversions if item.get("status") in {"ok", "oda_ok", "oda_fallback_ok"}
}
unresolved_dwgs = sorted(dwg_sources - successful_dwg_sources)
failed_files = [item.get("file", "?") for item in results if item.get("status") != "ok"]
empty_files = [
item.get("file", "?") for item in results if item.get("status") == "ok" and item.get("modelspace_entities") == 0
]
issues = []
if not cad_files:
issues.append("input contains no DWG/DXF files")
if unresolved_dwgs:
issues.append("unconverted DWG files: " + ", ".join(Path(path).name for path in unresolved_dwgs))
if failed_files:
issues.append("unreadable DXF files: " + ", ".join(failed_files))
if empty_files:
issues.append("zero-entity DXF files: " + ", ".join(empty_files))
if not results:
issues.append("no readable DXF files were produced")
payload["gate"] = {
"name": "all_sources_converted_and_readable",
"status": "WARN" if issues and args.allow_partial else ("FAIL" if issues else "PASS"),
"detail": "; ".join(issues) if issues else f"{len(results)} DXF file(s) readable",
"partial_reason": args.partial_reason if issues and args.allow_partial else None,
}
payload = scrub_surrogates(payload)
results = payload["files"]
json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")
gate = payload["gate"]
gate_md = (
"## Source Gate\n\n"
f"- **{gate['status']}** `{gate['name']}`: {gate['detail']}"
+ (f"\n- Partial reason: {gate['partial_reason']}" if gate.get("partial_reason") else "")
+ "\n\n"
)
md_path.write_text(gate_md + markdown_report(results, conversions, input_dir), encoding="utf-8")
print(json.dumps({"json": str(json_path), "markdown": str(md_path), "files": len(results)}, ensure_ascii=False))
if issues and not args.allow_partial:
for issue in issues:
print(f"GATE FAIL [all_sources_converted_and_readable]: {issue}", file=sys.stderr)
return 3
return 0
if __name__ == "__main__":
raise SystemExit(main())