benedictpepper commited on
Commit
dead8f4
Β·
0 Parent(s):

Clean deployment

Browse files
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ *.keras filter=lfs diff=lfs merge=lfs -text
Dockerfile ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # Install system dependencies required for OpenCV headless
4
+ RUN apt-get update && \
5
+ apt-get install -y libgl1 libglib2.0-0 && \
6
+ rm -rf /var/lib/apt/lists/*
7
+
8
+ WORKDIR /app
9
+
10
+ # Install python dependencies
11
+ COPY requirements.txt .
12
+ RUN pip install --no-cache-dir -r requirements.txt
13
+
14
+ # Copy the entire project to the container
15
+ COPY . .
16
+
17
+ # Change working directory to demo where app.py lives
18
+ WORKDIR /app/demo
19
+
20
+ # Hugging Face Spaces defaults to port 7860
21
+ EXPOSE 7860
22
+
23
+ # Run the Flask app on port 7860
24
+ ENV FLASK_APP=app.py
25
+ CMD ["flask", "run", "--host=0.0.0.0", "--port=7860"]
README.md ADDED
@@ -0,0 +1,313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # EfficientNetB4 Pneumonia Classification: Fixed Size vs. Progressive Resizing
2
+
3
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](LICENSE)
4
+ [![Python 3.9+](https://img.shields.io/badge/Python-3.9%2B-blue.svg)](https://www.python.org/)
5
+ [![TensorFlow 2.19](https://img.shields.io/badge/TensorFlow-2.19-orange.svg)](https://www.tensorflow.org/)
6
+ [![Platform: Kaggle](https://img.shields.io/badge/Platform-Kaggle-20BEFF.svg)](https://www.kaggle.com/)
7
+
8
+ > **Paper:** *Perbandingan Strategi Pelatihan EfficientNetB4 dengan dan tanpa Progressive Resizing untuk Klasifikasi Pneumonia Bakterial dan Viral pada Citra X-Ray Dada*
9
+ > Presented at SEMNAS (National Seminar on Technology and Applied Science), 2025.
10
+
11
+ ---
12
+
13
+ ## Overview
14
+
15
+ This repository accompanies a comparative study evaluating two training strategies for
16
+ EfficientNetB4 on the task of distinguishing **bacterial** from **viral pneumonia** in
17
+ chest X-ray images:
18
+
19
+ 1. **Fixed Size** β€” trains exclusively at the target resolution (384 Γ— 384 px) using a two-phase
20
+ head-training + global fine-tuning schedule.
21
+ 2. **Progressive Resizing** β€” a curriculum learning approach that trains through progressively
22
+ higher resolutions (224 β†’ 256 β†’ 384 px) with continuous weight transfer between stages.
23
+
24
+ Both models share an identical architecture, loss function, optimizer, and augmentation pipeline.
25
+ The only variable is the training resolution schedule.
26
+
27
+ **Key finding:** Fixed-size training at 384 Γ— 384 px achieves **86.92% accuracy and 0.9198 AUC**,
28
+ outperforming Progressive Resizing (78.46%, AUC 0.8011) by 8.46 percentage points, despite using
29
+ fewer total epochs (32 vs 41). The result suggests that sustained high-resolution exposure during
30
+ fine-tuning is more critical than curriculum-based resolution scaling for this task.
31
+
32
+ ---
33
+
34
+ ## Results
35
+
36
+ ### Main Experiments β€” Test Set (N=390, 242 bacterial : 148 viral, with 2-step TTA)
37
+
38
+ | Model | Strategy | Epochs | Accuracy | ROC AUC | Macro F1 | Viral Recall |
39
+ |-------|----------|--------|----------|---------|----------|--------------|
40
+ | EfficientNetB4 | **Fixed Size** (384Γ—384) | **32** | **86.92%** | **0.9198** | **85.02%** | **67.57%** |
41
+ | EfficientNetB4 | Progressive Resizing (224β†’256β†’384) | 41 | 78.46% | 0.8011 | 74.72% | 52.70% |
42
+
43
+ ### Per-Class Metrics
44
+
45
+ | Class | Precision (Fixed) | Recall (Fixed) | F1 (Fixed) | Precision (Prog) | Recall (Prog) | F1 (Prog) |
46
+ |-------|-------------------|----------------|------------|------------------|---------------|-----------|
47
+ | Bacterial | 83.28% | 98.76% | 90.36% | 76.51% | 94.21% | 84.44% |
48
+ | Viral | 97.09% | 67.57% | 79.68% | 84.78% | 52.70% | 65.00% |
49
+
50
+ > **Note:** The test set uses the original Kaggle `test/PNEUMONIA` distribution (unbalanced:
51
+ > 242 bacterial, 148 viral). Both models show higher false-negative rates for the viral class,
52
+ > reflecting the intrinsic difficulty of this clinically important sub-task.
53
+
54
+ ### Legacy Architecture Comparison (v1 pipeline, `archive/legacy_experiments/`)
55
+
56
+ | Model | Accuracy |
57
+ |-------|----------|
58
+ | VGG16 v2 | 55.47% |
59
+ | EfficientNetB4 v1 | 52.34% |
60
+ | EfficientNetB0 v2 | 40.62% |
61
+ | ResNet50 v1 | 37.50% |
62
+
63
+ ---
64
+
65
+ ## Architecture
66
+
67
+ ```
68
+ EfficientNetB4 (ImageNet pretrained, include_top=False)
69
+ β†’ top_activation feature maps [None, H, W, 1792]
70
+ β”œβ”€β”€ GlobalAveragePooling2D β†’ [None, 1792]
71
+ └── GlobalMaxPooling2D β†’ [None, 1792]
72
+ β†’ Concatenate β†’ [None, 3584] ← Concat Pooling
73
+ β†’ Dense(512, activation='swish')
74
+ β†’ BatchNormalization
75
+ β†’ Dropout(0.5)
76
+ β†’ Dense(2, activation='softmax', dtype='float32')
77
+
78
+ Total parameters: 18,594,913
79
+ Head parameters: 921,090
80
+ Fine-tuned (block6a+): 9,556,294
81
+ ```
82
+
83
+ | Component | Detail |
84
+ |-----------|--------|
85
+ | Loss | `CategoricalFocalCrossentropy` (Ξ±=0.25, Ξ³=2.0, label_smoothing=0.1) |
86
+ | Optimizer | AdamW + `LossScaleOptimizer` (fp16) |
87
+ | LR β€” head | 1Γ—10⁻³ |
88
+ | LR β€” Fixed Size FT | 1Γ—10⁻⁴ β†’ 6.25Γ—10⁻⁢ (ReduceLROnPlateau Γ—0.5) |
89
+ | LR β€” Progressive FT | CosineDecayRestarts (initial 1Γ—10⁻⁡, t_mul=2.0, m_mul=0.9) |
90
+ | Augmentation | CLAHE Β· ShiftScaleRotate Β· RandomBrightnessContrast Β· HorizontalFlip Β· MixUp |
91
+ | TTA | 2-step deterministic (original + H-flip) |
92
+ | Platform | Kaggle Notebooks β€” Tesla P100-PCIE-16GB |
93
+ | Framework | TensorFlow 2.19.0, Keras, mixed precision fp16 |
94
+
95
+ ---
96
+
97
+ ## Dataset
98
+
99
+ All experiments use the **Kermany et al. Chest X-Ray** dataset (bacterial vs. viral pneumonia subset).
100
+
101
+ - **Source:** [Kaggle β€” Chest X-Ray Images (Pneumonia)](https://www.kaggle.com/datasets/paultimothymooney/chest-xray-pneumonia)
102
+ - **Classes used:** Bacterial Pneumonia (label 0), Viral Pneumonia (label 1). Normal class excluded.
103
+ - **Labeling:** Derived from filename prefix (`bacteria_*` β†’ 0, `virus_*` β†’ 1)
104
+
105
+ **Split protocol (v2 pipeline):**
106
+
107
+ | Subset | Bacterial | Viral | Total |
108
+ |--------|-----------|-------|-------|
109
+ | Training (80% of pool) | ~2,030 | ~1,076 | 3,106 |
110
+ | Validation (20% of pool) | ~508 | ~269 | 777 |
111
+ | Test (Kaggle original, isolated) | 242 | 148 | **390** |
112
+ | Pool (train + val combined) | 2,538 | 1,345 | 3,883 |
113
+
114
+ > **Class imbalance handling:** Computed via `sklearn.compute_class_weight('balanced')`.
115
+ > Bacterial weight = 0.765 Β· Viral weight = 1.444. No physical oversampling was performed.
116
+
117
+ ---
118
+
119
+ ## Visualizations
120
+
121
+ ### Architecture & Pipeline
122
+
123
+ <table>
124
+ <tr>
125
+ <td align="center"><b>Model Architecture β€” Concat Pooling</b></td>
126
+ <td align="center"><b>Training Strategy Comparison</b></td>
127
+ </tr>
128
+ <tr>
129
+ <td><img src="figures/01_architecture_concat_pooling.png" width="420"/></td>
130
+ <td><img src="figures/02_training_strategy_comparison.png" width="420"/></td>
131
+ </tr>
132
+ <tr>
133
+ <td align="center" colspan="2"><b>Data Pipeline &amp; Augmentation Strategy</b></td>
134
+ </tr>
135
+ <tr>
136
+ <td colspan="2" align="center"><img src="figures/03_data_pipeline.png" width="840"/></td>
137
+ </tr>
138
+ </table>
139
+
140
+ ### Experimental Results (from Kaggle Execution)
141
+
142
+ <table>
143
+ <tr>
144
+ <td align="center"><b>ROC Curve β€” Both Models (N=390)</b></td>
145
+ <td align="center"><b>Confusion Matrix β€” Both Models (N=390, TTA)</b></td>
146
+ </tr>
147
+ <tr>
148
+ <td><img src="kaggle_output/roc_comparison.png" width="420"/></td>
149
+ <td><img src="kaggle_output/confusion_matrix_comparison.png" width="420"/></td>
150
+ </tr>
151
+ <tr>
152
+ <td align="center"><b>Training Curves β€” Fixed Size (32 epochs)</b></td>
153
+ <td align="center"><b>Training Curves β€” Progressive Resizing (41 epochs)</b></td>
154
+ </tr>
155
+ <tr>
156
+ <td><img src="kaggle_output/learning_curves_fixed.png" width="420"/></td>
157
+ <td><img src="kaggle_output/learning_curves_progressive.png" width="420"/></td>
158
+ </tr>
159
+ </table>
160
+
161
+ ### Grad-CAM Interpretability: Fixed Size vs. Progressive Resizing
162
+
163
+ <table>
164
+ <tr>
165
+ <td align="center"><b>Grad-CAM Comparison (Both Models)</b></td>
166
+ </tr>
167
+ <tr>
168
+ <td align="center"><img src="figures/09_gradcam_comparison.png" width="840"/></td>
169
+ </tr>
170
+ </table>
171
+
172
+ > Grad-CAM activations computed on the `top_activation` layer (12Γ—12Γ—1,792 feature maps).
173
+ > **Fixed Size (left column)** shows precise, focused activation on the pathological lung parenchyma.
174
+ > **Progressive Resizing (right column)** shows slightly more diffuse activation patterns.
175
+ > Both models misclassify the viral samples (bottom two rows), reacting to the bilateral interstitial infiltrates but failing to find sufficient discriminative features for a correct viral prediction.
176
+
177
+ ---
178
+
179
+ ## Repository Structure
180
+
181
+ ```
182
+ .
183
+ β”œβ”€β”€ kaggle_pipeline/ # 8-cell Kaggle notebook, broken into scripts
184
+ β”‚ β”œβ”€β”€ 01_setup_and_imports.py
185
+ β”‚ β”œβ”€β”€ 02_data_pipeline.py # tf.data + Albumentations + MixUp
186
+ β”‚ β”œβ”€β”€ 03_model_architecture.py # Concat Pooling + Focal Loss
187
+ β”‚ β”œβ”€β”€ 04_experiment_1_fixed_size.py
188
+ β”‚ β”œβ”€β”€ 05_experiment_1_evaluation.py
189
+ β”‚ β”œβ”€β”€ 06_experiment_2_progressive.py
190
+ β”‚ β”œβ”€β”€ 07_experiment_2_evaluation.py
191
+ β”‚ β”œβ”€β”€ 08_final_comparison_and_gradcam.py
192
+ β”‚ └── README.md
193
+ β”‚
194
+ β”œβ”€β”€ kaggle_output/ # Figures and execution log from Kaggle run
195
+ β”‚ β”œβ”€β”€ *.png # Training curves, ROC, confusion matrices
196
+ β”‚ β”œβ”€β”€ gradcam_images/ # Grad-CAM sample visualizations
197
+ β”‚ └── pneumonia-fix-vs-progressive-resizing-v2.md # Full execution log
198
+ β”‚
199
+ β”œβ”€β”€ figures/ # Generated diagrams (architecture, pipeline, strategy)
200
+ β”‚ β”œβ”€β”€ 01_architecture_concat_pooling.png
201
+ β”‚ β”œβ”€β”€ 02_training_strategy_comparison.png
202
+ β”‚ └── 03_data_pipeline.png
203
+ β”œβ”€β”€ paper/ # Conference paper (manuskrip_deep_learning.md)
204
+ β”œβ”€β”€ demo/ # Flask demo β€” Fixed Size vs Progressive comparison
205
+ β”‚ β”œβ”€β”€ app.py
206
+ β”‚ β”œβ”€β”€ model.py # .keras loader + Concat Pooling Grad-CAM
207
+ β”‚ β”œβ”€β”€ templates/index.html
208
+ β”‚ └── static/
209
+ β”‚ β”œβ”€β”€ style.css
210
+ β”‚ └── script.js
211
+ β”‚
212
+ β”œβ”€β”€ models/ # Model weights β€” NOT tracked in git
213
+ β”‚ β”œβ”€β”€ .gitkeep
214
+ β”‚ β”œβ”€β”€ README.md # Download instructions
215
+ β”‚ β”œβ”€β”€ fixed_size_model.keras ← download from GitHub Releases
216
+ β”‚ └── progressive_model.keras ← download from GitHub Releases
217
+ β”‚
218
+ β”œβ”€β”€ test_dataset/ # Small sample subset for local Grad-CAM testing
219
+ β”œβ”€β”€ scripts/ # Utility scripts
220
+ β”œβ”€β”€ archive/
221
+ β”‚ └── legacy_experiments/ # v1 pipeline results (old architecture, H5 weights)
222
+ β”‚
223
+ β”œβ”€β”€ requirements.txt
224
+ β”œβ”€β”€ CITATION.cff
225
+ └── LICENSE
226
+ ```
227
+
228
+ ---
229
+
230
+ ## Local Demo
231
+
232
+ A Flask-based web demo is included in `demo/`. It supports:
233
+ - **Single model inference** β€” select Fixed Size or Progressive Resizing
234
+ - **Compare mode** β€” run both models on the same image side-by-side with Grad-CAM
235
+
236
+ ```bash
237
+ # 1. Download the pre-trained weights (see models/README.md)
238
+ # Place both .keras files in models/
239
+
240
+ # 2. Install dependencies
241
+ pip install -r requirements.txt
242
+
243
+ # 3. Run the demo server
244
+ cd demo
245
+ python app.py
246
+ # β†’ open http://localhost:5000
247
+ ```
248
+
249
+ Upload any chest X-ray (JPEG/PNG). The interface returns:
250
+ - Predicted class with confidence scores
251
+ - Per-class probability bars
252
+ - Grad-CAM activation heatmap highlighting diagnostically relevant lung regions
253
+
254
+ ---
255
+
256
+ ## Model Weights
257
+
258
+ Trained weights are tracked via **GitHub Releases** (not in the repository β€” each ~332 MB).
259
+
260
+ | Model | File | Download |
261
+ |-------|------|----------|
262
+ | Fixed Size (384Γ—384) | `fixed_size_model.keras` | [GitHub Releases β†’](https://github.com/bennypepper/pneumonia-efficientnetb4/releases) |
263
+ | Progressive Resizing | `progressive_model.keras` | [GitHub Releases β†’](https://github.com/bennypepper/pneumonia-efficientnetb4/releases) |
264
+
265
+ Place both files in the `models/` directory at the repository root.
266
+
267
+ ---
268
+
269
+ ## Reproducing the Experiments
270
+
271
+ The full pipeline is available as 8 modular Python scripts in `kaggle_pipeline/`.
272
+ See [`kaggle_pipeline/README.md`](kaggle_pipeline/README.md) for execution instructions.
273
+
274
+ The original Kaggle notebook is available on Kaggle at:
275
+ > *(link to be added upon public Kaggle release)*
276
+
277
+ ---
278
+
279
+ ## Update History
280
+
281
+ | Version | Date | Summary |
282
+ |---------|------|---------|
283
+ | **v2.0** | May 2025 | Complete pipeline overhaul: native `tf.data`, Concat Pooling, AdamW, CLAHE+MixUp augmentation, `.keras` format, strict data isolation, dynamic class weights. |
284
+ | v1.0 | Apr 2025 | Initial release: legacy H5 models, GAP-only pooling, manual oversampling. See `archive/legacy_experiments/`. |
285
+
286
+ ---
287
+
288
+ ## Citation
289
+
290
+ ```bibtex
291
+ @inproceedings{pepper2025efficientnetb4pneumonia,
292
+ title = {Perbandingan Strategi Pelatihan EfficientNetB4 dengan dan tanpa
293
+ Progressive Resizing untuk Klasifikasi Pneumonia Bakterial dan
294
+ Viral pada Citra X-Ray Dada},
295
+ author = {Pepper, Benedict},
296
+ booktitle = {Prosiding Seminar Nasional Teknologi dan Sains Terapan},
297
+ year = {2025}
298
+ }
299
+ ```
300
+
301
+ ---
302
+
303
+ ## License
304
+
305
+ Released under the [MIT License](LICENSE).
306
+
307
+ The Kermany chest X-ray dataset is made available under
308
+ [CC BY 4.0](https://creativecommons.org/licenses/by/4.0/) β€”
309
+ please cite the original paper when using it:
310
+
311
+ > Kermany, D. S., et al. (2018). *Identifying Medical Diagnoses and Treatable Diseases
312
+ > by Image-Based Deep Learning.* Cell, 172(5), 1122–1131.
313
+ > https://doi.org/10.1016/j.cell.2018.02.010
demo/README.md ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Demo
2
+
3
+ A local web demo for the best-performing model (EfficientNetB4, Fixed Size, Experiment 02).
4
+
5
+ Upload a chest X-ray image and the server returns:
6
+ - Predicted class (Bacterial or Viral Pneumonia)
7
+ - Per-class confidence scores
8
+ - Grad-CAM activation heatmap overlaid on the input image
9
+
10
+ ## Setup
11
+
12
+ **1. Install dependencies**
13
+
14
+ ```bash
15
+ pip install -r ../requirements.txt
16
+ ```
17
+
18
+ **2. Download model weights**
19
+
20
+ The model weights are hosted on GitHub Releases. Download and place them in the correct directory:
21
+
22
+ ```bash
23
+ # Create the directory if it doesn't exist
24
+ mkdir -p ../experiments/02_efficientnetb4_v3_fixed_size/models/
25
+
26
+ # Download the pre-trained weights
27
+ curl -L -o ../experiments/02_efficientnetb4_v3_fixed_size/models/best_model_384.h5 \
28
+ https://github.com/bennypepper/pneumonia-efficientnetb4/releases/download/v1.0/best_model_384.h5
29
+ ```
30
+
31
+ **3. Run the server**
32
+
33
+ ```bash
34
+ cd demo
35
+ python app.py
36
+ ```
37
+
38
+ Then open [http://localhost:5000](http://localhost:5000) in your browser.
39
+
40
+ ## Notes
41
+
42
+ - The model loads at startup. Initial load takes 15-30 seconds.
43
+ - Inference on CPU takes approximately 3-8 seconds per image.
44
+ - The model was trained on the Kermany bacterial vs. viral subset only.
45
+ It is not calibrated for normal (healthy) X-rays.
46
+ - This demo is intended for research purposes only.
demo/app.py ADDED
@@ -0,0 +1,85 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, render_template, request, jsonify
2
+ from model import get_classifier, available_models
3
+
4
+ app = Flask(__name__)
5
+
6
+ MODEL_META = {
7
+ "fixed": {
8
+ "name": "Fixed Size",
9
+ "detail": "384Γ—384 Β· 32 epochs Β· AdamW",
10
+ "accuracy": "86.92%",
11
+ "auc": "0.9198",
12
+ "sensitivity_viral": "67.57%",
13
+ "f1_macro": "85.02%",
14
+ },
15
+ "progressive": {
16
+ "name": "Progressive Resizing",
17
+ "detail": "224β†’256β†’384 Β· 41 epochs Β· AdamW",
18
+ "accuracy": "78.46%",
19
+ "auc": "0.8011",
20
+ "sensitivity_viral": "52.70%",
21
+ "f1_macro": "74.72%",
22
+ },
23
+ }
24
+
25
+
26
+ @app.route("/")
27
+ def index():
28
+ status = available_models()
29
+ return render_template("index.html", status=status, meta=MODEL_META)
30
+
31
+
32
+ @app.route("/predict", methods=["POST"])
33
+ def predict():
34
+ model_key = request.form.get("model", "fixed")
35
+ if model_key not in ("fixed", "progressive"):
36
+ return jsonify({"error": "Invalid model key."}), 400
37
+
38
+ if "file" not in request.files or request.files["file"].filename == "":
39
+ return jsonify({"error": "No file provided."}), 400
40
+
41
+ clf = get_classifier(model_key)
42
+ if clf is None:
43
+ return jsonify({
44
+ "error": f"Model weights not found. Download {model_key}_size_model.keras and place in models/. See README."
45
+ }), 503
46
+
47
+ try:
48
+ result = clf.predict(request.files["file"].read())
49
+ result["model"] = model_key
50
+ result["model_name"] = MODEL_META[model_key]["name"]
51
+ return jsonify(result)
52
+ except Exception as e:
53
+ return jsonify({"error": str(e)}), 500
54
+
55
+
56
+ @app.route("/predict/compare", methods=["POST"])
57
+ def predict_compare():
58
+ """Run both models on the same image and return side-by-side results."""
59
+ if "file" not in request.files or request.files["file"].filename == "":
60
+ return jsonify({"error": "No file provided."}), 400
61
+
62
+ image_bytes = request.files["file"].read()
63
+ results = {}
64
+ errors = {}
65
+
66
+ for key in ("fixed", "progressive"):
67
+ clf = get_classifier(key)
68
+ if clf is None:
69
+ errors[key] = f"{key} model weights not found."
70
+ continue
71
+ try:
72
+ r = clf.predict(image_bytes)
73
+ r["model_name"] = MODEL_META[key]["name"]
74
+ results[key] = r
75
+ except Exception as e:
76
+ errors[key] = str(e)
77
+
78
+ return jsonify({"results": results, "errors": errors})
79
+
80
+
81
+ if __name__ == "__main__":
82
+ # Pre-warm available models
83
+ for key in ("fixed", "progressive"):
84
+ get_classifier(key)
85
+ app.run(debug=True, host="0.0.0.0", port=5000)
demo/model.py ADDED
@@ -0,0 +1,158 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Pneumonia classifier β€” serves both Fixed Size and Progressive Resizing models.
3
+ Supports dual-model inference and Grad-CAM for the comparison research demo.
4
+ """
5
+ import io
6
+ import base64
7
+ import cv2
8
+ import numpy as np
9
+ import tensorflow as tf
10
+ from pathlib import Path
11
+ from PIL import Image
12
+
13
+ # ---------------------------------------------------------------------------
14
+ # Paths β€” both models live in repo-root /models/ (gitignored, see README)
15
+ # ---------------------------------------------------------------------------
16
+ REPO_ROOT = Path(__file__).resolve().parent.parent
17
+ MODELS_DIR = REPO_ROOT / "models"
18
+
19
+ MODEL_PATHS = {
20
+ "fixed": MODELS_DIR / "fixed_size_model.keras",
21
+ "progressive": MODELS_DIR / "progressive_model.keras",
22
+ }
23
+
24
+ IMAGE_SIZE = (384, 384)
25
+ CLASSES = ["Bacterial Pneumonia", "Viral Pneumonia"]
26
+
27
+ # ---------------------------------------------------------------------------
28
+ # Model loader β€” lazy, cached per key
29
+ # ---------------------------------------------------------------------------
30
+ _loaded: dict[str, "PneumoniaClassifier"] = {}
31
+
32
+
33
+ def get_classifier(key: str) -> "PneumoniaClassifier | None":
34
+ if key not in MODEL_PATHS:
35
+ return None
36
+ if key not in _loaded:
37
+ path = MODEL_PATHS[key]
38
+ if path.exists():
39
+ _loaded[key] = PneumoniaClassifier(path)
40
+ else:
41
+ return None
42
+ return _loaded[key]
43
+
44
+
45
+ def available_models() -> dict[str, bool]:
46
+ return {key: MODEL_PATHS[key].exists() for key in MODEL_PATHS}
47
+
48
+
49
+ # ---------------------------------------------------------------------------
50
+ # Classifier
51
+ # ---------------------------------------------------------------------------
52
+ class PneumoniaClassifier:
53
+ """
54
+ Wraps a .keras EfficientNetB4 model (Concat Pooling architecture).
55
+
56
+ Architecture (as built in kaggle_pipeline/03_model_architecture.py):
57
+ Input(384, 384, 3)
58
+ β†’ EfficientNetB4 (layer 1) β†’ top_activation [None, H, W, 1792]
59
+ β†’ GlobalAveragePooling2D (layer 2) β†’ [None, 1792]
60
+ β†’ GlobalMaxPooling2D (layer 3) β†’ [None, 1792]
61
+ β†’ Concatenate (layer 4) β†’ [None, 3584]
62
+ β†’ Dense 512, Swish (layer 5)
63
+ β†’ BatchNormalization (layer 6)
64
+ β†’ Dropout 0.5 (layer 7)
65
+ β†’ Dense 2, Softmax fp32 (layer 8)
66
+ """
67
+
68
+ def __init__(self, model_path: Path):
69
+ print(f"[demo] Loading model from {model_path.name} …")
70
+ self.model = tf.keras.models.load_model(str(model_path), compile=False)
71
+ self._base_model = self.model.layers[1] # nested EfficientNetB4
72
+ # Sub-model: image β†’ top_activation feature maps [None, H, W, 1792]
73
+ self._conv_model = tf.keras.Model(
74
+ inputs=self._base_model.inputs,
75
+ outputs=self._base_model.get_layer("top_activation").output,
76
+ name="conv_submodel",
77
+ )
78
+ print(f"[demo] Model ready. Layers: {[l.name for l in self.model.layers]}")
79
+
80
+ # -----------------------------------------------------------------------
81
+ # Preprocessing β€” matches training pipeline (/255, no preprocess_input)
82
+ # -----------------------------------------------------------------------
83
+ def _preprocess(self, image_bytes: bytes):
84
+ image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
85
+ image = image.resize(IMAGE_SIZE, Image.LANCZOS)
86
+ arr = np.array(image, dtype=np.float32) / 255.0
87
+ return np.expand_dims(arr, axis=0), np.array(image, dtype=np.uint8)
88
+
89
+ # -----------------------------------------------------------------------
90
+ # Grad-CAM (Concat Pooling compatible)
91
+ # -----------------------------------------------------------------------
92
+ def _gradcam(self, img_array: np.ndarray) -> np.ndarray:
93
+ """
94
+ Grad-CAM for the Concat Pooling architecture.
95
+ Watches top_activation conv maps, reconstructs the head manually.
96
+ """
97
+ tensor = tf.cast(img_array, tf.float32)
98
+
99
+ with tf.GradientTape() as tape:
100
+ # 1. Get raw feature maps from EfficientNetB4
101
+ conv_maps = self._conv_model(tensor, training=False) # [1, H, W, 1792]
102
+ tape.watch(conv_maps)
103
+
104
+ # 2. Replicate Concat Pooling using the loaded model's layer weights
105
+ x_avg = self.model.layers[2](conv_maps) # GAP β†’ [1, 1792]
106
+ x_max = self.model.layers[3](conv_maps) # GMP β†’ [1, 1792]
107
+ x = self.model.layers[4]([x_avg, x_max]) # Concat β†’ [1, 3584]
108
+
109
+ # 3. Run Dense/BN/Dropout/Output head layers
110
+ for layer in self.model.layers[5:]:
111
+ x = layer(x, training=False)
112
+
113
+ # 4. Score for the predicted class
114
+ pred_class = tf.argmax(x[0])
115
+ class_score = x[:, pred_class]
116
+
117
+ grads = tape.gradient(class_score, conv_maps) # [1, H, W, 1792]
118
+ pooled_grads = tf.reduce_mean(grads, axis=(0, 1, 2)) # [1792]
119
+ weighted = conv_maps[0] @ pooled_grads[..., tf.newaxis] # [H, W, 1]
120
+ heatmap = tf.squeeze(weighted)
121
+ heatmap = tf.maximum(heatmap, 0.0)
122
+ heatmap_max = tf.math.reduce_max(heatmap)
123
+ if heatmap_max > 0:
124
+ heatmap = heatmap / heatmap_max
125
+ return heatmap.numpy()
126
+
127
+ def _overlay(self, original_rgb: np.ndarray, heatmap: np.ndarray, alpha: float = 0.40) -> str:
128
+ img_bgr = cv2.cvtColor(original_rgb, cv2.COLOR_RGB2BGR)
129
+ h_resized = cv2.resize(np.uint8(255 * heatmap), IMAGE_SIZE)
130
+ colored = cv2.applyColorMap(h_resized, cv2.COLORMAP_JET)
131
+ blended = cv2.addWeighted(img_bgr, 1 - alpha, colored, alpha, 0)
132
+ _, buf = cv2.imencode(".png", blended)
133
+ return base64.b64encode(buf).decode("utf-8")
134
+
135
+ # -----------------------------------------------------------------------
136
+ # Public predict
137
+ # -----------------------------------------------------------------------
138
+ def predict(self, image_bytes: bytes) -> dict:
139
+ img_array, original_rgb = self._preprocess(image_bytes)
140
+
141
+ # TTA: average of original + horizontal flip
142
+ flipped = img_array[:, :, ::-1, :]
143
+ probs_orig = self.model.predict(img_array, verbose=0)[0]
144
+ probs_flip = self.model.predict(flipped, verbose=0)[0]
145
+ probs = (probs_orig + probs_flip) / 2.0
146
+
147
+ pred_idx = int(np.argmax(probs))
148
+ heatmap = self._gradcam(img_array)
149
+
150
+ return {
151
+ "label": CLASSES[pred_idx],
152
+ "class_index": pred_idx,
153
+ "confidence": {
154
+ "bacterial": round(float(probs[0]) * 100, 1),
155
+ "viral": round(float(probs[1]) * 100, 1),
156
+ },
157
+ "gradcam": self._overlay(original_rgb, heatmap),
158
+ }
demo/static/script.js ADDED
@@ -0,0 +1,271 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // ─── State ───────────────────────────────────────────────────────────────────
2
+ let selectedFile = null;
3
+ let currentMode = "single"; // "single" | "compare"
4
+ let selectedModel = "fixed"; // "fixed" | "progressive"
5
+ let timerInterval = null;
6
+ let elapsedSeconds = 0;
7
+
8
+ // ─── DOM Refs ────────────────────────────────────────────────────────────────
9
+ const dropZone = document.getElementById("drop-zone");
10
+ const dropContent = document.getElementById("drop-content");
11
+ const dropError = document.getElementById("drop-error");
12
+ const fileInput = document.getElementById("file-input");
13
+ const browseBtn = document.getElementById("browse-btn");
14
+ const preview = document.getElementById("preview");
15
+ const predictBtn = document.getElementById("predict-btn");
16
+ const resetBtn = document.getElementById("reset-btn");
17
+ const singleTimer = document.getElementById("single-timer");
18
+ const compareTimer = document.getElementById("compare-timer");
19
+
20
+ // Single-model results
21
+ const resultsSingle = document.getElementById("results-single");
22
+ const resultsPlaceholder = document.getElementById("results-placeholder");
23
+ const resultsContent = document.getElementById("results-content");
24
+ const loadingEl = document.getElementById("loading");
25
+ const errorBox = document.getElementById("error-box");
26
+ const modelBadgeResult = document.getElementById("model-badge-result");
27
+ const predictionLabel = document.getElementById("prediction-label");
28
+ const barBacterial = document.getElementById("bar-bacterial");
29
+ const barViral = document.getElementById("bar-viral");
30
+ const pctBacterial = document.getElementById("pct-bacterial");
31
+ const pctViral = document.getElementById("pct-viral");
32
+ const imgOriginal = document.getElementById("img-original");
33
+ const imgGradcam = document.getElementById("img-gradcam");
34
+
35
+ // Compare results
36
+ const resultsCompare = document.getElementById("results-compare");
37
+ const compareLoading = document.getElementById("compare-loading");
38
+ const compareError = document.getElementById("compare-error");
39
+ const compareCards = document.getElementById("compare-cards");
40
+ const compareXrayRow = document.getElementById("compare-xray-row");
41
+ const compareImgOriginal = document.getElementById("compare-img-original");
42
+ const compareDisclaimer = document.getElementById("compare-disclaimer");
43
+
44
+ // Model selector cards
45
+ const modelCardEls = document.querySelectorAll(".model-card");
46
+ const singleSelector = document.getElementById("single-selector");
47
+ const compareLabel = document.getElementById("compare-label");
48
+
49
+ // Mode toggle buttons
50
+ document.getElementById("btn-single").addEventListener("click", () => setMode("single"));
51
+ document.getElementById("btn-compare").addEventListener("click", () => setMode("compare"));
52
+
53
+ // ─── Mode Switching ──────────────────────────────────────────────────────────
54
+ function setMode(mode) {
55
+ currentMode = mode;
56
+
57
+ document.getElementById("btn-single").classList.toggle("active", mode === "single");
58
+ document.getElementById("btn-compare").classList.toggle("active", mode === "compare");
59
+
60
+ singleSelector.hidden = mode === "compare";
61
+ compareLabel.hidden = mode === "single";
62
+
63
+ resultsSingle.hidden = mode === "compare";
64
+ resultsCompare.hidden = mode === "single";
65
+
66
+ predictBtn.style.opacity = "0";
67
+ setTimeout(() => {
68
+ predictBtn.textContent = mode === "compare" ? "Compare Both Models" : "Run Inference";
69
+ predictBtn.style.opacity = "1";
70
+ }, 200);
71
+ }
72
+
73
+ // ─── Model Card Selection ────────────────────────────────────────────────────
74
+ modelCardEls.forEach(card => {
75
+ card.addEventListener("click", () => {
76
+ if (card.classList.contains("unavailable")) return;
77
+ const radio = card.querySelector("input[type=radio]");
78
+ if (!radio) return;
79
+ radio.checked = true;
80
+ selectedModel = card.dataset.model;
81
+ modelCardEls.forEach(c => c.classList.remove("selected"));
82
+ card.classList.add("selected");
83
+ });
84
+ });
85
+
86
+ // ─── File Handling ────────────────────────────────────────────────────────────
87
+ function showPreview(file) {
88
+ if (!["image/jpeg", "image/png"].includes(file.type)) {
89
+ dropError.hidden = false;
90
+ return;
91
+ }
92
+ dropError.hidden = true;
93
+ selectedFile = file;
94
+ const url = URL.createObjectURL(file);
95
+ preview.src = url;
96
+ preview.hidden = false;
97
+ dropContent.hidden = true;
98
+ predictBtn.disabled = false;
99
+
100
+ predictBtn.hidden = false;
101
+ resetBtn.hidden = true;
102
+ setSingleState("idle");
103
+ setCompareState("idle");
104
+ }
105
+
106
+ browseBtn.addEventListener("click", () => fileInput.click());
107
+ dropZone.addEventListener("click", e => { if (e.target !== browseBtn) fileInput.click(); });
108
+ fileInput.addEventListener("change", () => { if (fileInput.files.length > 0) showPreview(fileInput.files[0]); });
109
+
110
+ dropZone.addEventListener("dragover", e => { e.preventDefault(); dropZone.classList.add("dragover"); });
111
+ dropZone.addEventListener("dragleave", () => dropZone.classList.remove("dragover"));
112
+ dropZone.addEventListener("drop", e => {
113
+ e.preventDefault();
114
+ dropZone.classList.remove("dragover");
115
+ const file = e.dataTransfer.files[0];
116
+ if (file) showPreview(file);
117
+ });
118
+
119
+ // Reset flow
120
+ resetBtn.addEventListener("click", () => {
121
+ selectedFile = null;
122
+ preview.src = "";
123
+ preview.hidden = true;
124
+ dropContent.hidden = false;
125
+ predictBtn.disabled = true;
126
+ predictBtn.hidden = false;
127
+ resetBtn.hidden = true;
128
+ fileInput.value = "";
129
+ setSingleState("idle");
130
+ setCompareState("idle");
131
+ });
132
+
133
+ function startTimer(el) {
134
+ clearInterval(timerInterval);
135
+ elapsedSeconds = 0;
136
+ el.textContent = `Running inference Β· ${elapsedSeconds}s`;
137
+ timerInterval = setInterval(() => {
138
+ elapsedSeconds++;
139
+ el.textContent = `Running inference Β· ${elapsedSeconds}s`;
140
+ }, 1000);
141
+ }
142
+ function stopTimer() { clearInterval(timerInterval); }
143
+
144
+ // ─── Single-model Results ────────────────────────────────────────────────────
145
+ function setSingleState(state) {
146
+ resultsPlaceholder.hidden = true;
147
+ resultsContent.hidden = true;
148
+ loadingEl.hidden = true;
149
+ errorBox.hidden = true;
150
+ stopTimer();
151
+ if (state === "loading") { loadingEl.hidden = false; startTimer(singleTimer); }
152
+ if (state === "results") resultsContent.hidden = false;
153
+ if (state === "error") errorBox.hidden = false;
154
+ if (state === "idle") resultsPlaceholder.hidden = false;
155
+ }
156
+
157
+ function renderSingle(data) {
158
+ const isBacterial = data.class_index === 0;
159
+ modelBadgeResult.textContent = data.model_name || "";
160
+ predictionLabel.textContent = data.label;
161
+ predictionLabel.className = isBacterial ? "bacterial" : "viral";
162
+
163
+ pctBacterial.textContent = `${data.confidence.bacterial}%`;
164
+ pctViral.textContent = `${data.confidence.viral}%`;
165
+
166
+ requestAnimationFrame(() => {
167
+ barBacterial.style.width = `${data.confidence.bacterial}%`;
168
+ barViral.style.width = `${data.confidence.viral}%`;
169
+ });
170
+
171
+ imgOriginal.src = URL.createObjectURL(selectedFile);
172
+ imgGradcam.src = `data:image/png;base64,${data.gradcam}`;
173
+ setSingleState("results");
174
+ }
175
+
176
+ // ─── Compare Results ─────────────────────────────────────────────────────────
177
+ function setCompareState(state) {
178
+ compareLoading.hidden = state !== "loading";
179
+ compareError.hidden = state !== "error";
180
+ compareCards.hidden = state !== "results";
181
+ compareXrayRow.hidden = state !== "results";
182
+ compareDisclaimer.hidden = state !== "results";
183
+ stopTimer();
184
+ if (state === "loading") startTimer(compareTimer);
185
+ }
186
+
187
+ function buildCompareBar(label, pct, colorClass) {
188
+ return `
189
+ <div class="compare-bar-row">
190
+ <span class="bar-label" style="font-size:12px;color:var(--muted)">${label}</span>
191
+ <div class="bar-track">
192
+ <div class="bar" id="cbar-${colorClass}-${Date.now()}"
193
+ style="width:${pct}%;background:${colorClass==='bacterial'
194
+ ? 'linear-gradient(90deg,#f87171,#fb923c)'
195
+ : 'linear-gradient(90deg,#60a5fa,#818cf8)'}"></div>
196
+ </div>
197
+ <span class="bar-value" style="font-size:12px">${pct}%</span>
198
+ </div>`;
199
+ }
200
+
201
+ function renderCompare(data) {
202
+ const { results, errors } = data;
203
+ const keys = ["fixed", "progressive"];
204
+
205
+ compareCards.innerHTML = keys.map(key => {
206
+ if (!results[key]) {
207
+ return `<div class="compare-card">
208
+ <div class="compare-model-name">${key === 'fixed' ? 'Fixed Size' : 'Progressive Resizing'}</div>
209
+ <div style="color:var(--muted);font-size:13px">${errors[key] || 'Model unavailable'}</div>
210
+ </div>`;
211
+ }
212
+ const r = results[key];
213
+ const isBacterial = r.class_index === 0;
214
+ return `
215
+ <div class="compare-card">
216
+ <div class="compare-model-name">
217
+ ${r.model_name}
218
+ </div>
219
+ <div class="compare-verdict ${isBacterial ? 'bacterial' : 'viral'}">${r.label}</div>
220
+ <div class="compare-conf">
221
+ ${buildCompareBar('Bacterial', r.confidence.bacterial, 'bacterial')}
222
+ ${buildCompareBar('Viral', r.confidence.viral, 'viral')}
223
+ </div>
224
+ <figure class="compare-gradcam">
225
+ <img src="data:image/png;base64,${r.gradcam}" alt="Grad-CAM">
226
+ <figcaption>Grad-CAM Activation Map</figcaption>
227
+ </figure>
228
+ </div>`;
229
+ }).join("");
230
+
231
+ compareImgOriginal.src = URL.createObjectURL(selectedFile);
232
+ setCompareState("results");
233
+ }
234
+
235
+ // ─── Inference Entry Point ────────────────────────────────────────────────────
236
+ async function runInference() {
237
+ if (!selectedFile) return;
238
+ predictBtn.disabled = true;
239
+ predictBtn.hidden = true;
240
+ resetBtn.hidden = false;
241
+
242
+ const formData = new FormData();
243
+ formData.append("file", selectedFile);
244
+
245
+ if (currentMode === "single") {
246
+ setSingleState("loading");
247
+ formData.append("model", selectedModel);
248
+ try {
249
+ const res = await fetch("/predict", { method: "POST", body: formData });
250
+ const data = await res.json();
251
+ if (!res.ok) throw new Error(data.error || `Server error (${res.status})`);
252
+ renderSingle(data);
253
+ } catch (err) {
254
+ errorBox.textContent = "The server couldn't process this image. Make sure it's a chest X-ray in JPEG or PNG format. Details: " + err.message;
255
+ setSingleState("error");
256
+ }
257
+ } else {
258
+ setCompareState("loading");
259
+ try {
260
+ const res = await fetch("/predict/compare", { method: "POST", body: formData });
261
+ const data = await res.json();
262
+ if (!res.ok) throw new Error(data.error || `Server error (${res.status})`);
263
+ renderCompare(data);
264
+ } catch (err) {
265
+ compareError.textContent = "The server couldn't process this image. Make sure it's a chest X-ray in JPEG or PNG format. Details: " + err.message;
266
+ setCompareState("error");
267
+ }
268
+ }
269
+ }
270
+
271
+ predictBtn.addEventListener("click", runInference);
demo/static/style.css ADDED
@@ -0,0 +1,618 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* ============================================================
2
+ Design tokens
3
+ ============================================================ */
4
+ *, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
5
+
6
+ :root {
7
+ --bg: #090d13;
8
+ --surface: #0f1623;
9
+ --surface-2: #161e2e;
10
+ --surface-3: #1c2638;
11
+ --border: #232f45;
12
+ --border-soft: #1a2438;
13
+ --text: #e2e8f4;
14
+ --muted: #627394;
15
+ --accent: #4f9cf9;
16
+ --accent-glow: rgba(79, 156, 249, 0.18);
17
+ --green: #34d399;
18
+ --bacterial: #f87171;
19
+ --viral: #60a5fa;
20
+ --warn: #fbbf24;
21
+ --radius: 10px;
22
+ --radius-sm: 6px;
23
+ --font: 'Inter', system-ui, sans-serif;
24
+ --transition: 0.18s ease;
25
+ }
26
+
27
+ *:focus-visible {
28
+ outline: 2px solid var(--accent);
29
+ outline-offset: 3px;
30
+ }
31
+
32
+ [hidden] { display: none !important; }
33
+
34
+ html, body { height: 100%; }
35
+
36
+ body {
37
+ background: var(--bg);
38
+ color: var(--text);
39
+ font-family: var(--font);
40
+ font-size: 14px;
41
+ line-height: 1.65;
42
+ display: flex;
43
+ flex-direction: column;
44
+ min-height: 100vh;
45
+ }
46
+
47
+ /* ============================================================
48
+ Layout helpers
49
+ ============================================================ */
50
+ .container {
51
+ width: 100%;
52
+ max-width: 1140px;
53
+ margin: 0 auto;
54
+ padding: 0 28px;
55
+ }
56
+
57
+ /* ============================================================
58
+ Header
59
+ ============================================================ */
60
+ header {
61
+ border-bottom: 1px solid var(--border);
62
+ padding: 18px 0;
63
+ background: rgba(9, 13, 19, 0.92);
64
+ backdrop-filter: blur(12px);
65
+ position: sticky;
66
+ top: 0;
67
+ z-index: 50;
68
+ }
69
+
70
+ .header-inner {
71
+ display: flex;
72
+ align-items: center;
73
+ justify-content: space-between;
74
+ gap: 16px;
75
+ }
76
+
77
+ header h1 {
78
+ font-size: 15px;
79
+ font-weight: 600;
80
+ letter-spacing: -0.01em;
81
+ background: linear-gradient(90deg, #e2e8f4 60%, var(--accent));
82
+ -webkit-background-clip: text;
83
+ -webkit-text-fill-color: transparent;
84
+ }
85
+
86
+ .header-sub {
87
+ font-size: 12px;
88
+ color: var(--muted);
89
+ margin-top: 1px;
90
+ }
91
+
92
+ .header-badges { display: flex; gap: 8px; flex-wrap: wrap; }
93
+
94
+ /* ============================================================
95
+ Badges
96
+ ============================================================ */
97
+ .badge {
98
+ font-size: 11px;
99
+ font-weight: 500;
100
+ padding: 3px 9px;
101
+ border-radius: 20px;
102
+ white-space: nowrap;
103
+ letter-spacing: 0.02em;
104
+ }
105
+ .badge-ready { background: rgba(52,211,153,.12); color: var(--green); border: 1px solid rgba(52,211,153,.3); }
106
+ .badge-missing { background: rgba(248,113,113,.12); color: var(--bacterial); border: 1px solid rgba(248,113,113,.3); }
107
+ .badge-arch { background: rgba(79,156,249,.10); color: var(--accent); border: 1px solid rgba(79,156,249,.25); }
108
+ .badge-tf { background: rgba(251,191,36,.08); color: var(--warn); border: 1px solid rgba(251,191,36,.2); }
109
+ .badge-research { background: rgba(99,102,241,.10); color: #a5b4fc; border: 1px solid rgba(99,102,241,.25); }
110
+
111
+ /* ============================================================
112
+ Main
113
+ ============================================================ */
114
+ main {
115
+ flex: 1;
116
+ padding: 36px 28px;
117
+ display: flex;
118
+ flex-direction: column;
119
+ gap: 32px;
120
+ }
121
+
122
+ /* ============================================================
123
+ Model Selector Section
124
+ ============================================================ */
125
+ .model-selector-section {
126
+ display: flex;
127
+ flex-direction: column;
128
+ gap: 16px;
129
+ }
130
+
131
+ .mode-toggle-wrap {
132
+ display: flex;
133
+ background: var(--surface);
134
+ border: 1px solid var(--border);
135
+ border-radius: var(--radius-sm);
136
+ padding: 4px;
137
+ width: fit-content;
138
+ }
139
+
140
+ .mode-btn {
141
+ background: none;
142
+ border: none;
143
+ color: var(--muted);
144
+ font-family: var(--font);
145
+ font-size: 13px;
146
+ font-weight: 500;
147
+ padding: 7px 20px;
148
+ border-radius: 4px;
149
+ cursor: pointer;
150
+ transition: all var(--transition);
151
+ }
152
+
153
+ .mode-btn.active {
154
+ background: var(--surface-3);
155
+ color: var(--text);
156
+ box-shadow: 0 1px 3px rgba(0,0,0,.4);
157
+ }
158
+
159
+ .model-cards {
160
+ display: grid;
161
+ grid-template-columns: 1fr 1fr;
162
+ gap: 12px;
163
+ }
164
+
165
+ @media (max-width: 640px) {
166
+ .model-cards { grid-template-columns: 1fr; }
167
+ }
168
+
169
+ .model-card {
170
+ background: var(--surface);
171
+ border: 1.5px solid var(--border);
172
+ border-radius: var(--radius);
173
+ padding: 18px 20px;
174
+ cursor: pointer;
175
+ transition: border-color var(--transition), box-shadow var(--transition), background var(--transition);
176
+ display: block;
177
+ }
178
+
179
+ .model-card:hover:not(.unavailable) {
180
+ border-color: rgba(79,156,249,.45);
181
+ background: var(--surface-2);
182
+ }
183
+
184
+ .model-card.selected {
185
+ border-color: var(--accent);
186
+ background: var(--surface-2);
187
+ box-shadow: 0 0 0 3px var(--accent-glow);
188
+ }
189
+
190
+ .model-card.unavailable { opacity: 0.55; cursor: not-allowed; }
191
+
192
+ .model-card-header {
193
+ display: flex;
194
+ align-items: center;
195
+ justify-content: space-between;
196
+ margin-bottom: 4px;
197
+ }
198
+
199
+ .model-card-name {
200
+ font-size: 14px;
201
+ font-weight: 600;
202
+ color: var(--text);
203
+ }
204
+
205
+ .model-card-detail {
206
+ font-size: 12px;
207
+ color: var(--muted);
208
+ margin-bottom: 14px;
209
+ }
210
+
211
+ .model-stats-row {
212
+ display: grid;
213
+ grid-template-columns: repeat(4, 1fr);
214
+ gap: 8px;
215
+ }
216
+
217
+ .stat {
218
+ display: flex;
219
+ flex-direction: column;
220
+ align-items: center;
221
+ background: var(--surface-3);
222
+ border-radius: var(--radius-sm);
223
+ padding: 8px 4px;
224
+ }
225
+
226
+ .stat-val {
227
+ font-size: 15px;
228
+ font-weight: 700;
229
+ color: var(--accent);
230
+ letter-spacing: -0.02em;
231
+ font-variant-numeric: tabular-nums;
232
+ }
233
+
234
+ .model-card.selected .stat-val { color: var(--green); }
235
+
236
+ .stat-lbl {
237
+ font-size: 10px;
238
+ color: var(--muted);
239
+ text-align: center;
240
+ margin-top: 2px;
241
+ }
242
+
243
+ .compare-hint {
244
+ font-size: 13px;
245
+ color: var(--muted);
246
+ padding: 10px 14px;
247
+ background: var(--surface-2);
248
+ border: 1px solid var(--border);
249
+ border-radius: var(--radius-sm);
250
+ }
251
+
252
+ .compare-hint .warn { color: var(--warn); margin-left: 6px; }
253
+
254
+ /* ============================================================
255
+ Workspace (upload + results)
256
+ ============================================================ */
257
+ .workspace {
258
+ display: grid;
259
+ grid-template-columns: 380px 1fr;
260
+ gap: 20px;
261
+ align-items: start;
262
+ }
263
+
264
+ @media (max-width: 820px) { .workspace { grid-template-columns: 1fr; } }
265
+
266
+ /* ============================================================
267
+ Cards
268
+ ============================================================ */
269
+ .card {
270
+ background: var(--surface);
271
+ border: 1px solid var(--border);
272
+ border-radius: var(--radius);
273
+ padding: 24px;
274
+ }
275
+
276
+ .card-label {
277
+ font-size: 11px;
278
+ font-weight: 500;
279
+ color: var(--muted);
280
+ text-transform: uppercase;
281
+ letter-spacing: 0.08em;
282
+ margin-bottom: 18px;
283
+ }
284
+
285
+ /* ============================================================
286
+ Drop Zone
287
+ ============================================================ */
288
+ .drop-zone {
289
+ border: 1.5px dashed var(--border);
290
+ border-radius: var(--radius-sm);
291
+ height: 240px;
292
+ cursor: pointer;
293
+ transition: border-color var(--transition), background var(--transition);
294
+ position: relative;
295
+ overflow: hidden;
296
+ display: flex;
297
+ align-items: center;
298
+ justify-content: center;
299
+ }
300
+
301
+ .drop-zone:hover, .drop-zone.dragover {
302
+ border-color: var(--accent);
303
+ background: var(--accent-glow);
304
+ }
305
+
306
+ #drop-content {
307
+ display: flex;
308
+ flex-direction: column;
309
+ align-items: center;
310
+ gap: 8px;
311
+ color: var(--muted);
312
+ text-align: center;
313
+ padding: 24px;
314
+ pointer-events: none;
315
+ position: relative;
316
+ z-index: 1;
317
+ }
318
+
319
+ #drop-content svg { color: var(--border); }
320
+ #drop-content p { font-size: 14px; color: var(--text); }
321
+ #drop-content span { font-size: 13px; }
322
+ #drop-content small { font-size: 12px; }
323
+
324
+ #browse-btn {
325
+ background: transparent;
326
+ border: 1px solid var(--accent);
327
+ color: var(--accent);
328
+ padding: 6px 14px;
329
+ border-radius: var(--radius-sm);
330
+ font-size: 13px;
331
+ font-weight: 500;
332
+ cursor: pointer;
333
+ transition: all var(--transition);
334
+ margin-top: 4px;
335
+ }
336
+ #browse-btn:hover { background: var(--accent-glow); }
337
+
338
+ #preview {
339
+ position: absolute;
340
+ inset: 0;
341
+ width: 100%;
342
+ height: 100%;
343
+ object-fit: contain;
344
+ padding: 10px;
345
+ }
346
+
347
+ /* ============================================================
348
+ Predict Button
349
+ ============================================================ */
350
+ #predict-btn {
351
+ width: 100%;
352
+ margin-top: 14px;
353
+ padding: 11px;
354
+ background: linear-gradient(135deg, var(--accent), #6366f1);
355
+ color: #fff;
356
+ border: none;
357
+ border-radius: var(--radius-sm);
358
+ font-family: var(--font);
359
+ font-size: 14px;
360
+ font-weight: 600;
361
+ cursor: pointer;
362
+ transition: opacity var(--transition), transform var(--transition);
363
+ letter-spacing: 0.01em;
364
+ }
365
+ #predict-btn:hover:not(:disabled) { opacity: 0.88; transform: translateY(-1px); }
366
+ #predict-btn:active:not(:disabled) { transform: translateY(0); }
367
+ #predict-btn:disabled { opacity: 0.3; cursor: not-allowed; }
368
+
369
+ #reset-btn {
370
+ background: transparent;
371
+ border: 1px solid var(--border);
372
+ color: var(--text);
373
+ width: 100%;
374
+ margin-top: 10px;
375
+ padding: 10px;
376
+ border-radius: var(--radius-sm);
377
+ font-family: var(--font);
378
+ font-size: 14px;
379
+ font-weight: 500;
380
+ cursor: pointer;
381
+ transition: all var(--transition);
382
+ }
383
+ #reset-btn:hover { background: var(--surface-2); border-color: var(--muted); }
384
+
385
+ /* ============================================================
386
+ Single Results
387
+ ============================================================ */
388
+ #results-placeholder {
389
+ display: flex;
390
+ align-items: center;
391
+ justify-content: center;
392
+ min-height: 220px;
393
+ }
394
+
395
+ .muted { color: var(--muted); font-size: 13px; }
396
+
397
+ #model-badge-result {
398
+ font-size: 11px;
399
+ font-weight: 500;
400
+ color: var(--accent);
401
+ text-transform: uppercase;
402
+ letter-spacing: 0.08em;
403
+ margin-bottom: 8px;
404
+ }
405
+
406
+ #prediction-label {
407
+ font-size: 24px;
408
+ font-weight: 700;
409
+ letter-spacing: -0.03em;
410
+ margin-bottom: 20px;
411
+ padding-bottom: 16px;
412
+ border-bottom: 1px solid var(--border);
413
+ }
414
+ #prediction-label.bacterial { color: var(--bacterial); }
415
+ #prediction-label.viral { color: var(--viral); }
416
+
417
+ .confidence-section { display: flex; flex-direction: column; gap: 10px; margin-bottom: 22px; }
418
+
419
+ .bar-row {
420
+ display: grid;
421
+ grid-template-columns: 72px 1fr 46px;
422
+ align-items: center;
423
+ gap: 10px;
424
+ }
425
+ .bar-label { font-size: 13px; color: var(--muted); }
426
+ .bar-track { height: 6px; background: var(--surface-3); border-radius: 3px; position: relative; }
427
+ .bar { height: 100%; border-radius: 3px; width: 0%; transition: width 0.55s cubic-bezier(.4,0,.2,1); position: absolute; left: 0; top: 0; }
428
+ .bar-marker-50 { position: absolute; left: 50%; top: -2px; bottom: -2px; width: 2px; background: var(--border); z-index: 2; }
429
+ .bar-label-50 { position: absolute; left: 50%; top: 8px; transform: translateX(-50%); font-size: 10px; color: var(--muted); }
430
+ #bar-bacterial { background: linear-gradient(90deg, #f87171, #fb923c); }
431
+ #bar-viral { background: linear-gradient(90deg, var(--viral), #818cf8); }
432
+ .bar-value { font-size: 13px; font-weight: 600; text-align: right; font-variant-numeric: tabular-nums; }
433
+
434
+ .image-pair {
435
+ display: grid;
436
+ grid-template-columns: 1fr 1fr;
437
+ gap: 12px;
438
+ margin-bottom: 16px;
439
+ }
440
+ .image-pair figure { display: flex; flex-direction: column; gap: 6px; }
441
+ .image-pair img { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); display: block; }
442
+ .image-pair figcaption { font-size: 11px; color: var(--muted); text-align: center; }
443
+
444
+ @media (max-width: 640px) {
445
+ .image-pair { grid-template-columns: 1fr; }
446
+ .image-pair figure:first-child { display: none; }
447
+ }
448
+
449
+ /* ============================================================
450
+ Compare Mode
451
+ ============================================================ */
452
+ #results-compare { display: flex; flex-direction: column; gap: 20px; }
453
+
454
+ .section-heading {
455
+ font-size: 13px;
456
+ font-weight: 500;
457
+ color: var(--muted);
458
+ text-transform: uppercase;
459
+ letter-spacing: 0.08em;
460
+ }
461
+
462
+ .compare-grid {
463
+ display: grid;
464
+ grid-template-columns: 1fr 1fr;
465
+ gap: 16px;
466
+ }
467
+ @media (max-width: 640px) {
468
+ .compare-grid { grid-template-columns: 1fr; }
469
+ .compare-xray-row figure { max-width: 100%; }
470
+ }
471
+
472
+ .compare-card {
473
+ background: var(--surface);
474
+ border: 1px solid var(--border);
475
+ border-radius: var(--radius);
476
+ padding: 20px;
477
+ display: flex;
478
+ flex-direction: column;
479
+ gap: 14px;
480
+ }
481
+
482
+ .compare-card.winner { border-color: var(--green); box-shadow: 0 0 0 2px rgba(52,211,153,.15); }
483
+
484
+ .compare-model-name {
485
+ font-size: 13px;
486
+ font-weight: 600;
487
+ color: var(--text);
488
+ display: flex;
489
+ align-items: center;
490
+ gap: 8px;
491
+ }
492
+
493
+ .winner-tag {
494
+ font-size: 10px;
495
+ font-weight: 600;
496
+ background: rgba(52,211,153,.15);
497
+ color: var(--green);
498
+ border: 1px solid rgba(52,211,153,.3);
499
+ padding: 2px 7px;
500
+ border-radius: 10px;
501
+ }
502
+
503
+ .compare-verdict {
504
+ font-size: 18px;
505
+ font-weight: 700;
506
+ letter-spacing: -0.02em;
507
+ }
508
+ .compare-verdict.bacterial { color: var(--bacterial); }
509
+ .compare-verdict.viral { color: var(--viral); }
510
+
511
+ .compare-conf { display: flex; flex-direction: column; gap: 7px; }
512
+
513
+ .compare-bar-row {
514
+ display: grid;
515
+ grid-template-columns: 64px 1fr 42px;
516
+ align-items: center;
517
+ gap: 8px;
518
+ }
519
+
520
+ .compare-gradcam img { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); }
521
+ .compare-gradcam figcaption { font-size: 11px; color: var(--muted); margin-top: 5px; text-align: center; }
522
+
523
+ .compare-xray-row {
524
+ display: flex;
525
+ justify-content: center;
526
+ }
527
+ .compare-xray-row figure { max-width: 240px; display: flex; flex-direction: column; gap: 6px; }
528
+ .compare-xray-row img { width: 100%; border-radius: var(--radius-sm); border: 1px solid var(--border); }
529
+ .compare-xray-row figcaption { font-size: 11px; color: var(--muted); text-align: center; }
530
+
531
+ /* ============================================================
532
+ Loading / Error
533
+ ============================================================ */
534
+ #loading, #compare-loading {
535
+ display: flex;
536
+ flex-direction: column;
537
+ justify-content: center;
538
+ min-height: 200px;
539
+ }
540
+
541
+ .skeleton-container {
542
+ display: flex;
543
+ flex-direction: column;
544
+ gap: 16px;
545
+ width: 100%;
546
+ }
547
+ .skeleton-label { height: 32px; width: 60%; background: var(--surface-3); border-radius: var(--radius-sm); animation: pulse 1.5s infinite; }
548
+ .skeleton-bar { height: 6px; width: 100%; background: var(--surface-3); border-radius: 3px; animation: pulse 1.5s infinite; }
549
+ .skeleton-images { display: grid; grid-template-columns: 1fr 1fr; gap: 12px; }
550
+ .skeleton-img { height: 180px; background: var(--surface-3); border-radius: var(--radius-sm); animation: pulse 1.5s infinite; }
551
+ @keyframes pulse {
552
+ 0% { opacity: 0.6; }
553
+ 50% { opacity: 1; }
554
+ 100% { opacity: 0.6; }
555
+ }
556
+ .timer-text { font-variant-numeric: tabular-nums; text-align: center; margin-top: 8px; }
557
+
558
+ .spinner {
559
+ width: 26px;
560
+ height: 26px;
561
+ border: 2px solid var(--border);
562
+ border-top-color: var(--accent);
563
+ border-radius: 50%;
564
+ animation: spin 0.65s linear infinite;
565
+ }
566
+ @keyframes spin { to { transform: rotate(360deg); } }
567
+
568
+ #error-box, #compare-error {
569
+ background: rgba(248,113,113,.08);
570
+ border: 1px solid rgba(248,113,113,.25);
571
+ border-radius: var(--radius-sm);
572
+ padding: 13px 16px;
573
+ font-size: 13px;
574
+ color: var(--bacterial);
575
+ }
576
+
577
+ /* ============================================================
578
+ Disclaimer
579
+ ============================================================ */
580
+ .disclaimer {
581
+ font-size: 12px;
582
+ color: var(--muted);
583
+ padding-top: 12px;
584
+ border-top: 1px solid var(--border-soft);
585
+ margin-top: 4px;
586
+ }
587
+
588
+ /* ============================================================
589
+ Footer
590
+ ============================================================ */
591
+ footer {
592
+ border-top: 1px solid var(--border);
593
+ background: linear-gradient(to bottom, transparent, var(--surface));
594
+ padding: 28px 0;
595
+ margin-top: auto;
596
+ }
597
+
598
+ .footer-inner {
599
+ display: grid;
600
+ grid-template-columns: 1fr 1fr;
601
+ gap: 32px;
602
+ }
603
+ @media (max-width: 720px) { .footer-inner { grid-template-columns: 1fr; } }
604
+
605
+ .footer-heading {
606
+ font-size: 11px;
607
+ font-weight: 500;
608
+ color: var(--muted);
609
+ text-transform: uppercase;
610
+ letter-spacing: 0.08em;
611
+ margin-bottom: 12px;
612
+ }
613
+
614
+ .specs { width: 100%; border-collapse: collapse; font-size: 12.5px; }
615
+ .specs td { padding: 6px 10px; border-bottom: 1px solid var(--border-soft); }
616
+ .specs td:first-child { color: var(--muted); width: 120px; }
617
+ .specs td:last-child { color: var(--text); }
618
+ .specs tr:last-child td { border-bottom: none; }
demo/templates/index.html ADDED
@@ -0,0 +1,221 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="UTF-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
+ <meta name="description" content="Interactive research demo comparing Fixed Size vs Progressive Resizing training strategies for EfficientNetB4 pneumonia classification from chest X-ray images.">
7
+ <title>Pneumonia Classification β€” Fixed Size vs Progressive Resizing</title>
8
+ <link rel="preconnect" href="https://fonts.googleapis.com">
9
+ <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Inter:ital,wght@0,300;0,400;0,500;0,600;0,700;1,400&display=swap">
10
+ <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
11
+ </head>
12
+ <body>
13
+
14
+ <header>
15
+ <div class="container header-inner">
16
+ <div>
17
+ <h1>Pneumonia X-Ray Classifier</h1>
18
+ <p class="header-sub">EfficientNetB4 Β· Bacterial vs. Viral Β· Research Demo</p>
19
+ </div>
20
+ <div class="header-badges">
21
+ <span class="badge badge-arch">Concat Pooling</span>
22
+ <span class="badge badge-tf">TF 2.19</span>
23
+ <span class="badge badge-research">Research Only</span>
24
+ </div>
25
+ </div>
26
+ </header>
27
+
28
+ <main class="container">
29
+
30
+ <!-- Model Selector -->
31
+ <section class="model-selector-section">
32
+ <div class="mode-toggle-wrap">
33
+ <button class="mode-btn active" id="btn-single" data-mode="single">Single Model</button>
34
+ <button class="mode-btn" id="btn-compare" data-mode="compare">Compare Both</button>
35
+ </div>
36
+
37
+ <div id="single-selector" class="model-cards">
38
+ {% for key, m in meta.items() %}
39
+ <label class="model-card {% if key == 'fixed' %}selected{% endif %} {% if not status[key] %}unavailable{% endif %}"
40
+ data-model="{{ key }}" id="card-{{ key }}">
41
+ <input type="radio" name="model" value="{{ key }}" {% if key == 'fixed' %}checked{% endif %}
42
+ {% if not status[key] %}disabled{% endif %} hidden>
43
+ <div class="model-card-header">
44
+ <span class="model-card-name">{{ m.name }}</span>
45
+ {% if not status[key] %}
46
+ <span class="badge badge-missing">Weights Missing</span>
47
+ {% else %}
48
+ <span class="badge badge-ready">Ready</span>
49
+ {% endif %}
50
+ </div>
51
+ <p class="model-card-detail">{{ m.detail }}</p>
52
+ <div class="model-stats-row">
53
+ <div class="stat" title="Accuracy: % of correctly classified test images out of 390 total."><span class="stat-val">{{ m.accuracy }}</span><span class="stat-lbl">Accuracy β„Ή</span></div>
54
+ <div class="stat" title="ROC AUC: Area under the receiver operating characteristic curve."><span class="stat-val">{{ m.auc }}</span><span class="stat-lbl">ROC AUC β„Ή</span></div>
55
+ <div class="stat" title="Viral Recall: % of actual viral pneumonia correctly identified."><span class="stat-val">{{ m.sensitivity_viral }}</span><span class="stat-lbl">Viral Recall β„Ή</span></div>
56
+ <div class="stat" title="Macro F1: Harmonic mean of precision and recall across classes."><span class="stat-val">{{ m.f1_macro }}</span><span class="stat-lbl">Macro F1 β„Ή</span></div>
57
+ </div>
58
+ </label>
59
+ {% endfor %}
60
+ </div>
61
+
62
+ <p id="compare-label" class="compare-hint" hidden>
63
+ Both models will run on your image β€” results shown side by side.
64
+ {% if not status['fixed'] or not status['progressive'] %}
65
+ <span class="warn">⚠ One or more model weights are missing β€” comparison may be partial.</span>
66
+ {% endif %}
67
+ </p>
68
+ </section>
69
+
70
+ <!-- Upload + Inference -->
71
+ <div class="workspace">
72
+
73
+ <section class="card" id="upload-card">
74
+ <h2 class="card-label">Input</h2>
75
+
76
+ <div class="drop-zone" id="drop-zone">
77
+ <input type="file" id="file-input" accept="image/jpeg,image/png" hidden>
78
+ <div id="drop-content">
79
+ <svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
80
+ <path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/>
81
+ <polyline points="17 8 12 3 7 8"/>
82
+ <line x1="12" y1="3" x2="12" y2="15"/>
83
+ </svg>
84
+ <p>Drop a chest X-ray here</p>
85
+ <span style="margin: 4px 0;">or</span>
86
+ <button type="button" id="browse-btn" class="btn-outline">Browse Files</button>
87
+ <small style="margin-top: 8px;">JPEG Β· PNG Β· Pediatric chest X-ray</small>
88
+ <div id="drop-error" hidden>
89
+ <span style="color: var(--bacterial); display: flex; align-items: center; gap: 4px; margin-top: 8px; font-weight: 500;">
90
+ <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
91
+ Only JPEG and PNG are supported. Try a different file.
92
+ </span>
93
+ </div>
94
+ </div>
95
+ <img id="preview" alt="Selected X-ray" hidden>
96
+ </div>
97
+
98
+ <button id="predict-btn" disabled>Run Inference</button>
99
+ <button id="reset-btn" hidden>↑ Upload a new image</button>
100
+ </section>
101
+
102
+ <!-- Results (single model) -->
103
+ <section class="card" id="results-single">
104
+ <h2 class="card-label">Results</h2>
105
+
106
+ <div id="results-placeholder">
107
+ <p class="muted">Upload a chest X-ray to run inference.</p>
108
+ </div>
109
+
110
+ <div id="results-content" hidden>
111
+ <div id="model-badge-result"></div>
112
+ <div id="prediction-label"></div>
113
+ <p class="disclaimer" style="margin-bottom: 20px;">For research demonstration purposes only. Not for clinical use.</p>
114
+
115
+ <div class="confidence-section">
116
+ <div class="bar-row">
117
+ <span class="bar-label">Bacterial</span>
118
+ <div class="bar-track">
119
+ <div class="bar" id="bar-bacterial"></div>
120
+ <div class="bar-marker-50"></div>
121
+ <div class="bar-label-50">50%</div>
122
+ </div>
123
+ <span class="bar-value" id="pct-bacterial"></span>
124
+ </div>
125
+ <div class="bar-row">
126
+ <span class="bar-label">Viral</span>
127
+ <div class="bar-track">
128
+ <div class="bar" id="bar-viral"></div>
129
+ <div class="bar-marker-50"></div>
130
+ <div class="bar-label-50">50%</div>
131
+ </div>
132
+ <span class="bar-value" id="pct-viral"></span>
133
+ </div>
134
+ </div>
135
+
136
+ <div class="image-pair">
137
+ <figure>
138
+ <img id="img-original" alt="Input image">
139
+ <figcaption>Input Β· 384Γ—384</figcaption>
140
+ </figure>
141
+ <figure>
142
+ <img id="img-gradcam" alt="Grad-CAM heatmap">
143
+ <figcaption>Grad-CAM Activation</figcaption>
144
+ </figure>
145
+ </div>
146
+
147
+ </div>
148
+
149
+ <div id="loading" class="skeleton-container" hidden>
150
+ <div class="skeleton-label"></div>
151
+ <div class="skeleton-bar"></div>
152
+ <div class="skeleton-bar"></div>
153
+ <div class="skeleton-images">
154
+ <div class="skeleton-img"></div>
155
+ <div class="skeleton-img"></div>
156
+ </div>
157
+ <p class="muted timer-text" id="single-timer">Running inference Β· 0s</p>
158
+ </div>
159
+ <div id="error-box" hidden></div>
160
+ </section>
161
+
162
+ <!-- Results (compare mode) -->
163
+ <section id="results-compare" hidden>
164
+ <h2 class="section-heading">Side-by-Side Comparison</h2>
165
+
166
+ <div id="compare-loading" class="skeleton-container" hidden>
167
+ <div class="skeleton-images">
168
+ <div class="skeleton-img" style="height: 120px;"></div>
169
+ <div class="skeleton-img" style="height: 120px;"></div>
170
+ </div>
171
+ <p class="muted timer-text" id="compare-timer">Running inference Β· 0s</p>
172
+ </div>
173
+ <div id="compare-error" hidden></div>
174
+
175
+ <div id="compare-xray-row" class="compare-xray-row" hidden>
176
+ <figure>
177
+ <img id="compare-img-original" alt="Input image">
178
+ <figcaption>Input X-ray Β· 384Γ—384</figcaption>
179
+ </figure>
180
+ </div>
181
+
182
+ <div id="compare-cards" class="compare-grid" hidden>
183
+ <!-- Filled by JS -->
184
+ </div>
185
+ <p class="disclaimer" id="compare-disclaimer" hidden>For research demonstration purposes only. Not for clinical use.</p>
186
+ </section>
187
+ </div>
188
+
189
+ </main>
190
+
191
+ <footer>
192
+ <div class="container footer-inner">
193
+ <div class="footer-col">
194
+ <h3 class="footer-heading">Architecture</h3>
195
+ <table class="specs">
196
+ <tr><td>Backbone</td><td>EfficientNetB4 (ImageNet)</td></tr>
197
+ <tr><td>Pooling</td><td>Concat (GAP + GMP β†’ 3,584-dim)</td></tr>
198
+ <tr><td>Head</td><td>Dense 512 Β· Swish Β· BN Β· Dropout 0.5</td></tr>
199
+ <tr><td>Output</td><td>Dense 2 Β· Softmax (float32)</td></tr>
200
+ <tr><td>Loss</td><td>Focal Loss Ξ±=0.25, Ξ³=2.0, smooth=0.1</td></tr>
201
+ <tr><td>Optimizer</td><td>AdamW + LossScaleOptimizer (fp16)</td></tr>
202
+ <tr><td>TTA</td><td>2-step (original + H-flip)</td></tr>
203
+ </table>
204
+ </div>
205
+ <div class="footer-col">
206
+ <h3 class="footer-heading">Dataset Β· Kermany et al.</h3>
207
+ <table class="specs">
208
+ <tr><td>Train pool</td><td>3,883 images (2,538 bact Β· 1,345 viral)</td></tr>
209
+ <tr><td>Test set</td><td>N=390 (242 bact Β· 148 viral)</td></tr>
210
+ <tr><td>Split</td><td>80 / 20 from train+val folders</td></tr>
211
+ <tr><td>Balancing</td><td>Dynamic class weights (no oversampling)</td></tr>
212
+ <tr><td>Platform</td><td>Kaggle Β· Tesla P100-PCIE-16GB</td></tr>
213
+ <tr><td>Framework</td><td>TensorFlow 2.19.0 Β· mixed fp16</td></tr>
214
+ </table>
215
+ </div>
216
+ </div>
217
+ </footer>
218
+
219
+ <script src="{{ url_for('static', filename='script.js') }}"></script>
220
+ </body>
221
+ </html>
models/.gitkeep ADDED
File without changes
models/README.md ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Model Weights
2
+
3
+ Trained model weights are **not tracked in this repository** due to file size.
4
+
5
+ Download from the [GitHub Releases page](https://github.com/bennypepper/pneumonia-efficientnetb4/releases/tag/v2.0.0) and place files here in `models/`.
6
+
7
+ ---
8
+
9
+ ## Available Formats
10
+
11
+ | File | Size | Format | Notes |
12
+ |------|------|--------|-------|
13
+ | `fixed_size_model.weights.h5` | ~76 MB | Weights-only HDF5 | βœ… Recommended for most users |
14
+ | `progressive_model.weights.h5` | ~76 MB | Weights-only HDF5 | βœ… Recommended for most users |
15
+ | `fixed_size_model.keras` | ~317 MB | Full Keras SavedModel | For research / retraining only |
16
+ | `progressive_model.keras` | ~317 MB | Full Keras SavedModel | For research / retraining only |
17
+
18
+ ---
19
+
20
+ ## Loading `.weights.h5` (Recommended)
21
+
22
+ Requires rebuilding the architecture first, then loading weights:
23
+
24
+ ```python
25
+ import tensorflow as tf
26
+
27
+ def build_model(img_size=384):
28
+ """Concat Pooling EfficientNetB4 head β€” matches training architecture."""
29
+ tf.keras.mixed_precision.set_global_policy('float32')
30
+ inputs = tf.keras.Input(shape=(img_size, img_size, 3))
31
+ backbone = tf.keras.applications.EfficientNetB4(
32
+ include_top=False, weights=None, input_tensor=inputs
33
+ )
34
+ x = backbone.output
35
+ gap = tf.keras.layers.GlobalAveragePooling2D()(x)
36
+ gmp = tf.keras.layers.GlobalMaxPooling2D()(x)
37
+ x = tf.keras.layers.Concatenate()([gap, gmp])
38
+ x = tf.keras.layers.Dense(512, activation='swish')(x)
39
+ x = tf.keras.layers.BatchNormalization()(x)
40
+ x = tf.keras.layers.Dropout(0.5)(x)
41
+ out = tf.keras.layers.Dense(2, activation='softmax')(x)
42
+ return tf.keras.Model(inputs, out)
43
+
44
+ model = build_model(img_size=384)
45
+ model.load_weights("models/fixed_size_model.weights.h5")
46
+
47
+ # Inference β€” preprocess: pixel / 255.0 (NOT preprocess_input)
48
+ import numpy as np
49
+ from PIL import Image
50
+ img = np.array(Image.open("xray.jpg").resize((384, 384))) / 255.0
51
+ pred = model(img[np.newaxis].astype(np.float32), training=False).numpy()[0]
52
+ print(f"Bacterial: {pred[0]:.3f} Viral: {pred[1]:.3f}")
53
+ ```
54
+
55
+ ---
56
+
57
+ ## Loading `.keras` (Full Model)
58
+
59
+ ```python
60
+ import tensorflow as tf
61
+ model = tf.keras.models.load_model("models/fixed_size_model.keras", compile=False)
62
+ ```
63
+
64
+ Requires TensorFlow 2.19+. Mixed precision is embedded in the model config.
65
+
66
+ ---
67
+
68
+ ## Performance
69
+
70
+ | Model | Test Accuracy | Test AUC | FNR Viral |
71
+ |-------|-------------|---------|-----------|
72
+ | Fixed Size (384Γ—384) | 86.92% | 0.9198 | 32.4% |
73
+ | Progressive Resizing (224β†’256β†’384) | 78.46% | 0.8011 | 47.3% |
74
+
75
+ *Evaluated on 390-image Kermany test set (242 bacterial, 148 viral) with 2-pass TTA.*
76
+
77
+ ---
78
+
79
+ ## Architecture
80
+
81
+ - **Backbone**: EfficientNetB4 (ImageNet pretrained, `include_top=False`)
82
+ - **Head**: Concat Pooling β€” GlobalAveragePooling2D + GlobalMaxPooling2D β†’ Concatenate(3,584-dim) β†’ Dense(512, Swish) β†’ BatchNorm β†’ Dropout(0.5) β†’ Dense(2, Softmax)
83
+ - **Preprocessing**: pixel Γ· 255.0 β€” **not** `preprocess_input`
84
+ - **Loss**: CategoricalFocalCrossentropy (Ξ³=2.0, Ξ±=0.25, label_smoothing=0.1)
models/fixed_size_model.keras ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:3194c2093c6a5e231b7570235b785ccd3074dfb52c9fa7c4ef3257ac2f5fbb13
3
+ size 331935181
models/progressive_model.keras ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:35f78333ebe5f024a97c135b76a0477e425d00aaf994f267d2561ea4cb97467c
3
+ size 331934901
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ flask>=2.3.0
2
+ tensorflow>=2.12.0
3
+ numpy>=1.23.0
4
+ pandas>=1.5.0
5
+ matplotlib>=3.7.0
6
+ opencv-python>=4.7.0
7
+ albumentations>=1.3.0
8
+ scikit-learn>=1.2.0
9
+ Pillow>=9.5.00