Merge pull request #27 from So3Lab/feat/add-exporter

Feat/add exporter
This commit is contained in:
xingyao huang
2026-09-06 00:05:53 +08:00
committed by GitHub
5 changed files with 325 additions and 11 deletions
+20
View File
@@ -215,6 +215,26 @@ scad.exporter.export_product_package_to_obj(
"out/mounting_plate.scadpkg", "out/mounting_plate.obj"
)
```
### Command-line product export
Export the standard delivery set (AP242 STEP, binary STL, and OBJ) from a
validated product package with no wrapper script:
```bash
uv run simplecad-export out/mounting_plate.scadpkg --output-dir out/exports
```
Request additional targets explicitly. FCStd requires `FreeCADCmd` (or an
explicit `--freecad-cmd` path); `--check` validates the package, output paths,
and selected target prerequisites without writing files.
```bash
uv run simplecad-export out/mounting_plate.scadpkg \
--format fcstd --format mjcf --output-dir out/exports --check
uv run simplecad-export out/mounting_plate.scadpkg \
--format fcstd --freecad-cmd /path/to/FreeCADCmd --output-dir out/exports
```
STL and OBJ share one direct OpenCASCADE tessellation of the evaluated BREP.
Both outputs contain the same oriented triangles and require no optional
remeshing dependency. Control curved-surface accuracy with `linear_deflection`
@@ -3,6 +3,32 @@
Take a validated product package and produce the requested downstream
deliverables.
## Preferred command path
For normal delivery, use the package exporter CLI rather than writing a
one-off Python wrapper. It validates the `.scadpkg`, chooses the conventional
output names, prints one JSON report, and lets independent targets finish even
when an optional target is unavailable:
```bash
uv run simplecad-export out/product.scadpkg --output-dir out/exports
```
Without `--format`, this writes AP242 STEP, binary STL, and OBJ. Add unusual
or backend-dependent outputs deliberately; `--check` performs all package,
output-path, and selected-target prerequisite checks without writing files:
```bash
uv run simplecad-export out/product.scadpkg \
--format fcstd --format mjcf --output-dir out/exports --check
uv run simplecad-export out/product.scadpkg \
--format fcstd --freecad-cmd /path/to/FreeCADCmd --output-dir out/exports
```
Use the lower-level Python APIs only when a workflow needs behavior the CLI
does not expose, such as consuming a report in-process or a format-specific
option not represented by a CLI flag.
## Goal and scope
Use when geometry and product validation already passed and the remaining
@@ -21,7 +47,7 @@ optional_domains:
- step-inspection # roundtrip validation of exports
artifacts:
- refreshed package (capture re-run if sources changed)
- export reports per format
- simplecad-export JSON report (or API reports for programmatic export)
validation_gates:
- package is current (sources unchanged since capture)
- each export report read and printed
@@ -43,11 +69,18 @@ repair_routes:
(`domains/export-and-translation.md` table): editable FreeCAD document →
`.FCStd`; neutral exchange → AP242 `.step`; DCC/surface inspection →
`.obj`; additive manufacturing → `.stl`; MuJoCo simulation → MJCF.
3. **Export from the package path** (`scad.exporter.*` /
`scad.translator.<backend>.*`), one call per target, keyword arguments.
4. **Read every report**: definition ids, occurrence/solid/triangle counts,
material items, limitations. Print the facts; never assume success from a
missing exception.
3. **Preflight and export from the package path**. Start with
`uv run simplecad-export <package>.scadpkg --output-dir <dir> --check`.
It checks the package and default STEP/STL/OBJ targets. Add each non-default
target with `--format`; FCStd requires FreeCADCmd (or `--freecad-cmd`) and
MJCF requires an assembly-rooted package. Re-run without `--check` to write
the files. Use `--output FORMAT=PATH` for a non-conventional file name and
`--overwrite` only when replacement is intentional.
4. **Read the JSON report**: definition ids, occurrence/solid/triangle counts,
material items, limitations, and per-target failures. Print the facts;
never assume success from a missing exception. An unavailable optional
target returns a nonzero status but does not erase successful independent
exports.
5. **Validate roundtrip when it matters**: consumers that re-import STEP →
`validate_step_roundtrip_rdescriptor` on the exported file.
6. **Report**: file paths, per-format report facts, parameters chosen
@@ -55,9 +88,10 @@ repair_routes:
## API pages to read
`capture` (when re-capturing), the exporter page(s) for every format
requested, the translator page(s) for every backend requested, and
`validate_step_roundtrip_rdescriptor` when roundtrip validation applies.
`capture` (when re-capturing), this workflow's CLI command contract, the
exporter page(s) for every format requested when using APIs or interpreting
format-specific reports, the translator page(s) for every backend requested,
and `validate_step_roundtrip_rdescriptor` when roundtrip validation applies.
## Validation gates
@@ -69,11 +103,14 @@ requested, the translator page(s) for every backend requested, and
- MJCF: every intended joint present; loop-closing constraints emitted as
equality/connect; public connectors only expose sites/endpoints.
- `.FCStd`: translation consumed the intended package revision.
- `simplecad-export --check` passes before delivery export; the final JSON
report records every requested target as successful.
## Failure routes
- FreeCAD/FreeCADCmd missing → report the missing backend; offer STEP as the
neutral fallback and say so explicitly.
- FreeCAD/FreeCADCmd missing → `simplecad-export --check --format fcstd`
reports the missing backend before writing. Export default STEP/STL/OBJ if
requested, offer STEP as the neutral fallback, and say so explicitly.
- STL/OBJ too coarse or too large → adjust deflection parameters, re-export;
both formats share one tessellation pass.
- MJCF joints missing → the assembly lacked explicit constraints; return to
+1
View File
@@ -130,3 +130,4 @@ testpaths = ["test", "tests"]
[project.scripts]
simplecad-cache = "simplecadapi.cache.cli:main"
simplecad-export = "simplecadapi.exporter.cli:main"
+196
View File
@@ -0,0 +1,196 @@
"""Command-line export of validated ``.scadpkg`` product packages."""
from __future__ import annotations
import argparse
import json
import shutil
from dataclasses import asdict, is_dataclass
from pathlib import Path
from typing import Any, Callable, Sequence
from ..product.packages import read_product_package
from ..translator.freecad_translator import (
translate_product_package_to_fcstd,
translate_product_package_to_freecad_script,
)
from ..translator.freecad_translator.exporter import discover_freecad_executable
from ..translator.fusion360_translator import translate_product_package_to_fusion360_script
from ..translator.solidworks_translator import translate_product_package_to_solidworks_script
from .mjcf import export_product_package_to_mjcf
from .obj import export_product_package_to_obj
from .step import export_product_package_to_step
from .stl import export_product_package_to_stl
DEFAULT_FORMATS = ("step", "stl", "obj")
_SUFFIXES = {
"step": ".step",
"stl": ".stl",
"obj": ".obj",
"fcstd": ".FCStd",
"mjcf": ".xml",
"freecad-script": ".freecad.py",
"fusion360-script": ".fusion360.py",
"solidworks-script": ".solidworks.py",
}
def _parser() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser(
prog="simplecad-export",
description="Export a validated .scadpkg product package.",
)
parser.add_argument("input", type=Path, help="input .scadpkg package")
parser.add_argument(
"--format",
action="append",
choices=tuple(_SUFFIXES),
dest="formats",
help="additional export format; may be repeated (default: step, stl, obj)",
)
parser.add_argument("--output-dir", type=Path, default=Path("."))
parser.add_argument(
"--output",
action="append",
default=[],
metavar="FORMAT=PATH",
help="override one output path; may be repeated",
)
parser.add_argument("--overwrite", action="store_true")
parser.add_argument("--check", action="store_true", help="validate and preflight without writing")
parser.add_argument("--linear-deflection", type=float, default=0.1)
parser.add_argument("--angular-deflection-degrees", type=float, default=20.0)
parser.add_argument("--relative", action="store_true", help="use relative mesh deflection")
parser.add_argument("--freecad-cmd", help="path to FreeCADCmd/FreeCAD for FCStd output")
parser.add_argument("--document-name", default="SimpleCADProduct")
return parser
def _parse_outputs(items: Sequence[str]) -> dict[str, Path]:
outputs: dict[str, Path] = {}
for item in items:
format_name, separator, raw_path = item.partition("=")
if not separator or format_name not in _SUFFIXES or not raw_path:
raise ValueError("--output must have the form FORMAT=PATH")
if format_name in outputs:
raise ValueError(f"duplicate --output for {format_name}")
outputs[format_name] = Path(raw_path)
return outputs
def _selected_formats(extra: Sequence[str] | None) -> tuple[str, ...]:
return tuple(dict.fromkeys((*DEFAULT_FORMATS, *(extra or ()))))
def _output_paths(input_path: Path, output_dir: Path, overrides: dict[str, Path], formats: Sequence[str]) -> dict[str, Path]:
stem = input_path.name.removesuffix(".scadpkg")
return {
format_name: (overrides.get(format_name) or output_dir / f"{stem}{_SUFFIXES[format_name]}").expanduser().resolve()
for format_name in formats
}
def _freecad_command(value: str | None) -> str | None:
if value is None:
return discover_freecad_executable()
path = Path(value).expanduser()
return str(path.resolve()) if path.is_file() else shutil.which(value)
def _report_value(value: Any) -> Any:
if is_dataclass(value):
value = asdict(value)
if isinstance(value, Path):
return str(value)
if isinstance(value, dict):
return {str(key): _report_value(item) for key, item in value.items()}
if isinstance(value, (list, tuple)):
return [_report_value(item) for item in value]
return value
def run(argv: Sequence[str] | None = None) -> tuple[dict[str, Any], int]:
args = _parser().parse_args(argv)
input_path = args.input.expanduser().resolve()
if input_path.suffix.lower() != ".scadpkg":
raise ValueError("input must end in .scadpkg")
formats = _selected_formats(args.formats)
overrides = _parse_outputs(args.output)
unselected_overrides = sorted(set(overrides) - set(formats))
if unselected_overrides:
raise ValueError(
"--output requires its format to be selected with --format: "
+ ", ".join(unselected_overrides)
)
output_paths = _output_paths(input_path, args.output_dir, overrides, formats)
package = read_product_package(input_path)
failures: dict[str, str] = {}
checks: dict[str, dict[str, Any]] = {}
freecad_cmd = _freecad_command(args.freecad_cmd) if "fcstd" in formats else None
for format_name in formats:
issues: list[str] = []
if format_name == "fcstd" and freecad_cmd is None:
issues.append("FreeCADCmd/FreeCAD not found; install it or pass --freecad-cmd")
if format_name == "mjcf" and package.root_kind != "assembly":
issues.append("MJCF export requires an assembly-rooted .scadpkg")
if not args.check and not args.overwrite and output_paths[format_name].exists():
issues.append("output already exists; pass --overwrite to replace it")
checks[format_name] = {"output": str(output_paths[format_name]), "ok": not issues, "issues": issues}
if issues:
failures[format_name] = "; ".join(issues)
report: dict[str, Any] = {
"input": str(input_path),
"root_kind": package.root_kind,
"root_id": package.root_id,
"check_only": bool(args.check),
"formats": checks,
"exports": {},
}
if args.check:
report["ok"] = not failures
return report, 0 if not failures else 1
exporters: dict[str, Callable[[], Any]] = {
"step": lambda: export_product_package_to_step(input_path, output_paths["step"]),
"stl": lambda: export_product_package_to_stl(input_path, output_paths["stl"], linear_deflection=args.linear_deflection, angular_deflection_degrees=args.angular_deflection_degrees, relative=args.relative),
"obj": lambda: export_product_package_to_obj(input_path, output_paths["obj"], linear_deflection=args.linear_deflection, angular_deflection_degrees=args.angular_deflection_degrees, relative=args.relative),
"fcstd": lambda: translate_product_package_to_fcstd(input_path, str(output_paths["fcstd"]), document_name=args.document_name, freecad_cmd=freecad_cmd),
"mjcf": lambda: export_product_package_to_mjcf(input_path, output_paths["mjcf"], linear_deflection=args.linear_deflection, angular_deflection_degrees=args.angular_deflection_degrees),
"freecad-script": lambda: translate_product_package_to_freecad_script(input_path, document_name=args.document_name),
"fusion360-script": lambda: translate_product_package_to_fusion360_script(input_path, document_name=args.document_name),
"solidworks-script": lambda: translate_product_package_to_solidworks_script(input_path, document_name=args.document_name),
}
for format_name in formats:
if format_name in failures:
continue
try:
result = exporters[format_name]()
if format_name.endswith("-script"):
output_paths[format_name].parent.mkdir(parents=True, exist_ok=True)
output_paths[format_name].write_text(str(result), encoding="utf-8")
result = {"output_path": str(output_paths[format_name])}
report["exports"][format_name] = {"ok": True, "report": _report_value(result)}
except Exception as exc: # retain independent exports when one target fails
failures[format_name] = f"{type(exc).__name__}: {exc}"
report["exports"][format_name] = {"ok": False, "error": failures[format_name]}
report["ok"] = not failures
if failures:
report["failures"] = failures
return report, 0 if not failures else 1
def main(argv: Sequence[str] | None = None) -> int:
try:
report, exit_code = run(argv)
except (OSError, PermissionError, ValueError) as exc:
print(json.dumps({"error": type(exc).__name__, "message": str(exc)}, sort_keys=True))
return 2
print(json.dumps(report, default=str, sort_keys=True))
return exit_code
if __name__ == "__main__":
raise SystemExit(main())
+60
View File
@@ -0,0 +1,60 @@
from pathlib import Path
from simplecadapi.exporter import cli
class _Package:
root_kind = "part"
root_id = "part-bracket"
def test_check_defaults_to_step_stl_and_obj(monkeypatch, tmp_path: Path):
input_path = tmp_path / "bracket.scadpkg"
monkeypatch.setattr(cli, "read_product_package", lambda value: _Package())
report, exit_code = cli.run([str(input_path), "--check", "--output-dir", str(tmp_path / "out")])
assert exit_code == 0
assert report["check_only"] is True
assert set(report["formats"]) == {"step", "stl", "obj"}
assert report["formats"]["step"]["output"].endswith("bracket.step")
assert report["formats"]["stl"]["output"].endswith("bracket.stl")
assert report["formats"]["obj"]["output"].endswith("bracket.obj")
def test_check_fcstd_reports_missing_freecad(monkeypatch, tmp_path: Path):
monkeypatch.setattr(cli, "read_product_package", lambda value: _Package())
monkeypatch.setattr(cli, "discover_freecad_executable", lambda: None)
report, exit_code = cli.run([str(tmp_path / "part.scadpkg"), "--format", "fcstd", "--check"])
assert exit_code == 1
assert report["formats"]["fcstd"]["ok"] is False
assert "FreeCADCmd" in report["formats"]["fcstd"]["issues"][0]
def test_check_mjcf_requires_assembly(monkeypatch, tmp_path: Path):
monkeypatch.setattr(cli, "read_product_package", lambda value: _Package())
report, exit_code = cli.run([str(tmp_path / "part.scadpkg"), "--format", "mjcf", "--check"])
assert exit_code == 1
assert report["formats"]["mjcf"]["ok"] is False
def test_check_rejects_unknown_package_extension(tmp_path: Path):
try:
cli.run([str(tmp_path / "part.json"), "--check"])
except ValueError as exc:
assert ".scadpkg" in str(exc)
else:
raise AssertionError("expected .scadpkg validation error")
def test_output_override_requires_selected_optional_format(tmp_path: Path):
try:
cli.run([str(tmp_path / "part.scadpkg"), "--check", "--output", "fcstd=part.FCStd"])
except ValueError as exc:
assert "--format" in str(exc)
else:
raise AssertionError("expected unselected format validation error")