brainchop 0.1.0__py3-none-any.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 ADDED
@@ -0,0 +1 @@
1
+
brainchop/convert.py ADDED
@@ -0,0 +1,111 @@
1
+ import json
2
+ import numpy as np
3
+ from tinygrad import Tensor
4
+ from nibabel import save, load, Nifti1Image
5
+
6
+ def normalize(img):
7
+ img = (img - img.min()) / (img.max() - img.min())
8
+ return img
9
+
10
+ def load_tfjs_model(json_path, bin_path):
11
+ with open(json_path, "r") as f:
12
+ model_spec = json.load(f)
13
+
14
+ with open(bin_path, "rb") as f:
15
+ weights_data = np.frombuffer(f.read(), dtype=np.float32)
16
+
17
+ return model_spec, weights_data
18
+
19
+ def create_activation(name):
20
+ activation_map = {
21
+ "relu": lambda x: x.relu(),
22
+ "elu": lambda x: x.elu(),
23
+ "sigmoid": lambda x: x.sigmoid(),
24
+ "tanh": lambda x: x.tanh(),
25
+ "leaky_relu": lambda x: x.leakyrelu(),
26
+ }
27
+ return activation_map[name]
28
+
29
+ def calculate_same_padding(kernel_size, dilation):
30
+ if isinstance(kernel_size, int):
31
+ kernel_size = (kernel_size,) * 3
32
+ if isinstance(dilation, int):
33
+ dilation = (dilation,) * 3
34
+
35
+ padding = []
36
+ for k, d in zip(kernel_size, dilation):
37
+ padding.append((k - 1) * d // 2)
38
+ return tuple(padding)
39
+
40
+
41
+ def tinygrad_model(json_path, bin_path, x):
42
+
43
+ model_spec, weights_data = load_tfjs_model(json_path, bin_path)
44
+ x = normalize(x)
45
+ layers = []
46
+ weight_index = 0
47
+ in_channels = 1 # Start with 1 input channel
48
+ spec = model_spec["modelTopology"]["model_config"]["config"]["layers"][1:]
49
+ for i, layer in enumerate(spec): # skip input layer
50
+ if layer["class_name"] == "Conv3D":
51
+ config = layer["config"]
52
+ padding = calculate_same_padding(
53
+ config["kernel_size"], config["dilation_rate"]
54
+ )
55
+
56
+ in_channels=in_channels,
57
+ out_channels=config["filters"],
58
+ kernel_size=config["kernel_size"],
59
+ stride=config["strides"],
60
+ padding=padding,
61
+ dilation=config["dilation_rate"],
62
+
63
+ # Load weights and biases
64
+ k, k, k = kernel_size[0]
65
+ weight_shape = [out_channels[0], in_channels[0], k,k,k]
66
+ # putting the shape into tfjs order
67
+ weight_shape = [weight_shape[i] for i in (2, 3, 4, 1, 0)]
68
+ bias_shape = [out_channels[0]]
69
+
70
+ weight_size = np.prod(weight_shape)
71
+ bias_size = np.prod(bias_shape)
72
+
73
+ weight = weights_data[
74
+ weight_index : weight_index + weight_size].reshape(weight_shape)
75
+ weight = np.transpose(weight, (4, 3, 0, 1, 2))
76
+ weight_index += weight_size
77
+
78
+ bias = weights_data[
79
+ weight_index : weight_index + bias_size].reshape(bias_shape)
80
+ weight_index += bias_size
81
+
82
+ weight_data = Tensor(weight.copy())
83
+ bias_data = Tensor(bias.copy())
84
+ x = x.conv2d(
85
+ weight = weight_data,
86
+ bias = bias_data,
87
+ groups = 1,
88
+ stride = stride[0][0],
89
+ dilation = dilation[0][0],
90
+ padding = padding[0][0]
91
+ )
92
+ in_channels = out_channels[0]
93
+
94
+ elif layer["class_name"] == "Activation":
95
+ activation = create_activation(layer["config"]["activation"])
96
+ x = activation(x)
97
+ return x.argmax(1).numpy()[0]
98
+
99
+ if __name__ == "__main__":
100
+ json_path = "model.json"
101
+ bin_path = "model.bin"
102
+ input_path = "example.nii.gz"
103
+ output_path = "output.nii.gz"
104
+
105
+ img = load(input_path)
106
+ tensor = np.array(img.dataobj).reshape(1,1,256,256,256)
107
+ t = Tensor(tensor.astype(np.float16))
108
+ out_tensor = tinygrad_model(json_path, bin_path,t)
109
+
110
+ save(Nifti1Image(out_tensor, img.affine, img.header), output_path)
111
+ print(f"Output saved as {output_path}")
brainchop/main.py ADDED
@@ -0,0 +1,65 @@
1
+ import os
2
+ import sys
3
+ import argparse
4
+ from nibabel import save, load, Nifti1Image
5
+ from tinygrad import Tensor
6
+ import numpy as np
7
+
8
+ # Add the directory containing the script to the Python path
9
+ script_dir = os.path.dirname(os.path.abspath(__file__))
10
+ project_root = os.path.dirname(script_dir)
11
+ sys.path.insert(0, project_root)
12
+
13
+ from brainchop.model import tinygrad_model
14
+
15
+ def find_file(filename, search_paths):
16
+ for path in search_paths:
17
+ file_path = os.path.join(path, filename)
18
+ if os.path.isfile(file_path):
19
+ return file_path
20
+ return None
21
+
22
+ def main():
23
+ parser = argparse.ArgumentParser(description="BrainChop: Brain segmentation tool")
24
+ parser.add_argument("input", help="Input NIfTI file path")
25
+ parser.add_argument("-o", "--output", default="output.nii.gz", help="Output NIfTI file path")
26
+ parser.add_argument("--json", default="model.json", help="Path to model JSON file")
27
+ parser.add_argument("--bin", default="model.bin", help="Path to model binary file")
28
+ args = parser.parse_args()
29
+
30
+ # Convert input and output paths to absolute paths
31
+ args.input = os.path.abspath(args.input)
32
+ args.output = os.path.abspath(args.output)
33
+
34
+ # Define search paths
35
+ search_paths = [
36
+ os.getcwd(), # Current working directory
37
+ os.path.dirname(args.input), # Directory of the input file
38
+ script_dir, # Directory of the main.py script
39
+ project_root, # Root directory of the project
40
+ os.path.join(project_root, 'example'), # Example directory
41
+ ]
42
+
43
+ # Find JSON and bin files
44
+ args.json = find_file(args.json, search_paths) or args.json
45
+ args.bin = find_file(args.bin, search_paths) or args.bin
46
+
47
+ # Verify all required files exist
48
+ for file_path in [args.input, args.json, args.bin]:
49
+ if not os.path.isfile(file_path):
50
+ print(f"Error: File not found: {file_path}")
51
+ sys.exit(1)
52
+
53
+ try:
54
+ img = load(args.input)
55
+ tensor = np.array(img.dataobj).reshape(1, 1, 256, 256, 256)
56
+ t = Tensor(tensor.astype(np.float16))
57
+ out_tensor = tinygrad_model(args.json, args.bin, t)
58
+ save(Nifti1Image(out_tensor, img.affine, img.header), args.output)
59
+ print(f"Output saved as {args.output}")
60
+ except Exception as e:
61
+ print(f"An error occurred: {str(e)}")
62
+ sys.exit(1)
63
+
64
+ if __name__ == "__main__":
65
+ main()
brainchop/model.py ADDED
@@ -0,0 +1,97 @@
1
+ import json
2
+ import numpy as np
3
+ from tinygrad import Tensor
4
+ from nibabel import save, load, Nifti1Image
5
+
6
+ def normalize(img):
7
+ img = (img - img.min()) / (img.max() - img.min())
8
+ return img
9
+
10
+ def load_tfjs_model(json_path, bin_path):
11
+ with open(json_path, "r") as f:
12
+ model_spec = json.load(f)
13
+
14
+ with open(bin_path, "rb") as f:
15
+ weights_data = np.frombuffer(f.read(), dtype=np.float32)
16
+
17
+ return model_spec, weights_data
18
+
19
+ def create_activation(name):
20
+ activation_map = {
21
+ "relu": lambda x: x.relu(),
22
+ "elu": lambda x: x.elu(),
23
+ "sigmoid": lambda x: x.sigmoid(),
24
+ "tanh": lambda x: x.tanh(),
25
+ "leaky_relu": lambda x: x.leakyrelu(),
26
+ }
27
+ return activation_map[name]
28
+
29
+ def calculate_same_padding(kernel_size, dilation):
30
+ if isinstance(kernel_size, int):
31
+ kernel_size = (kernel_size,) * 3
32
+ if isinstance(dilation, int):
33
+ dilation = (dilation,) * 3
34
+
35
+ padding = []
36
+ for k, d in zip(kernel_size, dilation):
37
+ padding.append((k - 1) * d // 2)
38
+ return tuple(padding)
39
+
40
+
41
+ def tinygrad_model(json_path, bin_path, x):
42
+
43
+ model_spec, weights_data = load_tfjs_model(json_path, bin_path)
44
+ x = normalize(x)
45
+ layers = []
46
+ weight_index = 0
47
+ in_channels = 1 # Start with 1 input channel
48
+ spec = model_spec["modelTopology"]["model_config"]["config"]["layers"][1:]
49
+ for i, layer in enumerate(spec): # skip input layer
50
+ if layer["class_name"] == "Conv3D":
51
+ config = layer["config"]
52
+ padding = calculate_same_padding(
53
+ config["kernel_size"], config["dilation_rate"]
54
+ )
55
+
56
+ in_channels=in_channels,
57
+ out_channels=config["filters"],
58
+ kernel_size=config["kernel_size"],
59
+ stride=config["strides"],
60
+ padding=padding,
61
+ dilation=config["dilation_rate"],
62
+
63
+ # Load weights and biases
64
+ k, k, k = kernel_size[0]
65
+ weight_shape = [out_channels[0], in_channels[0], k,k,k]
66
+ # putting the shape into tfjs order
67
+ weight_shape = [weight_shape[i] for i in (2, 3, 4, 1, 0)]
68
+ bias_shape = [out_channels[0]]
69
+
70
+ weight_size = np.prod(weight_shape)
71
+ bias_size = np.prod(bias_shape)
72
+
73
+ weight = weights_data[
74
+ weight_index : weight_index + weight_size].reshape(weight_shape)
75
+ weight = np.transpose(weight, (4, 3, 0, 1, 2))
76
+ weight_index += weight_size
77
+
78
+ bias = weights_data[
79
+ weight_index : weight_index + bias_size].reshape(bias_shape)
80
+ weight_index += bias_size
81
+
82
+ weight_data = Tensor(weight.copy())
83
+ bias_data = Tensor(bias.copy())
84
+ x = x.conv2d(
85
+ weight = weight_data,
86
+ bias = bias_data,
87
+ groups = 1,
88
+ stride = stride[0][0],
89
+ dilation = dilation[0][0],
90
+ padding = padding[0][0]
91
+ )
92
+ in_channels = out_channels[0]
93
+
94
+ elif layer["class_name"] == "Activation":
95
+ activation = create_activation(layer["config"]["activation"])
96
+ x = activation(x)
97
+ return x.argmax(1).numpy()[0]
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Mike Doan
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,53 @@
1
+ Metadata-Version: 2.1
2
+ Name: brainchop
3
+ Version: 0.1.0
4
+ Summary: A tool for brain segmentation using tinygrad
5
+ Home-page: https://github.com/neuroneural/brainchop-cli
6
+ Author: Mike Doan
7
+ Author-email: spikedoanz@gmail.com
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: License :: OSI Approved :: MIT License
10
+ Classifier: Operating System :: OS Independent
11
+ Requires-Python: >=3.6
12
+ Description-Content-Type: text/markdown
13
+ License-File: LICENSE
14
+ Requires-Dist: numpy
15
+ Requires-Dist: tinygrad
16
+ Requires-Dist: nibabel
17
+
18
+ # BrainChop
19
+
20
+ BrainChop is a lightweight tool for brain segmentation using tinygrad that runs on pretty much everything.
21
+
22
+ ---
23
+
24
+ ## Installation
25
+
26
+ You can install BrainChop using pip:
27
+
28
+ ```
29
+ pip install brainchop
30
+ ```
31
+
32
+ ## Usage
33
+
34
+ To use BrainChop, run the following command:
35
+
36
+ ```
37
+ brainchop input.nii.gz -o output.nii.gz
38
+ ```
39
+
40
+ Where:
41
+ - `input.nii.gz` is your input NIfTI file
42
+ - `output.nii.gz` is the desired output file name
43
+
44
+ ## Requirements
45
+
46
+ - Python 3.6+
47
+ - numpy
48
+ - tinygrad
49
+ - nibabel
50
+
51
+ ## License
52
+
53
+ This project is licensed under the MIT License.
@@ -0,0 +1,10 @@
1
+ brainchop/__init__.py,sha256=AbpHGcgLb-kRsJGnwFEktk7uzpZOCcBY74-YBdrKVGs,1
2
+ brainchop/convert.py,sha256=ct0Gvt9kmKqPP2MkqeiVWkqcNIQmO3rEm-b-YkULSZ8,3349
3
+ brainchop/main.py,sha256=rVThWDXPxiDQpMJ_X5cS-CHcxFhCXPfVJEjoEEdzx6c,2378
4
+ brainchop/model.py,sha256=tYwx4sM_1leKo9tNeF41_p8ZVGbLp_UoJFQ4NsmTmjM,2916
5
+ brainchop-0.1.0.dist-info/LICENSE,sha256=hxJPYExi_agShTqPFAn10IQfV9Jnr7nrSb4708_llY8,1066
6
+ brainchop-0.1.0.dist-info/METADATA,sha256=f4EL2YHK4kSJ962fc6pjk09OZBQ9x9RI20uNniV4ECQ,1054
7
+ brainchop-0.1.0.dist-info/WHEEL,sha256=R0nc6qTxuoLk7ShA2_Y-UWkN8ZdfDBG2B6Eqpz2WXbs,91
8
+ brainchop-0.1.0.dist-info/entry_points.txt,sha256=OtPeN3BNO5KV6lPYH_0yep4zcvwqbsCFQv4Oq4HqHBI,50
9
+ brainchop-0.1.0.dist-info/top_level.txt,sha256=0DgLnatINxuyorbwVl_OR4FS-Sp8z3aQcZQRDD4nunM,10
10
+ brainchop-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (72.1.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ brainchop = brainchop.main:main
@@ -0,0 +1 @@
1
+ brainchop