#!/usr/bin/env python3 """Rebuild an ezdxf DXF from a dwg_dump_json.mjs entity dump. Fallback DWG->DXF path when native dwg2dxf / ODA File Converter is not available. Preserves layers, block definitions, and INSERT transforms so the extraction pipeline (derive_showcase_spec.py block probing included) works unchanged. Usage: python3 dwgjson_to_dxf.py --json work/dump.json --out work/dxf_raw/file.dxf """ from __future__ import annotations import argparse import json import math import sys from pathlib import Path def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--json", required=True) parser.add_argument("--out", required=True) parser.add_argument("--vendor-dir", default="work/vendor") 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 except ImportError as exc: raise SystemExit( f"Missing ezdxf. Install with: python3 -m pip install --target {vendor_dir} ezdxf" ) from exc return ezdxf def add_entity(space, ent: dict) -> None: kind = ent["t"] attribs = {"layer": ent.get("layer", "0")} if kind == "LINE": space.add_line(ent["a"], ent["b"], dxfattribs=attribs) elif kind in {"LWPOLYLINE", "POLYLINE"}: points = [(v[0], v[1], 0.0, 0.0, v[2] if len(v) > 2 else 0.0) for v in ent["v"]] space.add_lwpolyline(points, format="xyseb", close=bool(ent.get("closed")), dxfattribs=attribs) elif kind == "ARC": start = math.degrees(ent["sa"]) if abs(ent["sa"]) <= math.tau + 0.01 else ent["sa"] end = math.degrees(ent["ea"]) if abs(ent["ea"]) <= math.tau + 0.01 else ent["ea"] if ent.get("r", 0) > 0: space.add_arc(ent["c"], ent["r"], start, end, dxfattribs=attribs) elif kind == "CIRCLE": if ent.get("r", 0) > 0: space.add_circle(ent["c"], ent["r"], dxfattribs=attribs) elif kind == "ELLIPSE": major = (ent["mj"][0], ent["mj"][1], 0.0) if math.hypot(major[0], major[1]) > 0: space.add_ellipse( ent["c"], major_axis=major, ratio=max(min(ent.get("ratio", 1.0), 1.0), 1e-6), start_param=ent.get("sa", 0.0), end_param=ent.get("ea", math.tau), dxfattribs=attribs, ) elif kind == "SPLINE": space.add_lwpolyline([(v[0], v[1]) for v in ent["v"]], dxfattribs=attribs) elif kind in {"TEXT", "MTEXT"}: text = ent.get("text", "") if text: space.add_text( text, height=max(float(ent.get("h", 250.0) or 250.0), 1e-3), dxfattribs=attribs, ).set_placement(ent["p"]) elif kind == "INSERT": rotation = ent.get("rot", 0.0) rotation = math.degrees(rotation) if abs(rotation) <= math.tau + 0.01 else rotation space.add_blockref( ent["name"], ent["p"], dxfattribs={ **attribs, "xscale": ent.get("sx", 1.0) or 1.0, "yscale": ent.get("sy", 1.0) or 1.0, "rotation": rotation, }, ) def main() -> int: args = parse_args() ezdxf = import_ezdxf(Path(args.vendor_dir)) payload = json.loads(Path(args.json).read_text(encoding="utf-8")) doc = ezdxf.new("R2010", setup=False) doc.header["$INSUNITS"] = int(payload.get("insunits", 4) or 4) for layer in payload.get("layers", []): name = layer.get("name") or "0" if name != "0" and name not in doc.layers: try: doc.layers.add(name, color=max(int(layer.get("color", 7)) or 7, 1)) except Exception: pass block_defs: dict = payload.get("blocks", {}) for name in block_defs: if name in doc.blocks: continue try: doc.blocks.new(name=name) except Exception: continue for name, ents in block_defs.items(): try: block = doc.blocks.get(name) except Exception: continue for ent in ents: if ent["t"] == "INSERT" and ent.get("name") not in doc.blocks: continue try: add_entity(block, ent) except Exception: pass msp = doc.modelspace() added = skipped = 0 for ent in payload.get("entities", []): if ent["t"] == "INSERT" and ent.get("name") not in doc.blocks: skipped += 1 continue try: add_entity(msp, ent) added += 1 except Exception: skipped += 1 out = Path(args.out) out.parent.mkdir(parents=True, exist_ok=True) doc.saveas(out) print(json.dumps({"out": str(out), "added": added, "skipped": skipped, "blocks": len(block_defs)})) return 0 if __name__ == "__main__": raise SystemExit(main())