GeomCAD / tools /convert_format.py
FanQY's picture
Add files using upload-large-folder tool
5805ce8 verified
Raw
History Blame Contribute Delete
2.52 kB
#!/usr/bin/env python3
"""GeomCAD format converter.
Executes a GeomCAD CadQuery program (.py file) and exports its solid to
STEP, BREP, or STL. Run inside the GeomCAD devcontainer (CadQuery / OCCT
installed). The .py program is the canonical exact representation; this
utility is a thin wrapper around CadQuery's exporter for on-demand
conversion to industrial CAD formats.
Usage:
python convert_format.py <input.py> <output.{step,stp,brep,stl}>
Optional:
--var NAME name of the solid variable in the program (default: r)
Examples:
python convert_format.py SOURCE/loft_100w/450871/450871.py /tmp/450871.step
python convert_format.py SOURCE/loft_100w/450871/450871.py /tmp/450871.brep
"""
import argparse
import sys
from pathlib import Path
import cadquery as cq
FMT_MAP = {".step": "STEP", ".stp": "STEP", ".stl": "STL", ".brep": "BREP"}
def export(solid, output_path: Path, fmt: str) -> None:
if fmt == "BREP":
shape = solid.val() if hasattr(solid, "val") else solid
shape.exportBrep(str(output_path))
else:
cq.exporters.export(solid, str(output_path), fmt)
def err(msg: str) -> int:
print(f"error: {msg}", file=sys.stderr)
return 1
def main() -> int:
ap = argparse.ArgumentParser(
description="Convert a GeomCAD CadQuery program to STEP, BREP, or STL.",
)
ap.add_argument("input", type=Path, help="GeomCAD .py program path")
ap.add_argument("output", type=Path, help="output file path with extension")
ap.add_argument("--var", default="r", help="solid variable name (default: r)")
args = ap.parse_args()
if not args.input.is_file():
return err(f"input not found: {args.input}")
suffix = args.output.suffix.lower()
if suffix not in FMT_MAP:
return err(f"unsupported extension {suffix!r}; supported: {sorted(FMT_MAP)}")
fmt = FMT_MAP[suffix]
ns = {}
try:
exec(compile(args.input.read_text(), str(args.input), "exec"), ns)
except Exception as e:
return err(f"failed to execute {args.input}: {e}")
if args.var not in ns:
avail = [k for k in ns if not k.startswith("_")]
return err(f"variable {args.var!r} not found in {args.input.name}; available: {avail}")
args.output.parent.mkdir(parents=True, exist_ok=True)
export(ns[args.var], args.output, fmt)
size_kb = args.output.stat().st_size / 1024
print(f"wrote {args.output} ({fmt}, {size_kb:.1f} KB)")
return 0
if __name__ == "__main__":
sys.exit(main())