brainchop 1.0.0__py3-none-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- brainchop/__init__.py +47 -0
- brainchop/__main__.py +3 -0
- brainchop/api.py +578 -0
- brainchop-1.0.0.dist-info/METADATA +188 -0
- brainchop-1.0.0.dist-info/RECORD +22 -0
- brainchop-1.0.0.dist-info/WHEEL +4 -0
- brainchop-1.0.0.dist-info/entry_points.txt +6 -0
- brainchop-1.0.0.dist-info/licenses/LICENSE +21 -0
- brainchop-1.0.0.dist-info/licenses/THIRD_PARTY_NOTICES.md +279 -0
- brainchop_cli/__init__.py +1 -0
- brainchop_cli/__main__.py +3 -0
- brainchop_cli/adaptive.py +277 -0
- brainchop_cli/bin/brainchop-mindgrab.exe +0 -0
- brainchop_cli/bin/brainchop-mindmap-fast.exe +0 -0
- brainchop_cli/bin/brainchop-mindmap.exe +0 -0
- brainchop_cli/bin/brainchop-mindsnap.exe +0 -0
- brainchop_cli/bin/hardware-probe.exe +0 -0
- brainchop_cli/build.json +198 -0
- brainchop_cli/cli.py +124 -0
- brainchop_cli/launch.py +24 -0
- brainchop_cli/native.py +140 -0
- brainchop_cli/source.tar.gz +0 -0
brainchop/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
brainchop - Native brain segmentation and skull stripping.
|
|
3
|
+
|
|
4
|
+
Example:
|
|
5
|
+
from brainchop import load, segment, save, list_models
|
|
6
|
+
|
|
7
|
+
vol = load("input.nii.gz")
|
|
8
|
+
result = segment(vol, "mindmap")
|
|
9
|
+
save(result, "output.nii.gz")
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
from importlib.metadata import PackageNotFoundError, version as _dist_version
|
|
15
|
+
|
|
16
|
+
from brainchop.api import (
|
|
17
|
+
RawClassMaps,
|
|
18
|
+
Volume,
|
|
19
|
+
export,
|
|
20
|
+
export_classes,
|
|
21
|
+
list_models,
|
|
22
|
+
load,
|
|
23
|
+
optimize,
|
|
24
|
+
save,
|
|
25
|
+
segment,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
__version__ = _dist_version("brainchop")
|
|
30
|
+
except PackageNotFoundError:
|
|
31
|
+
from pathlib import Path as _Path
|
|
32
|
+
|
|
33
|
+
_ver_file = _Path(__file__).resolve().parents[1] / "PYPI_VERSION"
|
|
34
|
+
__version__ = _ver_file.read_text().strip() if _ver_file.is_file() else "1.0.0"
|
|
35
|
+
|
|
36
|
+
__all__ = [
|
|
37
|
+
"__version__",
|
|
38
|
+
"RawClassMaps",
|
|
39
|
+
"Volume",
|
|
40
|
+
"load",
|
|
41
|
+
"save",
|
|
42
|
+
"segment",
|
|
43
|
+
"list_models",
|
|
44
|
+
"export",
|
|
45
|
+
"optimize",
|
|
46
|
+
"export_classes",
|
|
47
|
+
]
|
brainchop/__main__.py
ADDED
brainchop/api.py
ADDED
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
"""
|
|
2
|
+
brainchop.api - Zero-dependency Python scripting interface backed by native executables.
|
|
3
|
+
|
|
4
|
+
Backward-compatible with the historical ``brainchop-cli`` scripting surface
|
|
5
|
+
(``Volume``, ``load``, ``segment``, ``save``, ``list_models``, ``optimize``,
|
|
6
|
+
``export``, ``export_classes``), using only the Python standard library.
|
|
7
|
+
When ``numpy`` is installed, ``Volume.data`` returns a ``numpy.ndarray``;
|
|
8
|
+
otherwise it returns a lightweight pure-Python buffer view.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import array
|
|
14
|
+
import gzip
|
|
15
|
+
import os
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
import struct
|
|
18
|
+
import subprocess
|
|
19
|
+
import sys
|
|
20
|
+
import tempfile
|
|
21
|
+
from typing import Any
|
|
22
|
+
|
|
23
|
+
from brainchop_cli import native
|
|
24
|
+
|
|
25
|
+
_NIFTI_DTYPES: dict[int, tuple[str, str, int]] = {
|
|
26
|
+
2: ("uint8", "B", 1),
|
|
27
|
+
4: ("int16", "h", 2),
|
|
28
|
+
8: ("int32", "i", 4),
|
|
29
|
+
16: ("float32", "f", 4),
|
|
30
|
+
64: ("float64", "d", 8),
|
|
31
|
+
256: ("int8", "b", 1),
|
|
32
|
+
512: ("uint16", "H", 2),
|
|
33
|
+
768: ("uint32", "I", 4),
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
_GZIP_MAGIC = b"\x1f\x8b"
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _read_nifti_bytes(path: str | Path) -> bytes:
|
|
40
|
+
raw = Path(path).read_bytes()
|
|
41
|
+
if raw[:2] == _GZIP_MAGIC:
|
|
42
|
+
return gzip.decompress(raw)
|
|
43
|
+
return raw
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _read_nifti_header(path: str | Path) -> bytes:
|
|
47
|
+
file_path = Path(path)
|
|
48
|
+
with file_path.open("rb") as handle:
|
|
49
|
+
magic = handle.read(2)
|
|
50
|
+
if magic == _GZIP_MAGIC:
|
|
51
|
+
with gzip.open(file_path, "rb") as handle:
|
|
52
|
+
hdr = handle.read(352)
|
|
53
|
+
else:
|
|
54
|
+
with file_path.open("rb") as handle:
|
|
55
|
+
hdr = handle.read(352)
|
|
56
|
+
if len(hdr) < 348:
|
|
57
|
+
raise ValueError(f"not a valid NIfTI-1 file (too short): {path}")
|
|
58
|
+
sizeof_le = struct.unpack_from("<i", hdr, 0)[0]
|
|
59
|
+
sizeof_be = struct.unpack_from(">i", hdr, 0)[0]
|
|
60
|
+
if sizeof_le != 348 and sizeof_be != 348:
|
|
61
|
+
raise ValueError(f"not a valid NIfTI-1 file (unexpected sizeof_hdr): {path}")
|
|
62
|
+
return hdr if len(hdr) == 352 else hdr + b"\x00" * (352 - len(hdr))
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _header_endian(header: bytes) -> str:
|
|
66
|
+
if len(header) < 348:
|
|
67
|
+
raise ValueError("NIfTI-1 header must be at least 348 bytes")
|
|
68
|
+
if struct.unpack_from("<i", header, 0)[0] == 348:
|
|
69
|
+
return "<"
|
|
70
|
+
if struct.unpack_from(">i", header, 0)[0] == 348:
|
|
71
|
+
return ">"
|
|
72
|
+
raise ValueError("invalid NIfTI-1 header (sizeof_hdr != 348)")
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _parse_header_meta(header: bytes) -> dict[str, Any]:
|
|
76
|
+
end = _header_endian(header)
|
|
77
|
+
dims = struct.unpack_from(end + "8h", header, 40)
|
|
78
|
+
ndim = max(1, min(dims[0], 7))
|
|
79
|
+
shape = tuple(int(dims[i]) for i in range(1, ndim + 1))
|
|
80
|
+
# Strip trailing singleton dims above 3D so (X, Y, Z, 1) -> (X, Y, Z)
|
|
81
|
+
while len(shape) > 3 and shape[-1] == 1:
|
|
82
|
+
shape = shape[:-1]
|
|
83
|
+
datatype = struct.unpack_from(end + "h", header, 70)[0]
|
|
84
|
+
vox_offset = int(struct.unpack_from(end + "f", header, 108)[0])
|
|
85
|
+
if vox_offset < 352:
|
|
86
|
+
vox_offset = 352
|
|
87
|
+
scl_slope, scl_inter = struct.unpack_from(end + "2f", header, 112)
|
|
88
|
+
return {
|
|
89
|
+
"endian": end,
|
|
90
|
+
"shape": shape,
|
|
91
|
+
"datatype": datatype,
|
|
92
|
+
"vox_offset": vox_offset,
|
|
93
|
+
"scl_slope": scl_slope,
|
|
94
|
+
"scl_inter": scl_inter,
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _set_intent_label(header: bytes) -> bytes:
|
|
99
|
+
end = _header_endian(header)
|
|
100
|
+
ba = bytearray(header[:352])
|
|
101
|
+
if len(ba) < 352:
|
|
102
|
+
ba.extend(b"\x00" * (352 - len(ba)))
|
|
103
|
+
struct.pack_into(end + "h", ba, 68, 1002) # NIFTI_INTENT_LABEL
|
|
104
|
+
return bytes(ba)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _decode_nifti_payload(raw_nii: bytes, header: bytes) -> Any:
|
|
108
|
+
meta = _parse_header_meta(header)
|
|
109
|
+
shape = meta["shape"]
|
|
110
|
+
datatype = meta["datatype"]
|
|
111
|
+
if datatype not in _NIFTI_DTYPES:
|
|
112
|
+
raise ValueError(f"unsupported NIfTI datatype code: {datatype}")
|
|
113
|
+
dtype_name, fmt_char, itemsize = _NIFTI_DTYPES[datatype]
|
|
114
|
+
nvox = 1
|
|
115
|
+
for d in shape:
|
|
116
|
+
nvox *= d
|
|
117
|
+
start = meta["vox_offset"]
|
|
118
|
+
payload = raw_nii[start : start + nvox * itemsize]
|
|
119
|
+
if len(payload) < nvox * itemsize:
|
|
120
|
+
raise ValueError("NIfTI payload shorter than header dimensions")
|
|
121
|
+
try:
|
|
122
|
+
import numpy as np # type: ignore[import-not-found]
|
|
123
|
+
|
|
124
|
+
np_dtype = np.dtype(meta["endian"] + np.dtype(dtype_name).str[1:])
|
|
125
|
+
return np.frombuffer(payload, dtype=np_dtype, count=nvox).reshape(shape, order="F").copy()
|
|
126
|
+
except ImportError:
|
|
127
|
+
return _StdlibVolumeData(payload, shape, dtype_name, fmt_char, meta["endian"])
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
class _StdlibVolumeData:
|
|
131
|
+
"""Minimal pure-stdlib array view used when ``numpy`` is not installed."""
|
|
132
|
+
|
|
133
|
+
def __init__(self, payload: bytes, shape: tuple[int, ...], dtype: str, fmt_char: str, endian: str):
|
|
134
|
+
self._payload = payload
|
|
135
|
+
self.shape = shape
|
|
136
|
+
self.dtype = dtype
|
|
137
|
+
self._fmt_char = fmt_char
|
|
138
|
+
self._endian = endian
|
|
139
|
+
size = 1
|
|
140
|
+
for d in shape:
|
|
141
|
+
size *= d
|
|
142
|
+
self.size = size
|
|
143
|
+
|
|
144
|
+
def tobytes(self) -> bytes:
|
|
145
|
+
return self._payload
|
|
146
|
+
|
|
147
|
+
def tolist(self) -> list[Any]:
|
|
148
|
+
arr = array.array(self._fmt_char)
|
|
149
|
+
arr.frombytes(self._payload)
|
|
150
|
+
sys_endian = "<" if sys.byteorder == "little" else ">"
|
|
151
|
+
if self._endian != sys_endian and arr.itemsize > 1:
|
|
152
|
+
arr.byteswap()
|
|
153
|
+
return arr.tolist()
|
|
154
|
+
|
|
155
|
+
def __len__(self) -> int:
|
|
156
|
+
return self.shape[0] if self.shape else 0
|
|
157
|
+
|
|
158
|
+
def __repr__(self) -> str:
|
|
159
|
+
return f"_StdlibVolumeData(shape={self.shape}, dtype={self.dtype!r})"
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
class Volume:
|
|
163
|
+
"""A brain volume paired with its 352-byte NIfTI-1 header.
|
|
164
|
+
|
|
165
|
+
Compatible with ``brainchop-cli``'s ``Volume(data, header, crop_coords=None)``.
|
|
166
|
+
When constructed via ``load(path)``, voxel decoding is deferred until
|
|
167
|
+
``.data`` is accessed so ``load() -> segment() -> save()`` avoids unnecessary
|
|
168
|
+
in-memory decoding overhead.
|
|
169
|
+
"""
|
|
170
|
+
|
|
171
|
+
def __init__(
|
|
172
|
+
self,
|
|
173
|
+
data: Any = None,
|
|
174
|
+
header: bytes = b"",
|
|
175
|
+
crop_coords: tuple[int, ...] | None = None,
|
|
176
|
+
*,
|
|
177
|
+
_source_path: Path | None = None,
|
|
178
|
+
_raw_nii: bytes | None = None,
|
|
179
|
+
_load_opts: dict[str, Any] | None = None,
|
|
180
|
+
_is_label: bool = False,
|
|
181
|
+
) -> None:
|
|
182
|
+
self._data: Any = data
|
|
183
|
+
self.header: bytes = header
|
|
184
|
+
self.crop_coords: tuple[int, ...] | None = crop_coords
|
|
185
|
+
self._source_path: Path | None = _source_path
|
|
186
|
+
self._raw_nii: bytes | None = _raw_nii
|
|
187
|
+
self._load_opts: dict[str, Any] = dict(_load_opts or {})
|
|
188
|
+
self._is_label: bool = _is_label
|
|
189
|
+
|
|
190
|
+
@property
|
|
191
|
+
def data(self) -> Any:
|
|
192
|
+
if self._data is None:
|
|
193
|
+
if self._raw_nii is not None:
|
|
194
|
+
self._data = _decode_nifti_payload(self._raw_nii, self.header)
|
|
195
|
+
elif self._source_path is not None:
|
|
196
|
+
raw = _read_nifti_bytes(self._source_path)
|
|
197
|
+
self._raw_nii = raw
|
|
198
|
+
if not self.header:
|
|
199
|
+
self.header = raw[:352]
|
|
200
|
+
self._data = _decode_nifti_payload(raw, self.header)
|
|
201
|
+
return self._data
|
|
202
|
+
|
|
203
|
+
@data.setter
|
|
204
|
+
def data(self, value: Any) -> None:
|
|
205
|
+
self._data = value
|
|
206
|
+
self._raw_nii = None
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def shape(self) -> tuple[int, ...]:
|
|
210
|
+
if self._data is not None and hasattr(self._data, "shape"):
|
|
211
|
+
return tuple(int(d) for d in self._data.shape)
|
|
212
|
+
if self.header:
|
|
213
|
+
return _parse_header_meta(self.header)["shape"]
|
|
214
|
+
return ()
|
|
215
|
+
|
|
216
|
+
@property
|
|
217
|
+
def dtype(self) -> str:
|
|
218
|
+
if self._data is not None and hasattr(self._data, "dtype"):
|
|
219
|
+
return str(self._data.dtype)
|
|
220
|
+
if self.header:
|
|
221
|
+
code = _parse_header_meta(self.header)["datatype"]
|
|
222
|
+
return _NIFTI_DTYPES.get(code, (f"code_{code}", "", 0))[0]
|
|
223
|
+
return "unknown"
|
|
224
|
+
|
|
225
|
+
def _serialize_nii(self, *, force_label_intent: bool = False) -> bytes:
|
|
226
|
+
if self._raw_nii is not None and self._data is None:
|
|
227
|
+
if force_label_intent:
|
|
228
|
+
return _set_intent_label(self._raw_nii[:352]) + self._raw_nii[352:]
|
|
229
|
+
return self._raw_nii
|
|
230
|
+
if not self.header:
|
|
231
|
+
raise ValueError("Volume has no NIfTI header")
|
|
232
|
+
header = _set_intent_label(self.header) if force_label_intent else self.header[:352]
|
|
233
|
+
if len(header) < 352:
|
|
234
|
+
header = header + b"\x00" * (352 - len(header))
|
|
235
|
+
data = self.data
|
|
236
|
+
if data is None:
|
|
237
|
+
raise ValueError("Volume has no data")
|
|
238
|
+
if hasattr(data, "numpy") and callable(data.numpy):
|
|
239
|
+
data = data.numpy()
|
|
240
|
+
if isinstance(data, _StdlibVolumeData):
|
|
241
|
+
payload = data.tobytes()
|
|
242
|
+
else:
|
|
243
|
+
try:
|
|
244
|
+
import numpy as np # type: ignore[import-not-found]
|
|
245
|
+
|
|
246
|
+
arr = np.asarray(data)
|
|
247
|
+
meta = _parse_header_meta(header)
|
|
248
|
+
dtype_info = _NIFTI_DTYPES.get(meta["datatype"])
|
|
249
|
+
if dtype_info is not None:
|
|
250
|
+
np_dtype = np.dtype(meta["endian"] + np.dtype(dtype_info[0]).str[1:])
|
|
251
|
+
arr = arr.astype(np_dtype, copy=False)
|
|
252
|
+
payload = arr.tobytes(order="F")
|
|
253
|
+
except ImportError:
|
|
254
|
+
if hasattr(data, "tobytes"):
|
|
255
|
+
payload = data.tobytes()
|
|
256
|
+
elif isinstance(data, (bytes, bytearray, memoryview)):
|
|
257
|
+
payload = bytes(data)
|
|
258
|
+
else:
|
|
259
|
+
raise TypeError(f"cannot serialize volume data of type {type(data).__name__}")
|
|
260
|
+
# Reset vox_offset to 352 so the written NIfTI payload aligns immediately.
|
|
261
|
+
end = _header_endian(header)
|
|
262
|
+
hdr_ba = bytearray(header)
|
|
263
|
+
struct.pack_into(end + "f", hdr_ba, 108, 352.0)
|
|
264
|
+
return bytes(hdr_ba) + payload
|
|
265
|
+
|
|
266
|
+
def __repr__(self) -> str:
|
|
267
|
+
return f"Volume(shape={self.shape}, dtype={self.dtype!r})"
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class RawClassMaps:
|
|
271
|
+
"""Container for per-class raw maps returned by ``segment(..., return_raw=True)``."""
|
|
272
|
+
|
|
273
|
+
def __init__(self, class_nii_bytes: list[bytes]) -> None:
|
|
274
|
+
self._class_nii = class_nii_bytes
|
|
275
|
+
self.num_classes = len(class_nii_bytes)
|
|
276
|
+
|
|
277
|
+
def __len__(self) -> int:
|
|
278
|
+
return self.num_classes
|
|
279
|
+
|
|
280
|
+
def numpy(self) -> Any:
|
|
281
|
+
import numpy as np # type: ignore[import-not-found]
|
|
282
|
+
|
|
283
|
+
maps = []
|
|
284
|
+
for raw in self._class_nii:
|
|
285
|
+
vol = _decode_nifti_payload(raw, raw[:352])
|
|
286
|
+
# Match legacy (1, C, D, H, W) convention from brainchop-cli
|
|
287
|
+
maps.append(np.transpose(vol, (2, 1, 0)))
|
|
288
|
+
return np.stack(maps, axis=0)[None, ...]
|
|
289
|
+
|
|
290
|
+
def __array__(self, dtype: Any = None) -> Any:
|
|
291
|
+
arr = self.numpy()
|
|
292
|
+
return arr if dtype is None else arr.astype(dtype)
|
|
293
|
+
|
|
294
|
+
|
|
295
|
+
def list_models() -> dict[str, str]:
|
|
296
|
+
"""Return available embedded models as ``{name: description}``."""
|
|
297
|
+
return dict(native.NATIVE_MODELS)
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _load_single(
|
|
301
|
+
path: str | Path,
|
|
302
|
+
*,
|
|
303
|
+
crop: float | None = None,
|
|
304
|
+
ct: bool = False,
|
|
305
|
+
comply: bool = False,
|
|
306
|
+
) -> Volume:
|
|
307
|
+
file_path = Path(path)
|
|
308
|
+
if not file_path.is_file():
|
|
309
|
+
raise FileNotFoundError(f"NIfTI input does not exist: {file_path}")
|
|
310
|
+
header = _read_nifti_header(file_path)
|
|
311
|
+
return Volume(
|
|
312
|
+
data=None,
|
|
313
|
+
header=header,
|
|
314
|
+
crop_coords=None,
|
|
315
|
+
_source_path=file_path.resolve(),
|
|
316
|
+
_load_opts={"crop": crop, "ct": ct, "comply": comply},
|
|
317
|
+
)
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
def load(
|
|
321
|
+
path: str | Path | list[str | Path],
|
|
322
|
+
*,
|
|
323
|
+
crop: float | None = None,
|
|
324
|
+
ct: bool = False,
|
|
325
|
+
comply: bool = False,
|
|
326
|
+
) -> Volume | list[Volume]:
|
|
327
|
+
"""Load NIfTI file(s) as :class:`Volume` object(s).
|
|
328
|
+
|
|
329
|
+
Conform/rescaling is executed natively inside :func:`segment`, avoiding
|
|
330
|
+
extra Python dependencies and keeping full native preprocessing parity.
|
|
331
|
+
"""
|
|
332
|
+
if isinstance(path, list):
|
|
333
|
+
return [_load_single(p, crop=crop, ct=ct, comply=comply) for p in path]
|
|
334
|
+
return _load_single(path, crop=crop, ct=ct, comply=comply)
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def save(volume: Volume, path: str | Path) -> None:
|
|
338
|
+
"""Save a :class:`Volume` to ``.nii`` or ``.nii.gz`` using the stdlib."""
|
|
339
|
+
out_path = Path(path)
|
|
340
|
+
raw = volume._serialize_nii(force_label_intent=volume._is_label)
|
|
341
|
+
if str(out_path).endswith(".gz"):
|
|
342
|
+
out_path.write_bytes(gzip.compress(raw, compresslevel=6))
|
|
343
|
+
else:
|
|
344
|
+
out_path.write_bytes(raw)
|
|
345
|
+
|
|
346
|
+
|
|
347
|
+
def _resolve_model(model: str) -> str:
|
|
348
|
+
canonical = native.MODEL_ALIASES.get(model, model)
|
|
349
|
+
if canonical not in native.NATIVE_MODELS:
|
|
350
|
+
raise ValueError(native.unknown_model_message(model))
|
|
351
|
+
return canonical
|
|
352
|
+
|
|
353
|
+
|
|
354
|
+
def optimize(
|
|
355
|
+
model: str,
|
|
356
|
+
*,
|
|
357
|
+
batch_size: int = 1,
|
|
358
|
+
beam: int = 2,
|
|
359
|
+
) -> None:
|
|
360
|
+
"""Compatibility no-op: native models are already compiled and need no BEAM tuning."""
|
|
361
|
+
_ = (batch_size, beam)
|
|
362
|
+
_resolve_model(model)
|
|
363
|
+
print(
|
|
364
|
+
"brainchop :: Native models are precompiled; optimize() is a compatibility no-op.",
|
|
365
|
+
file=sys.stderr,
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def export(
|
|
370
|
+
model: str,
|
|
371
|
+
output_dir: str,
|
|
372
|
+
*,
|
|
373
|
+
target: str = "webgpu",
|
|
374
|
+
beam: int = 0,
|
|
375
|
+
tta: bool = False,
|
|
376
|
+
flip_axis: str = "sagittal",
|
|
377
|
+
force: bool = False,
|
|
378
|
+
) -> tuple[str, str]:
|
|
379
|
+
"""Retired tinygrad WebGPU export hook (kept for clear migration errors)."""
|
|
380
|
+
_ = (model, output_dir, target, beam, tta, flip_axis, force)
|
|
381
|
+
raise NotImplementedError(
|
|
382
|
+
"brainchop.export() (tinygrad WebGPU export) is retired in brainchop 1.0. "
|
|
383
|
+
"For browser inference, use the @brainchop/core JS WebGPU package; "
|
|
384
|
+
"install brainchop==0.2.5 if you need the legacy tinygrad exporter."
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
|
|
388
|
+
def export_classes(raw_output: Any, header: bytes, output_path: str | Path) -> list[str]:
|
|
389
|
+
"""Write per-class probability/logit maps as ``<base>_c{i}.nii``."""
|
|
390
|
+
base = str(output_path)
|
|
391
|
+
for ext in (".nii.gz", ".nii"):
|
|
392
|
+
if base.endswith(ext):
|
|
393
|
+
base = base[: -len(ext)]
|
|
394
|
+
break
|
|
395
|
+
|
|
396
|
+
saved_paths: list[str] = []
|
|
397
|
+
if isinstance(raw_output, RawClassMaps):
|
|
398
|
+
for i, nii_bytes in enumerate(raw_output._class_nii):
|
|
399
|
+
out_fname = f"{base}_c{i}.nii"
|
|
400
|
+
Path(out_fname).write_bytes(nii_bytes)
|
|
401
|
+
saved_paths.append(out_fname)
|
|
402
|
+
return saved_paths
|
|
403
|
+
|
|
404
|
+
import numpy as np # type: ignore[import-not-found]
|
|
405
|
+
|
|
406
|
+
arr = raw_output.numpy() if hasattr(raw_output, "numpy") else np.asarray(raw_output)
|
|
407
|
+
if arr.ndim == 5:
|
|
408
|
+
arr = arr[0]
|
|
409
|
+
if arr.ndim != 4:
|
|
410
|
+
raise ValueError(f"expected 4D (C,D,H,W) or 5D (1,C,D,H,W) raw_output, got shape {arr.shape}")
|
|
411
|
+
end = _header_endian(header)
|
|
412
|
+
hdr_ba = bytearray(header[:352])
|
|
413
|
+
if len(hdr_ba) < 352:
|
|
414
|
+
hdr_ba.extend(b"\x00" * (352 - len(hdr_ba)))
|
|
415
|
+
struct.pack_into(end + "h", hdr_ba, 70, 16) # float32
|
|
416
|
+
struct.pack_into(end + "h", hdr_ba, 72, 32) # bitpix
|
|
417
|
+
struct.pack_into(end + "f", hdr_ba, 108, 352.0)
|
|
418
|
+
hdr_bytes = bytes(hdr_ba)
|
|
419
|
+
for i in range(arr.shape[0]):
|
|
420
|
+
chan = np.transpose(arr[i], (2, 1, 0)).astype(end + "f4", copy=False)
|
|
421
|
+
out_fname = f"{base}_c{i}.nii"
|
|
422
|
+
Path(out_fname).write_bytes(hdr_bytes + chan.tobytes(order="F"))
|
|
423
|
+
saved_paths.append(out_fname)
|
|
424
|
+
return saved_paths
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def segment(
|
|
428
|
+
volume: Volume | str | Path | list[Volume | str | Path],
|
|
429
|
+
model: str = "mindmap-fast",
|
|
430
|
+
*,
|
|
431
|
+
shard_size: int = 1,
|
|
432
|
+
beam: int = 0,
|
|
433
|
+
return_raw: bool = False,
|
|
434
|
+
tta: bool = False,
|
|
435
|
+
backend: str | None = None,
|
|
436
|
+
threads: int | None = None,
|
|
437
|
+
inverse_conform: bool = False,
|
|
438
|
+
no_turbo: bool = False,
|
|
439
|
+
pve: bool = False,
|
|
440
|
+
mask: bool = False,
|
|
441
|
+
border: int = 0,
|
|
442
|
+
ct: bool | None = None,
|
|
443
|
+
comply: bool | None = None,
|
|
444
|
+
crop: float | None = None,
|
|
445
|
+
) -> Any:
|
|
446
|
+
"""Segment one or more brain volumes with a native embedded model.
|
|
447
|
+
|
|
448
|
+
Accepts a :class:`Volume` (from :func:`load`), a file path (``str``/``Path``),
|
|
449
|
+
or a list of them. Output defaults to conformed 256^3 space for label models
|
|
450
|
+
(matching historical ``brainchop-cli`` behavior); pass ``inverse_conform=True``
|
|
451
|
+
to reslice back to the input voxel grid. ``mindgrab`` always returns results
|
|
452
|
+
in input space.
|
|
453
|
+
"""
|
|
454
|
+
canonical = _resolve_model(model)
|
|
455
|
+
if tta:
|
|
456
|
+
raise NotImplementedError(
|
|
457
|
+
"Test-time augmentation (tta=True) is not available in the native runtime."
|
|
458
|
+
)
|
|
459
|
+
if pve and canonical != "mindmap":
|
|
460
|
+
raise ValueError("pve=True is supported and validated only for model='mindmap'.")
|
|
461
|
+
if pve and return_raw:
|
|
462
|
+
raise ValueError("pve=True cannot be combined with return_raw=True.")
|
|
463
|
+
if (mask or border) and canonical != "mindgrab":
|
|
464
|
+
raise ValueError("mask and border options are supported only for model='mindgrab'.")
|
|
465
|
+
if threads is not None and threads < 0:
|
|
466
|
+
raise ValueError("threads must be nonnegative (0 selects automatically).")
|
|
467
|
+
if threads is not None and backend not in (None, "auto", "cpu"):
|
|
468
|
+
raise ValueError("threads forces CPU execution; omit backend or set backend='cpu'.")
|
|
469
|
+
if shard_size < 1:
|
|
470
|
+
raise ValueError("shard_size must be positive.")
|
|
471
|
+
if beam != 0 or shard_size != 1:
|
|
472
|
+
print(
|
|
473
|
+
"brainchop :: beam and shard_size are compatibility options; "
|
|
474
|
+
"native models are precompiled and run sequentially.",
|
|
475
|
+
file=sys.stderr,
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
single_input = not isinstance(volume, list)
|
|
479
|
+
items: list[Volume | str | Path] = [volume] if single_input else list(volume)
|
|
480
|
+
executable = native.find_executable(canonical)
|
|
481
|
+
|
|
482
|
+
results: list[Any] = []
|
|
483
|
+
raw_outputs: list[RawClassMaps] = []
|
|
484
|
+
|
|
485
|
+
with tempfile.TemporaryDirectory(prefix="brainchop-api-") as tmp:
|
|
486
|
+
tmp_dir = Path(tmp)
|
|
487
|
+
for idx, item in enumerate(items):
|
|
488
|
+
if isinstance(item, (str, Path)):
|
|
489
|
+
vol = _load_single(item)
|
|
490
|
+
elif isinstance(item, Volume):
|
|
491
|
+
vol = item
|
|
492
|
+
else:
|
|
493
|
+
raise TypeError(f"expected Volume or file path, got {type(item).__name__}")
|
|
494
|
+
|
|
495
|
+
if vol._source_path is not None and vol._data is None:
|
|
496
|
+
in_path = vol._source_path
|
|
497
|
+
else:
|
|
498
|
+
in_path = tmp_dir / f"in_{idx}.nii"
|
|
499
|
+
in_path.write_bytes(vol._serialize_nii())
|
|
500
|
+
|
|
501
|
+
out_path = tmp_dir / f"out_{idx}.nii"
|
|
502
|
+
cmd = [executable, "-o", str(out_path)]
|
|
503
|
+
if canonical != "mindgrab" and not inverse_conform:
|
|
504
|
+
cmd.append("--save-conform")
|
|
505
|
+
|
|
506
|
+
use_ct = vol._load_opts.get("ct", False) if ct is None else ct
|
|
507
|
+
use_comply = vol._load_opts.get("comply", False) if comply is None else comply
|
|
508
|
+
use_crop = vol._load_opts.get("crop") if crop is None else crop
|
|
509
|
+
|
|
510
|
+
if use_ct:
|
|
511
|
+
cmd.append("--ct")
|
|
512
|
+
if use_comply:
|
|
513
|
+
cmd.append("--comply")
|
|
514
|
+
if use_crop is not None:
|
|
515
|
+
cmd.extend(["--crop", str(use_crop)])
|
|
516
|
+
if no_turbo:
|
|
517
|
+
cmd.append("--no-turbo")
|
|
518
|
+
if return_raw:
|
|
519
|
+
cmd.append("--export-classes")
|
|
520
|
+
if pve:
|
|
521
|
+
cmd.append("--pve")
|
|
522
|
+
mask_path = tmp_dir / f"mask_{idx}.nii"
|
|
523
|
+
if mask:
|
|
524
|
+
cmd.extend(["--mask", str(mask_path)])
|
|
525
|
+
if border:
|
|
526
|
+
cmd.extend(["--border", str(border)])
|
|
527
|
+
if threads is not None:
|
|
528
|
+
cmd.extend(["-cpu", str(threads)])
|
|
529
|
+
elif backend is not None:
|
|
530
|
+
cmd.extend(["-backend", backend])
|
|
531
|
+
cmd.append(os.path.abspath(str(in_path)))
|
|
532
|
+
|
|
533
|
+
proc = subprocess.run(cmd, capture_output=True, text=True)
|
|
534
|
+
if proc.returncode != 0:
|
|
535
|
+
detail = (proc.stderr or proc.stdout or "").strip()
|
|
536
|
+
raise RuntimeError(
|
|
537
|
+
f"brainchop-{canonical} failed (exit {proc.returncode})"
|
|
538
|
+
+ (f": {detail}" if detail else "")
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
if pve:
|
|
542
|
+
tissue_vols: dict[str, Volume] = {}
|
|
543
|
+
for tissue in ("gm", "wm", "csf", "brain"):
|
|
544
|
+
tpath = tmp_dir / f"out_{idx}_{tissue}.nii"
|
|
545
|
+
tbytes = tpath.read_bytes()
|
|
546
|
+
tissue_vols[tissue] = Volume(
|
|
547
|
+
data=None, header=tbytes[:352], _raw_nii=tbytes, _is_label=False
|
|
548
|
+
)
|
|
549
|
+
results.append(tissue_vols)
|
|
550
|
+
else:
|
|
551
|
+
out_bytes = out_path.read_bytes()
|
|
552
|
+
out_vol = Volume(
|
|
553
|
+
data=None,
|
|
554
|
+
header=out_bytes[:352],
|
|
555
|
+
_raw_nii=out_bytes,
|
|
556
|
+
_is_label=(canonical != "mindgrab"),
|
|
557
|
+
)
|
|
558
|
+
if mask:
|
|
559
|
+
mask_bytes = mask_path.read_bytes()
|
|
560
|
+
mask_vol = Volume(
|
|
561
|
+
data=None, header=mask_bytes[:352], _raw_nii=mask_bytes, _is_label=True
|
|
562
|
+
)
|
|
563
|
+
results.append((out_vol, mask_vol))
|
|
564
|
+
else:
|
|
565
|
+
results.append(out_vol)
|
|
566
|
+
|
|
567
|
+
if return_raw:
|
|
568
|
+
n_cls = native.CLASS_COUNTS[canonical]
|
|
569
|
+
raw_list = [
|
|
570
|
+
(tmp_dir / f"out_{idx}_c{c}.nii").read_bytes() for c in range(n_cls)
|
|
571
|
+
]
|
|
572
|
+
raw_outputs.append(RawClassMaps(raw_list))
|
|
573
|
+
|
|
574
|
+
final_result = results[0] if single_input else results
|
|
575
|
+
if return_raw:
|
|
576
|
+
final_raw = raw_outputs[0] if single_input else raw_outputs
|
|
577
|
+
return final_result, final_raw
|
|
578
|
+
return final_result
|