File size: 2,516 Bytes
5805ce8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
#!/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())