import json import os import pathlib import subprocess import tempfile from .step_tree import normalize_deleted_paths class FreeCADWorker: def __init__(self, freecad_cmd="FreeCADCmd"): self.freecad_cmd = freecad_cmd def trim_step_file(self, file_name, file_bytes, deleted_paths): normalized_paths = normalize_deleted_paths(deleted_paths) with tempfile.TemporaryDirectory(prefix="o3dv-step-") as temp_dir: temp_path = pathlib.Path(temp_dir) input_path = temp_path / file_name output_name = self._build_output_name(file_name) output_path = temp_path / output_name delete_manifest_path = temp_path / "deleted_paths.json" input_path.write_bytes(file_bytes) delete_manifest_path.write_text( json.dumps(normalized_paths), encoding="utf-8", ) subprocess.run( [ self.freecad_cmd, os.fspath(pathlib.Path(__file__).with_name("freecad_trim_step.py")), os.fspath(input_path), os.fspath(delete_manifest_path), os.fspath(output_path), ], check=True, capture_output=True, text=True, ) return output_path.read_bytes(), output_name def _build_output_name(self, file_name): lower_name = file_name.lower() if lower_name.endswith(".step"): return file_name[:-5] + "-edited.step" if lower_name.endswith(".stp"): return file_name[:-4] + "-edited.stp" return file_name + "-edited.step"