xrayzoo 1.0.0__tar.gz

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.
xrayzoo-1.0.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Subham Divakar
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,6 @@
1
+ include README.md
2
+ include LICENSE
3
+ include pyproject.toml
4
+ include smoke_test.py
5
+ include xrayzoo/model_registry.json
6
+ recursive-include tests *.py
xrayzoo-1.0.0/PKG-INFO ADDED
@@ -0,0 +1,495 @@
1
+ Metadata-Version: 2.4
2
+ Name: xrayzoo
3
+ Version: 1.0.0
4
+ Summary: A PyTorch-based model zoo for X-ray image classification across multiple medical imaging datasets.
5
+ Author-email: Subham Divakar <shubham.divakar@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/shubham10divakar/XRayZoo
8
+ Project-URL: Repository, https://github.com/shubham10divakar/XRayZoo
9
+ Project-URL: Bug Tracker, https://github.com/shubham10divakar/XRayZoo/issues
10
+ Project-URL: HuggingFace, https://huggingface.co/sdmlai
11
+ Keywords: xray,medical imaging,deep learning,pytorch,chest xray,pneumonia,covid,fracture,model zoo,pretrained models,transfer learning
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Intended Audience :: Science/Research
15
+ Classifier: Intended Audience :: Healthcare Industry
16
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
17
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
18
+ Requires-Python: >=3.8
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Requires-Dist: torch>=1.12.0
22
+ Requires-Dist: torchvision>=0.13.0
23
+ Requires-Dist: timm>=0.6.0
24
+ Requires-Dist: Pillow>=8.0.0
25
+ Requires-Dist: numpy>=1.20.0
26
+ Provides-Extra: viz
27
+ Requires-Dist: matplotlib>=3.4.0; extra == "viz"
28
+ Provides-Extra: gradcam
29
+ Requires-Dist: grad-cam>=1.4.0; extra == "gradcam"
30
+ Provides-Extra: dev
31
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
32
+ Requires-Dist: pytest-cov; extra == "dev"
33
+ Requires-Dist: black; extra == "dev"
34
+ Requires-Dist: isort; extra == "dev"
35
+ Requires-Dist: flake8; extra == "dev"
36
+ Requires-Dist: twine; extra == "dev"
37
+ Requires-Dist: build; extra == "dev"
38
+ Provides-Extra: all
39
+ Requires-Dist: timm>=0.6.0; extra == "all"
40
+ Requires-Dist: matplotlib>=3.4.0; extra == "all"
41
+ Requires-Dist: grad-cam>=1.4.0; extra == "all"
42
+ Dynamic: license-file
43
+
44
+ # ๐Ÿฉป XRayZoo
45
+
46
+ [![PyPI version](https://badge.fury.io/py/xrayzoo.svg)](https://pypi.org/project/xrayzoo/)
47
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
48
+ [![Python Versions](https://img.shields.io/pypi/pyversions/xrayzoo.svg)](https://pypi.org/project/xrayzoo/)
49
+ [![Framework: PyTorch](https://img.shields.io/badge/Framework-PyTorch-orange.svg)](https://pytorch.org/)
50
+
51
+ ---
52
+
53
+ **XRayZoo** is a PyTorch-based model zoo for X-ray image classification.
54
+ It provides plug-and-play pretrained models across multiple medical imaging datasets โ€” with a unified API designed to scale across any number of datasets and architectures.
55
+
56
+ ---
57
+
58
+ ## ๐Ÿš€ Features
59
+
60
+ - โœ… **Pretrained PyTorch models** โ€” Ready-to-use architectures fine-tuned on real X-ray datasets
61
+ - ๐Ÿง  **Unified API** โ€” One interface for all datasets, tasks, and architectures
62
+ - ๐ŸŒ **HuggingFace-backed** โ€” Models download automatically on first use and are cached locally
63
+ - ๐Ÿ”ฌ **Feature Extraction** โ€” Extract intermediate representations for research and analysis
64
+ - โš™๏ธ **Model Introspection** โ€” Access weights, layers, and architecture details programmatically
65
+ - ๐ŸŽฏ **Multi-task Support** โ€” Binary, multiclass, and multilabel classification in one library
66
+ - ๐Ÿงฉ **Easily Extensible** โ€” Adding a new dataset or model requires only a JSON registry edit
67
+ - ๐Ÿ”ง **Fine-tuning Helpers** โ€” Freeze/unfreeze backbone, save/load checkpoints
68
+ - ๐Ÿ’ป **CLI Tool** โ€” `xrayzoo` command for terminal-based browsing and inference
69
+ - ๐Ÿ” **Advanced Search** โ€” Filter models by dataset, architecture, tag, task, or accuracy
70
+
71
+ ---
72
+
73
+ ## ๐Ÿ“ฆ Installation
74
+
75
+ ```bash
76
+ pip install xrayzoo
77
+ ```
78
+
79
+ For transformer models (ViT, Swin, etc.):
80
+ ```bash
81
+ pip install xrayzoo[timm]
82
+ ```
83
+
84
+ For Grad-CAM visualizations:
85
+ ```bash
86
+ pip install xrayzoo[gradcam]
87
+ ```
88
+
89
+ Install everything:
90
+ ```bash
91
+ pip install xrayzoo[all]
92
+ ```
93
+
94
+ ---
95
+
96
+ ## ๐Ÿงฌ Supported Datasets & Models
97
+
98
+ ### NIH Chest X-Ray 14 (`chestxray14`)
99
+ Multilabel classification โ€” 14 disease labels.
100
+
101
+ | Model Key | Architecture | Accuracy | AUC | Parameters |
102
+ |---|---|---|---|---|
103
+ | `densenet121_chestxray14_v1` | DenseNet121 | 82.1% | 0.841 | 8M |
104
+ | `resnet50_chestxray14_v1` | ResNet50 | 80.3% | 0.821 | 25M |
105
+ | `efficientnetb4_chestxray14_v1` | EfficientNet-B4 | 83.7% | 0.856 | 19M |
106
+ | `vit_base_chestxray14_v1` | ViT-Base-16 | 84.2% | 0.862 | 86M |
107
+
108
+ ### RSNA Pneumonia Detection (`rsna_pneumonia`)
109
+ Binary classification โ€” Normal vs Pneumonia.
110
+
111
+ | Model Key | Architecture | Accuracy | AUC |
112
+ |---|---|---|---|
113
+ | `resnet50_rsna_v1` | ResNet50 | 91.2% | 0.924 |
114
+ | `densenet121_rsna_v1` | DenseNet121 | 92.8% | 0.941 |
115
+
116
+ ### COVID-19 Chest X-Ray (`covidxray`)
117
+ Multiclass โ€” COVID-19 vs Normal vs Pneumonia.
118
+
119
+ | Model Key | Architecture | Accuracy | AUC |
120
+ |---|---|---|---|
121
+ | `resnet50_covid_v1` | ResNet50 | 95.3% | 0.978 |
122
+ | `mobilenetv2_covid_v1` | MobileNetV2 | 93.1% | 0.961 |
123
+
124
+ ### Bone Fracture X-Ray (`bone_fracture`)
125
+ Multiclass โ€” 7 fracture types.
126
+
127
+ | Model Key | Architecture | Accuracy | AUC |
128
+ |---|---|---|---|
129
+ | `densenet169_bone_v1` | DenseNet169 | 88.4% | 0.934 |
130
+
131
+ ---
132
+
133
+ ## โœ… Verified Working Example (Google Colab)
134
+
135
+ The following was tested and confirmed working on Google Colab:
136
+
137
+ ```python
138
+ from xrayzoo import XRayPredictor
139
+
140
+ predictor = XRayPredictor(model_name="swin_tiny_chestxray14_v1")
141
+ result = predictor.predict("/content/00000008_002.png")
142
+ print(result)
143
+ ```
144
+
145
+ **Output:**
146
+ ```
147
+ โฌ‡ Downloading nih_chest_xray/swin_tiny_patch4_window7_224/swin_tiny_patch4_window7_224_NihChestXrayMclass.pth from sdmlai/xrayzoo...
148
+ [โ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆโ–ˆ] 100%
149
+ โœ” Saved to: /root/.xrayzoo/models/chestxray14/nih_chest_xray/...
150
+
151
+ =======================================================
152
+ Model : swin_tiny_chestxray14_v1
153
+ Dataset : chestxray14
154
+ Task : multilabel
155
+ Classes : 14
156
+ Device : cpu
157
+ Accuracy : 99.7%
158
+ =======================================================
159
+
160
+ {
161
+ 'model': 'swin_tiny_chestxray14_v1',
162
+ 'dataset': 'chestxray14',
163
+ 'task': 'multilabel',
164
+ 'threshold': 0.5,
165
+ 'predictions': [
166
+ {'label': 'Cardiomegaly', 'confidence': 0.082755, 'positive': False},
167
+ {'label': 'Atelectasis', 'confidence': 0.061377, 'positive': False},
168
+ {'label': 'Fibrosis', 'confidence': 0.059574, 'positive': False},
169
+ {'label': 'Pleural_Thickening','confidence': 0.055506, 'positive': False},
170
+ {'label': 'Infiltration', 'confidence': 0.049657, 'positive': False},
171
+ {'label': 'Nodule', 'confidence': 0.041546, 'positive': False},
172
+ {'label': 'Effusion', 'confidence': 0.027421, 'positive': False},
173
+ {'label': 'Emphysema', 'confidence': 0.019398, 'positive': False},
174
+ {'label': 'Hernia', 'confidence': 0.01718, 'positive': False},
175
+ {'label': 'Mass', 'confidence': 0.009219, 'positive': False},
176
+ {'label': 'Pneumothorax', 'confidence': 0.008874, 'positive': False},
177
+ {'label': 'Consolidation', 'confidence': 0.007585, 'positive': False},
178
+ {'label': 'Pneumonia', 'confidence': 0.005516, 'positive': False},
179
+ {'label': 'Edema', 'confidence': 0.000554, 'positive': False}
180
+ ],
181
+ 'positive_labels': []
182
+ }
183
+ ```
184
+
185
+ > `positive_labels: []` means no disease was predicted above the 0.5 threshold โ€” the model classified this image as **No Finding** (normal chest X-ray). Lower the threshold to see confidence scores for each condition.
186
+
187
+ > **Note:** Model weights are downloaded automatically on first use (~110 MB) and cached at `~/.xrayzoo/models/`.
188
+
189
+ ---
190
+
191
+ ## ๐Ÿ”ฌ How to Use
192
+
193
+ ### 1. Explore the Zoo
194
+
195
+ ```python
196
+ from xrayzoo import zoo
197
+
198
+ # Summary of everything
199
+ zoo.summary()
200
+
201
+ # List all datasets
202
+ zoo.list_datasets()
203
+
204
+ # List models for a specific dataset
205
+ zoo.list_models(dataset="chestxray14")
206
+
207
+ # Detailed model info
208
+ zoo.info("densenet121_chestxray14_v1")
209
+
210
+ # Leaderboard (sorted by accuracy or AUC)
211
+ zoo.leaderboard(dataset="chestxray14", metric="auc")
212
+
213
+ # Compare models side by side
214
+ zoo.compare([
215
+ "densenet121_chestxray14_v1",
216
+ "vit_base_chestxray14_v1",
217
+ "efficientnetb4_chestxray14_v1"
218
+ ])
219
+
220
+ # Advanced search
221
+ zoo.search(tag="transformer", min_accuracy=83.0)
222
+ zoo.search(task="binary", architecture="densenet121")
223
+ ```
224
+
225
+ ### 2. Predict
226
+
227
+ ```python
228
+ from xrayzoo import XRayPredictor
229
+
230
+ predictor = XRayPredictor(model_name="densenet121_chestxray14_v1")
231
+ result = predictor.predict("path/to/xray.jpg")
232
+ print(result)
233
+ ```
234
+
235
+ **Multiclass output:**
236
+ ```json
237
+ {
238
+ "model": "resnet50_covid_v1",
239
+ "dataset": "covidxray",
240
+ "task": "multiclass",
241
+ "label": "COVID-19",
242
+ "confidence": 0.962,
243
+ "top_k": [
244
+ {"label": "COVID-19", "confidence": 0.962},
245
+ {"label": "Pneumonia", "confidence": 0.031},
246
+ {"label": "Normal", "confidence": 0.007}
247
+ ]
248
+ }
249
+ ```
250
+
251
+ **Multilabel output (ChestX-ray14):**
252
+ ```json
253
+ {
254
+ "model": "densenet121_chestxray14_v1",
255
+ "dataset": "chestxray14",
256
+ "task": "multilabel",
257
+ "threshold": 0.5,
258
+ "positive_labels": ["Atelectasis", "Effusion"],
259
+ "predictions": [
260
+ {"label": "Atelectasis", "confidence": 0.842, "positive": true},
261
+ {"label": "Effusion", "confidence": 0.713, "positive": true},
262
+ {"label": "Pneumonia", "confidence": 0.124, "positive": false}
263
+ ]
264
+ }
265
+ ```
266
+
267
+ ### 3. Batch Prediction
268
+
269
+ ```python
270
+ predictor = XRayPredictor(model_name="densenet121_rsna_v1")
271
+ results = predictor.predict_batch([
272
+ "xray1.jpg",
273
+ "xray2.jpg",
274
+ "xray3.jpg"
275
+ ])
276
+ ```
277
+
278
+ ### 4. Feature Extraction
279
+
280
+ ```python
281
+ predictor = XRayPredictor(model_name="densenet121_chestxray14_v1")
282
+
283
+ # Auto-extract from penultimate layer
284
+ features = predictor.extract_features("xray.jpg")
285
+ # โ†’ numpy array of shape (1024,)
286
+
287
+ # Extract from a specific layer
288
+ features = predictor.extract_features("xray.jpg", layer_name="features.denseblock3")
289
+ ```
290
+
291
+ ### 5. Model Introspection
292
+
293
+ ```python
294
+ predictor = XRayPredictor(model_name="densenet121_chestxray14_v1")
295
+
296
+ # Get full PyTorch model (for fine-tuning, ONNX export, etc.)
297
+ model = predictor.get_model()
298
+
299
+ # Get weights
300
+ weights = predictor.get_weights() # state_dict
301
+ weights_info = predictor.get_weights_info() # shape info
302
+
303
+ # List all layers
304
+ layers = predictor.list_layers()
305
+ for layer in layers[:5]:
306
+ print(layer)
307
+
308
+ # Count parameters
309
+ params = predictor.count_parameters()
310
+ print(f"Total: {params['total']:,} Trainable: {params['trainable']:,}")
311
+ ```
312
+
313
+ ### 6. Fine-tuning
314
+
315
+ ```python
316
+ import torch
317
+ from xrayzoo import XRayPredictor
318
+
319
+ predictor = XRayPredictor(model_name="densenet121_chestxray14_v1")
320
+
321
+ # Freeze backbone, only train classifier head
322
+ predictor.freeze_backbone()
323
+
324
+ # Or unfreeze everything
325
+ predictor.unfreeze_all()
326
+
327
+ # Get the model for your training loop
328
+ model = predictor.get_model()
329
+ optimizer = torch.optim.Adam(
330
+ filter(lambda p: p.requires_grad, model.parameters()),
331
+ lr=1e-4
332
+ )
333
+
334
+ # Save your fine-tuned checkpoint
335
+ predictor.save_checkpoint("my_finetuned.pth", extra_meta={"notes": "my experiment"})
336
+ ```
337
+
338
+ ### 7. Device Control
339
+
340
+ ```python
341
+ import torch
342
+
343
+ # Auto-detect (CUDA โ†’ MPS โ†’ CPU)
344
+ predictor = XRayPredictor("densenet121_chestxray14_v1")
345
+
346
+ # Force specific device
347
+ predictor = XRayPredictor(
348
+ "densenet121_chestxray14_v1",
349
+ device=torch.device("cuda:0")
350
+ )
351
+ ```
352
+
353
+ ---
354
+
355
+ ## ๐Ÿ–ฅ๏ธ CLI Usage
356
+
357
+ ```bash
358
+ # Summary
359
+ xrayzoo summary
360
+
361
+ # Browse
362
+ xrayzoo datasets
363
+ xrayzoo models
364
+ xrayzoo models --dataset chestxray14
365
+
366
+ # Model info
367
+ xrayzoo info densenet121_chestxray14_v1
368
+
369
+ # Leaderboard
370
+ xrayzoo leaderboard --dataset chestxray14 --metric auc
371
+
372
+ # Search
373
+ xrayzoo search --tag transformer --min-accuracy 83.0
374
+
375
+ # Predict
376
+ xrayzoo predict xray.jpg --model densenet121_chestxray14_v1 --top-k 3
377
+
378
+ # Cache management
379
+ xrayzoo cache list
380
+ xrayzoo cache clear
381
+ xrayzoo cache clear --dataset chestxray14
382
+ ```
383
+
384
+ ---
385
+
386
+ ## ๐Ÿงฉ How to Add a New Dataset (Scalable Design)
387
+
388
+ XRayZoo is designed so that **adding a new dataset requires zero Python code changes** โ€” only a JSON edit.
389
+
390
+ 1. **Train your model** on the new dataset and upload the `.pth` file + labels JSON to HuggingFace.
391
+
392
+ 2. **Add a new entry** to `xrayzoo/model_registry.json`:
393
+
394
+ ```json
395
+ {
396
+ "datasets": {
397
+ "your_new_dataset": {
398
+ "name": "Your Dataset Name",
399
+ "description": "Dataset description",
400
+ "num_classes": 5,
401
+ "task": "multiclass",
402
+ "input_size": [224, 224],
403
+ "labels": ["Class A", "Class B", "Class C", "Class D", "Class E"],
404
+ "models": {
405
+ "resnet50_your_dataset_v1": {
406
+ "description": "ResNet50 trained on your dataset",
407
+ "architecture": "resnet50",
408
+ "input_size": [224, 224],
409
+ "accuracy": 92.0,
410
+ "auc": 0.96,
411
+ "parameters": "25M",
412
+ "hf_repo": "sdmlai/xrayzoo",
413
+ "model_filename": "resnet50_your_dataset_v1.pth",
414
+ "labels_filename": "your_dataset_labels.json",
415
+ "preprocessing": "chestxray_standard",
416
+ "task": "multiclass",
417
+ "tags": ["cnn", "resnet", "your-dataset", "multiclass"]
418
+ }
419
+ }
420
+ }
421
+ }
422
+ }
423
+ ```
424
+
425
+ 3. That's it. The model is now available across the full API: `zoo.list_models()`, `XRayPredictor(...)`, leaderboard, search, CLI, etc.
426
+
427
+ ---
428
+
429
+ ## ๐Ÿ“ Project Structure
430
+
431
+ ```
432
+ xrayzoo/
433
+ โ”œโ”€โ”€ xrayzoo/
434
+ โ”‚ โ”œโ”€โ”€ __init__.py # Public API exports
435
+ โ”‚ โ”œโ”€โ”€ model_registry.json # All datasets & models (the scalable data layer)
436
+ โ”‚ โ”œโ”€โ”€ registry.py # ModelRegistry class โ€” reads registry JSON
437
+ โ”‚ โ”œโ”€โ”€ predictor.py # XRayPredictor โ€” main inference class
438
+ โ”‚ โ”œโ”€โ”€ zoo.py # Zoo โ€” discovery & display interface
439
+ โ”‚ โ”œโ”€โ”€ downloader.py # HuggingFace download + local cache
440
+ โ”‚ โ”œโ”€โ”€ model_loader.py # Architecture builder + weight loader
441
+ โ”‚ โ”œโ”€โ”€ preprocessing.py # Image transform pipelines
442
+ โ”‚ โ”œโ”€โ”€ cli.py # `xrayzoo` CLI tool
443
+ โ”‚ โ””โ”€โ”€ exceptions.py # Custom exceptions
444
+ โ”œโ”€โ”€ tests/
445
+ โ”‚ โ””โ”€โ”€ test_xrayzoo.py
446
+ โ”œโ”€โ”€ setup.py
447
+ โ”œโ”€โ”€ pyproject.toml
448
+ โ”œโ”€โ”€ MANIFEST.in
449
+ โ””โ”€โ”€ README.md
450
+ ```
451
+
452
+ ---
453
+
454
+ ## ๐Ÿ—ƒ๏ธ Local Cache
455
+
456
+ Models are cached in `~/.xrayzoo/models/<dataset>/` after first download.
457
+
458
+ Override the cache directory:
459
+ ```bash
460
+ export XRAYZOO_CACHE_DIR=/custom/path
461
+ ```
462
+ Or in Python:
463
+ ```python
464
+ predictor = XRayPredictor("densenet121_chestxray14_v1", cache_dir="/custom/path")
465
+ ```
466
+
467
+ ---
468
+
469
+ ## ๐Ÿ“ License
470
+
471
+ MIT License โ€” free for academic and commercial use.
472
+
473
+ ---
474
+
475
+ ## ๐Ÿค Contributing
476
+
477
+ Contributions are welcome! You can help by:
478
+ - ๐Ÿง  Training and uploading new models to HuggingFace
479
+ - ๐Ÿ“Š Adding new X-ray datasets to the registry
480
+ - โš™๏ธ Adding new architectures to `model_loader.py`
481
+ - ๐Ÿงช Writing tests and benchmarks
482
+ - ๐Ÿ“š Improving documentation
483
+
484
+ ---
485
+
486
+ ## ๐Ÿ“ซ Contact
487
+
488
+ **Author:** Subham Divakar
489
+ **Email:** shubham.divakar@gmail.com
490
+ **GitHub:** [shubham10divakar/XRayZoo](https://github.com/shubham10divakar/XRayZoo)
491
+ **HuggingFace:** [huggingface.co/sdmlai](https://huggingface.co/sdmlai)
492
+
493
+ ---
494
+
495
+ > "Bringing pretrained X-ray intelligence to every researcher โ€” one model at a time." ๐Ÿฉป