File size: 4,318 Bytes
da6986a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""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)