classification / extraction.py
Silly98's picture
Upload 9 files
da6986a verified
"""In-process STEP -> NPZ extraction (no subprocess)."""
from __future__ import annotations
import json
import sys
import tempfile
from pathlib import Path
from typing import Dict, List, Optional
from heg_brep import DEFAULT_BREPEXTRACTOR_DIR, DEFAULT_FEATURE_LIST
# Make the BRepExtractor package importable (it is laid out as `pipeline.*`)
if str(DEFAULT_BREPEXTRACTOR_DIR) not in sys.path:
sys.path.insert(0, str(DEFAULT_BREPEXTRACTOR_DIR))
def _load_feature_schema(feature_list: Path) -> dict:
with open(feature_list, "r") as fp:
return json.load(fp)
def extract_step_to_npz(step_file: Path,
output_dir: Optional[Path] = None,
feature_list: Path = DEFAULT_FEATURE_LIST) -> Path:
"""Extract a single STEP to an NPZ. Returns the produced NPZ path.
Raises RuntimeError if extraction fails or the file is skipped.
"""
from pipeline.extract_brep_extractor_data_from_step import extract_brep_extractor_features
step_file = Path(step_file).expanduser().resolve()
if not step_file.exists():
raise FileNotFoundError(step_file)
if output_dir is None:
output_dir = Path(tempfile.mkdtemp(prefix="heg_brep_npz_"))
output_dir = Path(output_dir).expanduser().resolve()
output_dir.mkdir(parents=True, exist_ok=True)
schema = _load_feature_schema(feature_list)
ok = extract_brep_extractor_features(step_file, output_dir, schema, mesh_dir=None, seg_dir=None)
npz = output_dir / f"{step_file.stem}.npz"
if not ok or not npz.exists():
reason = _last_skip_reason_for(step_file, output_dir) or "unknown extraction failure"
raise RuntimeError(f"Extraction failed for {step_file.name}: {reason}")
return npz
def extract_folder_to_npz(step_folder: Path,
output_dir: Optional[Path] = None,
feature_list: Path = DEFAULT_FEATURE_LIST,
num_workers: int = 1,
max_file_mb: Optional[float] = None) -> Dict[str, object]:
"""Extract every STEP under `step_folder` to NPZ. Returns a summary dict
with: npz_dir, ok_stems, skipped (dict of stem -> reason), step_paths."""
from pipeline.extract_brep_extractor_data_from_step import extract_brep_extractor_data_from_step
step_folder = Path(step_folder).expanduser().resolve()
if not step_folder.is_dir():
raise FileNotFoundError(step_folder)
if output_dir is None:
output_dir = Path(tempfile.mkdtemp(prefix="heg_brep_npz_"))
output_dir = Path(output_dir).expanduser().resolve()
output_dir.mkdir(parents=True, exist_ok=True)
step_paths = _list_step_files(step_folder)
extract_brep_extractor_data_from_step(
step_path=step_folder,
output_path=output_dir,
mesh_dir=None,
seg_dir=None,
feature_list_path=feature_list,
force_regeneration=False,
max_file_mb=max_file_mb,
num_workers=max(1, int(num_workers)),
)
skipped = _all_skip_reasons(output_dir)
ok_stems = []
for sp in step_paths:
if (output_dir / f"{sp.stem}.npz").exists():
ok_stems.append(sp.stem)
return {
"npz_dir": output_dir,
"step_paths": step_paths,
"ok_stems": ok_stems,
"skipped": skipped,
}
def _list_step_files(folder: Path) -> List[Path]:
out = set()
for pattern in ("*.stp", "*.step", "*.STP", "*.STEP"):
for p in folder.glob(pattern): out.add(p.resolve())
for p in folder.glob(f"**/{pattern}"): out.add(p.resolve())
return sorted(out)
def _all_skip_reasons(npz_dir: Path) -> Dict[str, str]:
log = npz_dir / "skipped.jsonl"
out: Dict[str, str] = {}
if not log.exists():
return out
with log.open("r") as fp:
for line in fp:
line = line.strip()
if not line: continue
try:
rec = json.loads(line)
except json.JSONDecodeError:
continue
f = rec.get("file", "")
if f:
out[Path(f).stem] = str(rec.get("reason", "skipped"))
return out
def _last_skip_reason_for(step_file: Path, npz_dir: Path) -> Optional[str]:
reasons = _all_skip_reasons(npz_dir)
return reasons.get(step_file.stem)