#!/usr/bin/env python3 """Batch convert/read CAD drawings and generate a DXF inventory report.""" from __future__ import annotations import argparse import json import shutil import subprocess import sys from collections import Counter 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") 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( "Missing dependency: ezdxf. Install locally with:\n" f" 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)] proc = subprocess.run(cmd, text=True, capture_output=True) return { "source": str(source), "dest": str(dest), "status": "ok" if proc.returncode == 0 and dest.exists() else "failed", "returncode": proc.returncode, "stdout": proc.stdout[-2000:], "stderr": proc.stderr[-2000:], } def sanitize_dxf_comments(source: Path, dest: Path) -> int: """Remove DXF group code 999 comment pairs that can break brittle importers.""" lines = source.read_text(errors="ignore").splitlines(keepends=True) dest.parent.mkdir(parents=True, exist_ok=True) cleaned: list[str] = [] removed = 0 index = 0 while index < len(lines): if lines[index].strip() == "999": removed += 1 index += 2 continue cleaned.append(lines[index]) index += 1 dest.write_text("".join(cleaned), encoding="utf-8", errors="ignore") 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: 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 import re as _re PLAN_TITLE_RE = _re.compile(r"平面图$") PLAN_TITLE_EXCLUDE_RE = _re.compile(r"(示意|疏散|分区|索引|定位|总平面|放大|详图|布置|大样)") def count_plan_titles(entities) -> int: """Distinct plan-frame titles in modelspace (multi-frame sheet detector).""" seen = set() for entity in entities: kind = entity.dxftype() if kind not in {"TEXT", "MTEXT"}: continue try: text = str(entity.dxf.text if kind == "TEXT" else entity.plain_text() or "").strip() except Exception: continue if not text or len(text) > 40: continue if PLAN_TITLE_RE.search(text) and not PLAN_TITLE_EXCLUDE_RE.search(text): try: pos = entity.dxf.insert seen.add((text, round(float(pos.x) / 5000), round(float(pos.y) / 5000))) except Exception: seen.add((text, 0, 0)) return len(seen) 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." ) if 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), } 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 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}") raw_dir.mkdir(parents=True, exist_ok=True) clean_dir.mkdir(parents=True, exist_ok=True) used_names: set[str] = set() conversions: list[dict] = [] raw_dxfs: list[Path] = [] for source in find_cad_files(input_dir): dest = raw_dir / safe_name(source, used_names) if source.suffix.lower() == ".dwg": if args.no_convert: continue conversion = run_dwg2dxf(source, dest) conversions.append(conversion) if conversion["status"] == "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)] 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 = { "input": str(input_dir), "work": str(work_dir), "dxf_sanitized": str(clean_dir), "conversions": conversions, "files": results, } json_path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") md_path.write_text(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)) return 0 if __name__ == "__main__": raise SystemExit(main())