fix: make CAD conversion recovery deterministic
Some checks failed
ci / test (macos-latest, 3.10) (push) Has been cancelled
ci / test (macos-latest, 3.12) (push) Has been cancelled
ci / test (ubuntu-latest, 3.10) (push) Has been cancelled
ci / test (ubuntu-latest, 3.12) (push) Has been cancelled
ci / test (windows-latest, 3.10) (push) Has been cancelled
ci / test (windows-latest, 3.12) (push) Has been cancelled
ci / browser-smoke (push) Has been cancelled

This commit is contained in:
2026-07-21 13:49:18 +08:00
parent 9d7d3cb973
commit a3be794e19
7 changed files with 159 additions and 6 deletions

View File

@@ -17,6 +17,8 @@ from pathlib import Path
CAD_SUFFIXES = {".dwg", ".dxf"}
SCRIPT_DIR = Path(__file__).resolve().parent
ROOT = SCRIPT_DIR.parent
def parse_args() -> argparse.Namespace:
@@ -93,6 +95,91 @@ def run_dwg2dxf(source: Path, dest: Path) -> dict:
}
def libredwg_wasm_module_dir() -> Path | None:
"""Resolve the packaged WASM libredwg module without installing at runtime."""
override = os.environ.get("CAD_LIBREDWG_MODULE_DIR")
candidates = [Path(override)] if override else []
candidates.append(ROOT / "node_modules")
for candidate in candidates:
package = candidate / "@mlightcad" / "libredwg-web"
if (package / "dist" / "libredwg-web.js").exists() and (package / "wasm").is_dir():
return candidate
return None
def run_wasm_libredwg(source: Path, dest: Path, work_dir: Path, vendor_dir: Path) -> dict:
"""Convert one DWG through the packaged libredwg WASM bridge."""
node = shutil.which("node")
module_dir = libredwg_wasm_module_dir()
if not node or module_dir is None:
return {
"source": str(source),
"dest": str(dest),
"status": "missing_libredwg_wasm",
"message": (
"Install the toolchain Node dependencies with `npm install` or set "
"CAD_LIBREDWG_MODULE_DIR to a node_modules directory containing "
"@mlightcad/libredwg-web."
),
}
dump_dir = work_dir / "dwg_json"
dump_dir.mkdir(parents=True, exist_ok=True)
dump = dump_dir / f"{dest.stem}.json"
dest.parent.mkdir(parents=True, exist_ok=True)
try:
dump_proc = subprocess.run(
[
node,
str(SCRIPT_DIR / "dwg_dump_json.mjs"),
str(source),
str(dump),
"--module-dir",
str(module_dir),
],
capture_output=True,
timeout=600,
)
if dump_proc.returncode != 0 or not dump.exists():
return {
"source": str(source),
"dest": str(dest),
"status": "wasm_dump_failed",
"returncode": dump_proc.returncode,
"stdout": dump_proc.stdout.decode("utf-8", errors="replace")[-2000:],
"stderr": dump_proc.stderr.decode("utf-8", errors="replace")[-2000:],
}
rebuild_proc = subprocess.run(
[
sys.executable,
str(SCRIPT_DIR / "dwgjson_to_dxf.py"),
"--json",
str(dump),
"--out",
str(dest),
"--vendor-dir",
str(vendor_dir),
],
capture_output=True,
timeout=600,
)
except subprocess.TimeoutExpired as exc:
return {
"source": str(source),
"dest": str(dest),
"status": "wasm_timeout",
"message": str(exc),
}
return {
"source": str(source),
"dest": str(dest),
"status": "wasm_ok" if rebuild_proc.returncode == 0 and dest.exists() else "wasm_rebuild_failed",
"returncode": rebuild_proc.returncode,
"stdout": rebuild_proc.stdout.decode("utf-8", errors="replace")[-2000:],
"stderr": rebuild_proc.stderr.decode("utf-8", errors="replace")[-2000:],
}
def oda_converter() -> str | None:
"""ODA File Converter: env ODA_CONVERTER > PATH > macOS app-bundle default."""
override = os.environ.get("ODA_CONVERTER")
@@ -583,6 +670,21 @@ def main() -> int:
if args.allow_partial and not (args.partial_reason or "").strip():
raise SystemExit("--allow-partial requires --partial-reason")
cad_files = find_cad_files(input_dir)
generated_inputs = []
for source in cad_files:
resolved = source.resolve()
for generated_dir in (raw_dir.resolve(), clean_dir.resolve()):
if resolved == generated_dir or generated_dir in resolved.parents:
generated_inputs.append(source)
break
if generated_inputs:
examples = ", ".join(str(path) for path in generated_inputs[:3])
raise SystemExit(
"Input CAD files are inside generated work directories and would be deleted before inspection: "
f"{examples}. Use a separate --input directory such as out/dxf_src."
)
# These folders are generated intermediates. Recreate them so a source
# removed between runs cannot survive as a stale DXF and enter modeling.
shutil.rmtree(raw_dir, ignore_errors=True)
@@ -590,7 +692,6 @@ def main() -> int:
raw_dir.mkdir(parents=True, exist_ok=True)
clean_dir.mkdir(parents=True, exist_ok=True)
cad_files = find_cad_files(input_dir)
used_names: set[str] = set()
conversions: list[dict] = []
raw_dxfs: list[Path] = []
@@ -615,8 +716,10 @@ def main() -> int:
conversion = {"source": str(source), "dest": str(dest), "status": "oda_failed"}
else:
conversion = run_dwg2dxf(source, dest)
if conversion["status"] != "ok":
conversion = run_wasm_libredwg(source, dest, work_dir, vendor_dir)
conversions.append(conversion)
if conversion["status"] in {"ok", "oda_ok"}:
if conversion["status"] in {"ok", "wasm_ok", "oda_ok"}:
raw_dxfs.append(dest)
else:
if source.resolve() != dest.resolve():
@@ -648,7 +751,7 @@ def main() -> int:
if src and (item.get("status") == "failed" or item.get("modelspace_entities") == 0):
retry[item["file"]] = src
for c in list(conversions):
if c.get("status") in {"failed", "missing_dwg2dxf"} and str(c.get("source", "")).lower().endswith(".dwg"):
if c.get("status") not in {"ok", "wasm_ok", "oda_ok"} and str(c.get("source", "")).lower().endswith(".dwg"):
name = Path(c["dest"]).name if c.get("dest") else Path(c["source"]).with_suffix(".dxf").name
retry.setdefault(name, Path(c["source"]))
if retry and args.converter == "auto":
@@ -690,7 +793,9 @@ def main() -> int:
# hard gate until every DWG is converted or the run is explicitly partial.
dwg_sources = {str(path) for path in cad_files if path.suffix.lower() == ".dwg"}
successful_dwg_sources = {
str(item.get("source")) for item in conversions if item.get("status") in {"ok", "oda_ok", "oda_fallback_ok"}
str(item.get("source"))
for item in conversions
if item.get("status") in {"ok", "wasm_ok", "oda_ok", "oda_fallback_ok"}
}
unresolved_dwgs = sorted(dwg_sources - successful_dwg_sources)
failed_files = [item.get("file", "?") for item in results if item.get("status") != "ok"]

View File

@@ -451,6 +451,14 @@ def doctor() -> int:
except SystemExit:
path = None
checks.append({"name": executable, "status": "PASS" if path else "OPTIONAL", "path": path})
wasm_module = ROOT / "node_modules" / "@mlightcad" / "libredwg-web"
checks.append(
{
"name": "libredwg-wasm",
"status": "PASS" if (wasm_module / "dist" / "libredwg-web.js").exists() else "OPTIONAL",
"path": str(wasm_module) if wasm_module.exists() else None,
}
)
for executable, resolver in (("ODAFileConverter", oda_converter), ("blender", default_blender)):
candidate = resolver()
path = candidate if candidate and Path(candidate).exists() else None