Quantumstride commited on
Commit
024486e
Β·
verified Β·
1 Parent(s): f49d513

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +609 -65
app.py CHANGED
@@ -1,89 +1,633 @@
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
  import torch
3
- import numpy as np
 
 
 
 
 
4
  import pydicom
 
5
 
6
- # ── Load model ─────────────────────────
7
- ckpt = torch.load("swintiny_fold3.pt", map_location="cpu")
8
 
9
- # Try common keys
10
- state_dict = ckpt.get("model_state_dict", ckpt)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
- # Dummy model placeholder (temporary fix)
13
- import torch.nn as nn
14
 
15
- class DummyModel(nn.Module):
16
- def forward(self, ct, tab, weeks):
17
- return torch.zeros((1,145)), torch.ones((1,145))
 
 
 
 
 
 
 
 
 
 
18
 
19
- model = DummyModel()
20
- model.eval()
 
 
21
 
22
- # ── Basic DICOM processing ─────────────
23
- def process_dicom(files):
24
- if files is None or len(files) == 0:
25
- return torch.randn(1, 16, 224, 224) # fallback
26
 
27
- slices = []
28
- for f in files:
29
- ds = pydicom.dcmread(f.name)
30
- img = ds.pixel_array.astype(np.float32)
31
- slices.append(img)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
- volume = np.stack(slices)
 
 
 
 
 
 
 
 
 
 
 
34
 
35
- # normalize
36
- volume = (volume - volume.min()) / (volume.max() - volume.min() + 1e-5)
37
 
38
- # take first 16 slices
39
- if volume.shape[0] < 16:
40
- pad = 16 - volume.shape[0]
41
- volume = np.pad(volume, ((0, pad), (0,0), (0,0)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  else:
43
- volume = volume[:16]
44
 
45
- return torch.tensor(volume).unsqueeze(0).float()
 
46
 
 
 
 
 
 
 
 
 
 
 
47
 
48
- # ── Tabular processing ─────────────
49
- def process_tabular(age, sex, fvc, percent, smoking):
50
- sex_val = 1 if sex == "Male" else 0
51
- smoke_map = {"Never": 0, "Ex-smoker": 1, "Currently": 2}
52
- smoke_val = smoke_map.get(smoking, 0)
53
 
54
- return torch.tensor([[age, fvc, percent, sex_val, smoke_val]], dtype=torch.float32)
 
 
 
 
 
 
 
 
55
 
56
 
57
- # ── Prediction ─────────────
58
- def predict(age, sex, fvc, percent, smoking, dicoms):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- ct = process_dicom(dicoms)
61
- tab = process_tabular(age, sex, fvc, percent, smoking)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  with torch.no_grad():
64
- weeks = torch.arange(0, 145).float().unsqueeze(0)
65
- mu, sigma = model(ct, tab, weeks)
66
-
67
- fvc_1yr = mu[0][52].item()
68
-
69
- return f"Predicted FVC after 1 year: {fvc_1yr:.2f} ml"
70
-
71
-
72
- # ── UI ─────────────
73
- demo = gr.Interface(
74
- fn=predict,
75
- inputs=[
76
- gr.Number(label="Age", value=65),
77
- gr.Radio(["Male", "Female"], value="Male", label="Sex"),
78
- gr.Number(label="Baseline FVC", value=2500),
79
- gr.Number(label="Percent Predicted", value=70),
80
- gr.Dropdown(["Never", "Ex-smoker", "Currently"], value="Ex-smoker", label="Smoking"),
81
- gr.File(file_count="multiple", label="Upload DICOM files")
82
- ],
83
- outputs="text",
84
- title="🫁 FibrosisNet (Fast Demo)",
85
- description="Upload CT DICOM + patient data to predict fibrosis progression"
86
- )
87
-
88
- # ── Launch (important for HF) ─────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
+ """
2
+ FibrosisNet-V4 β€” Gradio App
3
+ Real model inference + FVC decline graph + 3D DICOM lung viewer with slice slider
4
+ Upload to Hugging Face Spaces (SDK: Gradio)
5
+ """
6
+
7
+ import os, json, warnings, math
8
+ import numpy as np
9
  import gradio as gr
10
  import torch
11
+ import torch.nn as nn
12
+ import torch.nn.functional as F
13
+ import matplotlib
14
+ matplotlib.use("Agg")
15
+ import matplotlib.pyplot as plt
16
+ import matplotlib.gridspec as gridspec
17
  import pydicom
18
+ import timm
19
 
20
+ warnings.filterwarnings("ignore")
21
+ device = torch.device("cpu")
22
 
23
+ # ─────────────────────────────────────────────────────────────
24
+ # CONFIGURATION (must match training exactly)
25
+ # ─────────────────────────────────────────────────────────────
26
+ IMG_SIZE = 224
27
+ NUM_SLICES = 16
28
+ HU_MIN, HU_MAX = -1000, 400
29
+ TAB_FEATURES = [
30
+ "BaselineFVC", "Percent", "Age", "Sex_enc", "Smoking_enc",
31
+ "FVC_height_ratio", "percent_age_interaction",
32
+ ]
33
+ SIN_PERIODS = (10., 26., 52., 104.)
34
+ SIN_DIM = len(SIN_PERIODS) * 2
35
+ TAB_DIM = len(TAB_FEATURES) + SIN_DIM # 15
36
+ FUSION_DIM = 512
37
+ FUSION_HEADS = 8
38
+ FUSION_DEPTH = 1
39
 
40
+ BLUE = "#2563EB"; GREEN = "#059669"; CORAL = "#DC2626"
41
+ GOLD = "#D97706"; GRAY = "#6B7280"; BG = "#F8FAFC"
42
 
43
+ # ─────────────────────────────────────────────────────────────
44
+ # MODEL ARCHITECTURE (exact copy from training notebook)
45
+ # ─────────────────────────────────────────────────────────────
46
+ class SEAttentionPool(nn.Module):
47
+ def __init__(self, enc_dim, n_slices=NUM_SLICES, reduction=16):
48
+ super().__init__()
49
+ self.attn = nn.Sequential(nn.Linear(enc_dim, 256), nn.Tanh(), nn.Linear(256, 1))
50
+ self.se = nn.Sequential(
51
+ nn.Linear(enc_dim, enc_dim // reduction),
52
+ nn.ReLU(inplace=True),
53
+ nn.Linear(enc_dim // reduction, enc_dim),
54
+ nn.Sigmoid(),
55
+ )
56
 
57
+ def forward(self, feat):
58
+ attn_w = F.softmax(self.attn(feat), dim=1)
59
+ pooled = (feat * attn_w).sum(dim=1)
60
+ return pooled * self.se(pooled)
61
 
 
 
 
 
62
 
63
+ class FusionTransformer(nn.Module):
64
+ def __init__(self, ct_dim, tab_dim_in, fuse_dim=FUSION_DIM,
65
+ n_heads=FUSION_HEADS, depth=FUSION_DEPTH):
66
+ super().__init__()
67
+ self.ct_proj = nn.Linear(ct_dim, fuse_dim)
68
+ self.tab_proj = nn.Linear(tab_dim_in, fuse_dim)
69
+ layer = nn.TransformerDecoderLayer(
70
+ d_model=fuse_dim, nhead=n_heads, dim_feedforward=fuse_dim * 4,
71
+ dropout=0.1, activation="gelu", batch_first=True, norm_first=True,
72
+ )
73
+ self.cross_attn = nn.TransformerDecoder(layer, num_layers=depth)
74
+ self.norm = nn.LayerNorm(fuse_dim)
75
+
76
+ def forward(self, ct_seq, tab_feat):
77
+ ct_kv = self.ct_proj(ct_seq)
78
+ tab_q = self.tab_proj(tab_feat).unsqueeze(1)
79
+ fused = self.cross_attn(tab_q, ct_kv)
80
+ return self.norm(fused.squeeze(1))
81
+
82
+
83
+ class TrajectoryHead(nn.Module):
84
+ def __init__(self, in_dim):
85
+ super().__init__()
86
+ self.week_proj = nn.Linear(3, 64)
87
+ self.fc = nn.Sequential(
88
+ nn.Linear(in_dim + 64, 512), nn.LayerNorm(512), nn.GELU(), nn.Dropout(0.20),
89
+ nn.Linear(512, 256), nn.LayerNorm(256), nn.GELU(), nn.Dropout(0.15),
90
+ nn.Linear(256, 3),
91
+ )
92
+ with torch.no_grad():
93
+ self.fc[-1].weight.data.zero_()
94
+ self.fc[-1].bias.data = torch.tensor([-2., 0., 5.])
95
+ self.sigma_rate_fc = nn.Linear(in_dim, 1)
96
+
97
+ def _week_embed(self, w):
98
+ return torch.stack([torch.sin(w / 52.0), torch.cos(w / 52.0),
99
+ (w / 100.0).clamp(-1, 1)], dim=-1)
100
 
101
+ def forward(self, feat, base_fvc, weeks):
102
+ B, T = weeks.shape
103
+ sigma_rate = torch.exp(self.sigma_rate_fc(feat)).clamp(0.01, 10.0)
104
+ out = self.fc(torch.cat([
105
+ feat.unsqueeze(1).expand(-1, T, -1),
106
+ F.gelu(self.week_proj(self._week_embed(weeks))),
107
+ ], dim=-1))
108
+ slope = out[..., 0:1]; intercept = out[..., 1:2]
109
+ sigma_base = torch.exp(out[..., 2:3]).clamp(50, 500)
110
+ mu = base_fvc.view(B, 1) + intercept.squeeze(-1) + slope.squeeze(-1) * weeks
111
+ sigma = (sigma_base.squeeze(-1) + sigma_rate * weeks.abs()).clamp(70, 3000)
112
+ return mu, sigma
113
 
 
 
114
 
115
+ class FibrosisModel2p5D(nn.Module):
116
+ def __init__(self, backbone_name, pretrained=False):
117
+ super().__init__()
118
+ self.backbone = timm.create_model(backbone_name, pretrained=pretrained,
119
+ num_classes=0, global_pool="")
120
+ enc_dim = self.backbone.num_features
121
+ self.gap = nn.AdaptiveAvgPool2d(1)
122
+ self.se_pool = SEAttentionPool(enc_dim, n_slices=NUM_SLICES)
123
+ self.tab_mlp = nn.Sequential(
124
+ nn.Linear(TAB_DIM, 256), nn.LayerNorm(256), nn.GELU(), nn.Dropout(0.1),
125
+ nn.Linear(256, 128), nn.LayerNorm(128), nn.GELU(),
126
+ )
127
+ self.fusion = FusionTransformer(enc_dim, 128, FUSION_DIM)
128
+ self.head = TrajectoryHead(FUSION_DIM)
129
+
130
+ def encode_ct(self, x):
131
+ B, C, D, H, W = x.shape
132
+ x2d = x.permute(0, 2, 1, 3, 4).reshape(B * D, C, H, W)
133
+ raw = self.backbone.forward_features(x2d)
134
+ if raw.ndim == 3:
135
+ feat = raw[:, 0]
136
+ elif raw.shape[-1] == self.backbone.num_features:
137
+ feat = raw.mean(dim=(1, 2))
138
+ else:
139
+ feat = self.gap(raw).flatten(1)
140
+ return feat.view(B, D, -1)
141
+
142
+ def forward(self, vol, tab, base_fvc, weeks):
143
+ ct_seq = self.encode_ct(vol)
144
+ fused = self.fusion(ct_seq, self.tab_mlp(tab))
145
+ return self.head(fused, base_fvc, weeks)
146
+
147
+
148
+ # ─────────────────────────────────────────────────────────────
149
+ # LOAD CHECKPOINT
150
+ # ─────────────────────────────────────────────────────────────
151
+ def load_model():
152
+ swin_name = "swin_tiny_patch4_window7_224"
153
+ try:
154
+ swin_name = "swin_tiny_patch4_window7_224.ms_in1k"
155
+ m = FibrosisModel2p5D(swin_name, pretrained=False)
156
+ except Exception:
157
+ m = FibrosisModel2p5D("swin_tiny_patch4_window7_224", pretrained=False)
158
+
159
+ ckpt_path = "swintiny_fold3.pt"
160
+ if os.path.exists(ckpt_path):
161
+ ckpt = torch.load(ckpt_path, map_location="cpu")
162
+ state = ckpt.get("model_state_dict", ckpt.get("ema_state_dict", ckpt))
163
+ # strip compiled-model prefix if present
164
+ state = {k.replace("_orig_mod.", ""): v for k, v in state.items()}
165
+ missing, unexpected = m.load_state_dict(state, strict=False)
166
+ print(f"βœ… Checkpoint loaded | missing={len(missing)} unexpected={len(unexpected)}")
167
  else:
168
+ print("⚠️ swintiny_fold3.pt not found β€” running with random weights (demo mode)")
169
 
170
+ m.eval()
171
+ return m
172
 
173
+ # load norm stats
174
+ def load_norm_stats():
175
+ if os.path.exists("norm_stats.json"):
176
+ ns = json.load(open("norm_stats.json"))
177
+ t_mean = np.array(ns["t_mean"], dtype=np.float32)
178
+ t_std = np.array(ns["t_std"], dtype=np.float32)
179
+ return t_mean, t_std
180
+ # fallback defaults (approximate β€” use real norm_stats.json for accuracy)
181
+ return np.array([2700., 75., 65., 0.5, 1., 3500., 1.07], dtype=np.float32), \
182
+ np.array([800., 18., 9., 0.5, 0.7, 800., 0.2], dtype=np.float32)
183
 
184
+ MODEL = load_model()
185
+ T_MEAN, T_STD = load_norm_stats()
 
 
 
186
 
187
+ # ─────────────────────────────────────────────────────────────
188
+ # CT PREPROCESSING (exact from notebook)
189
+ # ─────────────────────────────────────────────────────────────
190
+ def detect_lung_extent(vol, threshold=0.06):
191
+ mean_int = vol.mean(axis=(1, 2))
192
+ mask = mean_int > threshold
193
+ if mask.sum() < 5:
194
+ return 0, vol.shape[0] - 1
195
+ return int(np.argmax(mask)), int(len(mask) - np.argmax(mask[::-1]) - 1)
196
 
197
 
198
+ def adaptive_sample_slices(vol, n=NUM_SLICES, basal_frac=0.65):
199
+ D = vol.shape[0]
200
+ lo, hi = detect_lung_extent(vol)
201
+ mid = (lo + hi) // 2
202
+ n_lower = int(n * basal_frac)
203
+ idx = np.concatenate([
204
+ np.linspace(lo, mid - 1, n - n_lower).astype(int),
205
+ np.linspace(mid, hi, n_lower).astype(int),
206
+ ]).clip(0, D - 1)
207
+ t = torch.from_numpy(vol[idx]).unsqueeze(0).unsqueeze(0).float()
208
+ t = F.interpolate(t, size=(n, IMG_SIZE, IMG_SIZE), mode="trilinear", align_corners=False)
209
+ return t.squeeze(0).squeeze(0).numpy()
210
+
211
+
212
+ def build_3channel(slices):
213
+ return np.stack([
214
+ slices,
215
+ (slices > 0.05).astype(np.float32),
216
+ np.clip((slices - 0.3) * 2.0, 0, 1),
217
+ ], axis=0).astype(np.float32)
218
+
219
+
220
+ def load_dicoms(files):
221
+ """Load DICOM files β†’ (D, H, W) HU-normalised volume."""
222
+ if not files:
223
+ return None
224
+ slices, positions = [], []
225
+ for f in files:
226
+ try:
227
+ ds = pydicom.dcmread(f.name if hasattr(f, "name") else f)
228
+ img = ds.pixel_array.astype(np.float32)
229
+ slope = float(getattr(ds, "RescaleSlope", 1))
230
+ intercept = float(getattr(ds, "RescaleIntercept", 0))
231
+ img = img * slope + intercept
232
+ pos = float(getattr(ds, "ImagePositionPatient", [0, 0, 0])[-1]
233
+ if hasattr(ds, "ImagePositionPatient") else 0)
234
+ slices.append(img); positions.append(pos)
235
+ except Exception:
236
+ continue
237
+ if not slices:
238
+ return None
239
+ order = np.argsort(positions)
240
+ volume = np.stack([slices[i] for i in order])
241
+ volume = np.clip(volume, HU_MIN, HU_MAX)
242
+ volume = (volume - HU_MIN) / (HU_MAX - HU_MIN) # [0, 1]
243
+ return volume # (D, H, W)
244
 
245
+
246
+ # ─────────────────────────────────────────────────────────────
247
+ # TABULAR FEATURES (exact from notebook)
248
+ # ─────────────────────────────────────────────────────────────
249
+ def sinusoidal_week(w, periods=SIN_PERIODS):
250
+ encs = []
251
+ for p in periods:
252
+ encs.append(math.sin(w / p))
253
+ encs.append(math.cos(w / p))
254
+ return encs
255
+
256
+
257
+ def build_tabular(age, sex, fvc, percent, smoking):
258
+ sex_enc = 1. if sex == "Male" else 0.
259
+ smoke_map = {"Never smoker": 0., "Ex-smoker": 1., "Currently smokes": 2.}
260
+ smoke_enc = smoke_map.get(smoking, 1.)
261
+ fvc_height_ratio = fvc / max(percent / 100., 0.01)
262
+ percent_age_interaction = (percent / 100.) * (age / 70.)
263
+ base_feats = np.array([fvc, percent, age, sex_enc, smoke_enc,
264
+ fvc_height_ratio, percent_age_interaction], dtype=np.float32)
265
+ norm_feats = (base_feats - T_MEAN) / (T_STD + 1e-6)
266
+ sin_feats = np.array(sinusoidal_week(0.), dtype=np.float32) # week-0 encoding
267
+ return np.concatenate([norm_feats, sin_feats])
268
+
269
+
270
+ # ─────────────────────────────────────────────────────────────
271
+ # INFERENCE
272
+ # ─────────────────────────────────────────────────────────────
273
+ def run_inference(age, sex, fvc, percent, smoking, volume):
274
+ tab_np = build_tabular(age, sex, fvc, percent, smoking)
275
+ tab_t = torch.from_numpy(tab_np).unsqueeze(0)
276
+ bfvc_t = torch.tensor([[fvc]], dtype=torch.float32)
277
+ weeks_t = torch.arange(0, 145, dtype=torch.float32).unsqueeze(0)
278
+
279
+ if volume is not None:
280
+ slices = adaptive_sample_slices(volume)
281
+ ct_3ch = build_3channel(slices) # (3, 16, 224, 224)
282
+ vol_t = torch.from_numpy(ct_3ch).unsqueeze(0) # (1, 3, 16, 224, 224)
283
+ else:
284
+ vol_t = torch.zeros(1, 3, NUM_SLICES, IMG_SIZE, IMG_SIZE)
285
 
286
  with torch.no_grad():
287
+ mu, sigma = MODEL(vol_t, tab_t, bfvc_t.squeeze(1), weeks_t)
288
+
289
+ return mu.squeeze().numpy(), sigma.squeeze().numpy()
290
+
291
+
292
+ # ─────────────────────────────────────────────────────────────
293
+ # FVC DECLINE PLOT
294
+ # ─────────────────────────────────────────────────────────────
295
+ def make_fvc_plot(fvc_baseline, mu, sigma, age, sex, percent):
296
+ weeks = np.arange(0, 145)
297
+ # reference "normal" FVC (rough GLI estimate)
298
+ normal_fvc = (fvc_baseline / max(percent / 100., 0.01))
299
+
300
+ fig = plt.figure(figsize=(13, 7), facecolor=BG)
301
+ gs = gridspec.GridSpec(2, 2, figure=fig, hspace=0.40, wspace=0.35)
302
+ ax_main = fig.add_subplot(gs[:, 0]) # left: trajectory
303
+ ax_rate = fig.add_subplot(gs[0, 1]) # right-top: decline rate
304
+ ax_sev = fig.add_subplot(gs[1, 1]) # right-bottom: severity gauge
305
+
306
+ # ── Main trajectory ──
307
+ ax_main.plot(weeks, mu, color=BLUE, lw=2.5, zorder=4, label="Predicted FVC")
308
+ ax_main.fill_between(weeks, mu - sigma, mu + sigma,
309
+ alpha=0.22, color=BLUE, label="Β±1Οƒ confidence")
310
+ ax_main.fill_between(weeks, mu - 2*sigma, mu + 2*sigma,
311
+ alpha=0.09, color=BLUE, label="Β±2Οƒ confidence")
312
+ ax_main.axhline(fvc_baseline, color=GRAY, ls="--", lw=1.5, label="Baseline FVC")
313
+ ax_main.axhline(fvc_baseline * 0.90, color=CORAL, ls=":", lw=1.8,
314
+ label="10% decline threshold")
315
+ ax_main.axhline(fvc_baseline * 0.80, color="#7f0000", ls=":", lw=1.2,
316
+ label="20% decline threshold", alpha=0.7)
317
+ ax_main.axhline(normal_fvc, color=GREEN, ls="-.", lw=1.2,
318
+ label="Estimated normal FVC", alpha=0.7)
319
+ ax_main.scatter([0], [fvc_baseline], color="black", s=90, zorder=6)
320
+ # mark week milestones
321
+ for wk, label in [(26, "6m"), (52, "1yr"), (104, "2yr")]:
322
+ ax_main.axvline(wk, color=GRAY, ls=":", lw=0.8, alpha=0.5)
323
+ ax_main.text(wk + 1, mu.min() * 0.97, label, fontsize=7, color=GRAY)
324
+
325
+ ax_main.set_xlabel("Weeks from Baseline", fontsize=11)
326
+ ax_main.set_ylabel("FVC (ml)", fontsize=11)
327
+ ax_main.set_title("FVC Trajectory β€” FibrosisNet-V4", fontweight="bold", fontsize=12)
328
+ ax_main.legend(fontsize=7.5, loc="lower left")
329
+ ax_main.grid(alpha=0.25)
330
+ ax_main.set_facecolor(BG)
331
+
332
+ # ── Weekly decline rate bar ──
333
+ checkpoints = [0, 13, 26, 52, 78, 104, 144]
334
+ labels_ck = ["0w","3m","6m","1yr","18m","2yr","End"]
335
+ fvc_ck = [mu[min(w, 144)] for w in checkpoints]
336
+ colors_ck = [GREEN if v >= fvc_baseline*0.9 else
337
+ GOLD if v >= fvc_baseline*0.8 else CORAL for v in fvc_ck]
338
+ ax_rate.bar(labels_ck, fvc_ck, color=colors_ck, edgecolor="white", linewidth=0.5)
339
+ ax_rate.axhline(fvc_baseline, color=GRAY, ls="--", lw=1.2, alpha=0.8)
340
+ ax_rate.axhline(fvc_baseline * 0.9, color=CORAL, ls=":", lw=1.2, alpha=0.8)
341
+ ax_rate.set_ylabel("FVC (ml)", fontsize=9)
342
+ ax_rate.set_title("FVC at Key Timepoints", fontweight="bold", fontsize=10)
343
+ ax_rate.grid(axis="y", alpha=0.2); ax_rate.set_facecolor(BG)
344
+ for bar, val in zip(ax_rate.patches, fvc_ck):
345
+ ax_rate.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 20,
346
+ f"{val:.0f}", ha="center", fontsize=7)
347
+
348
+ # ── Severity gauge (horizontal bar) ──
349
+ decline_1yr = (fvc_baseline - mu[52]) / fvc_baseline * 100
350
+ if decline_1yr < 5:
351
+ sev_label, sev_col = "Stable / Mild", GREEN
352
+ elif decline_1yr < 10:
353
+ sev_label, sev_col = "Moderate", GOLD
354
+ else:
355
+ sev_label, sev_col = "Severe / Rapid", CORAL
356
+
357
+ thresholds = [0, 5, 10, 20, 30]
358
+ bar_cols = [GREEN, GOLD, "#f97316", CORAL, "#7f0000"]
359
+ for j in range(len(thresholds)-1):
360
+ ax_sev.barh(0, thresholds[j+1]-thresholds[j], left=thresholds[j],
361
+ color=bar_cols[j], height=0.4, alpha=0.55)
362
+ ax_sev.axvline(max(0, min(decline_1yr, 28)), color="black", lw=3, zorder=5)
363
+ ax_sev.set_xlim(0, 30); ax_sev.set_ylim(-0.5, 0.5)
364
+ ax_sev.set_yticks([]); ax_sev.set_xlabel("Annual FVC Decline (%)", fontsize=9)
365
+ ax_sev.set_title(f"Severity: {sev_label} ({decline_1yr:.1f}%/yr)",
366
+ fontweight="bold", fontsize=10, color=sev_col)
367
+ for xt, xtl in zip(thresholds, ["0%","5%","10%","20%","30%"]):
368
+ ax_sev.text(xt, -0.42, xtl, fontsize=7, ha="center", color=GRAY)
369
+ ax_sev.set_facecolor(BG)
370
+
371
+ fig.suptitle(f"FibrosisNet-V4 | Age {int(age)} {sex} | Baseline FVC {fvc_baseline:.0f} ml",
372
+ fontsize=11, fontweight="bold", y=0.98)
373
+ plt.tight_layout()
374
+ return fig
375
+
376
+
377
+ # ─────────────────────────────────────────────────────────────
378
+ # 3D LUNG VIEWER SLICES (returns list of images per axis)
379
+ # ─────────────────────────────────────────────────────────────
380
+ def make_lung_slices(volume):
381
+ """Return axial slices as a list of matplotlib images for the gallery."""
382
+ imgs = []
383
+ step = max(1, volume.shape[0] // 20)
384
+ for i in range(0, volume.shape[0], step):
385
+ fig, ax = plt.subplots(1, 1, figsize=(4, 4), facecolor="black")
386
+ ax.imshow(volume[i], cmap="gray", vmin=0, vmax=1)
387
+ ax.set_title(f"Axial Slice {i+1}/{volume.shape[0]}", color="white", fontsize=9)
388
+ ax.axis("off")
389
+ fig.tight_layout(pad=0.1)
390
+ imgs.append(fig)
391
+ plt.close(fig)
392
+ return imgs
393
+
394
+
395
+ def make_multiview(volume):
396
+ """Single figure with axial, coronal, sagittal mid-slices + colorbar."""
397
+ D, H, W = volume.shape
398
+ fig, axes = plt.subplots(1, 3, figsize=(13, 4.5), facecolor="black")
399
+ views = [
400
+ (volume[D//2], "Axial (mid)"),
401
+ (volume[:, H//2, :], "Coronal (mid)"),
402
+ (volume[:, :, W//2], "Sagittal (mid)"),
403
+ ]
404
+ for ax, (img, title) in zip(axes, views):
405
+ im = ax.imshow(img, cmap="bone", vmin=0, vmax=1, aspect="auto")
406
+ ax.set_title(title, color="white", fontsize=11, pad=5)
407
+ ax.axis("off")
408
+ fig.colorbar(im, ax=axes[-1], fraction=0.03, pad=0.02,
409
+ label="HU Normalised [0β†’1]").ax.yaxis.label.set_color("white")
410
+ fig.suptitle("CT Lung Volume β€” Multi-Plane View", color="white",
411
+ fontsize=12, fontweight="bold")
412
+ plt.tight_layout()
413
+ return fig
414
+
415
+
416
+ # ─────────────────────────────────────────────────────────────
417
+ # CLINICAL TEXT REPORT
418
+ # ─────────────────────────────────────────────────────────────
419
+ def build_report(age, sex, fvc, percent, smoking, mu, sigma):
420
+ fvc_6m = mu[26]; fvc_1yr = mu[52]; fvc_2yr = mu[104]
421
+ dec_6m = fvc - fvc_6m
422
+ dec_1yr = fvc - fvc_1yr
423
+ dec_pct = dec_1yr / fvc * 100
424
+ sig_1yr = sigma[52]
425
+ normal_fvc = fvc / max(percent / 100., 0.01)
426
+
427
+ # severity classification (ATS/ERS criteria on %predicted)
428
+ if percent >= 70:
429
+ sev = "Mild"
430
+ elif percent >= 50:
431
+ sev = "Moderate"
432
+ else:
433
+ sev = "Severe"
434
+
435
+ # trajectory classification
436
+ if dec_pct < 5:
437
+ traj = "STABLE β€” decline within expected physiological variation"
438
+ monitor = "every 6 months"
439
+ elif dec_pct < 10:
440
+ traj = "SLOW DECLINE β€” clinically meaningful progression likely"
441
+ monitor = "every 3–4 months"
442
+ else:
443
+ traj = "RAPID DECLINE β€” urgent clinical attention warranted"
444
+ monitor = "monthly or as clinically indicated"
445
+
446
+ # time to 10% threshold
447
+ threshold_10 = fvc * 0.90
448
+ wks_to_10 = None
449
+ for w in range(145):
450
+ if mu[w] <= threshold_10:
451
+ wks_to_10 = w
452
+ break
453
+
454
+ report = f"""
455
+ ╔══════════════════════════════════════════════════════════╗
456
+ β•‘ FibrosisNet-V4 β€” Clinical Summary Report β•‘
457
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
458
+
459
+ PATIENT PROFILE
460
+ Age : {int(age)} years
461
+ Sex : {sex}
462
+ Smoking : {smoking}
463
+ Baseline FVC : {fvc:.0f} ml ({percent:.1f}% predicted)
464
+ Normal FVC β‰ˆ : {normal_fvc:.0f} ml (GLI-estimated for age/sex)
465
+
466
+ SEVERITY CLASSIFICATION (ATS/ERS based on %Predicted FVC)
467
+ β–Ί {sev.upper()} ({percent:.1f}% predicted)
468
+ β€’ β‰₯70%: Mild | 50–69%: Moderate | <50%: Severe
469
+
470
+ PREDICTED TRAJECTORY
471
+ β–Ί {traj}
472
+
473
+ Predicted FVC:
474
+ 6 months : {fvc_6m:.0f} ml (βˆ’{dec_6m:.0f} ml from baseline)
475
+ 1 year : {fvc_1yr:.0f} ml (βˆ’{dec_1yr:.0f} ml, {dec_pct:.1f}%/yr)
476
+ 2 years : {fvc_2yr:.0f} ml (βˆ’{fvc-fvc_2yr:.0f} ml cumulative)
477
+
478
+ Uncertainty at 1 year (Β±1Οƒ):
479
+ Range: {fvc_1yr - sig_1yr:.0f} – {fvc_1yr + sig_1yr:.0f} ml
480
+
481
+ TIME TO CLINICALLY SIGNIFICANT THRESHOLD
482
+ 10% FVC Decline (key trial endpoint):
483
+ {'β–Ί Estimated at week ' + str(wks_to_10) + f' (~{wks_to_10//4} months)' if wks_to_10 else 'β–Ί Not reached within 2.5-year horizon'}
484
+
485
+ MONITORING RECOMMENDATION
486
+ β–Ί Spirometry {monitor}
487
+ β–Ί 6-minute walk test at each visit
488
+ {'β–Ί Consider antifibrotic therapy discussion' if sev in ('Moderate','Severe') or dec_pct >= 10 else 'β–Ί Continue current management plan'}
489
+
490
+ PATIENT-FRIENDLY SUMMARY
491
+ {"Your lung function is currently " + sev.lower() + "ly affected by fibrosis. " +
492
+ ("Based on your CT scan and clinical data, we predict your lung capacity may decline by " +
493
+ f"approximately {dec_1yr:.0f} ml ({dec_pct:.1f}%) over the next year. " if dec_pct > 3 else
494
+ "Your lung function appears relatively stable over the next year. ") +
495
+ f"We recommend follow-up every {monitor}."}
496
+
497
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
498
+ ⚠ This report is generated by an AI research model.
499
+ Always consult a qualified pulmonologist for clinical decisions.
500
+ ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
501
+ """
502
+ return report.strip()
503
+
504
+
505
+ # ─────────────────────────────────────────────────────────────
506
+ # MAIN PIPELINE (called by Gradio)
507
+ # ─────────────────────────────────────────────────────────────
508
+ _LAST_VOLUME = {"vol": None} # cache for slice viewer
509
+
510
+ def full_pipeline(age, sex, fvc, percent, smoking, dicom_files):
511
+ volume = None
512
+ if dicom_files:
513
+ volume = load_dicoms(dicom_files)
514
+ _LAST_VOLUME["vol"] = volume
515
+
516
+ mu, sigma = run_inference(age, sex, float(fvc), percent, smoking, volume)
517
+ fvc_plot = make_fvc_plot(float(fvc), mu, sigma, age, sex, percent)
518
+ report_txt = build_report(age, sex, float(fvc), percent, smoking, mu, sigma)
519
+
520
+ # multi-plane CT view
521
+ if volume is not None:
522
+ ct_view = make_multiview(volume)
523
+ else:
524
+ fig, ax = plt.subplots(figsize=(6, 3))
525
+ ax.text(0.5, 0.5, "No DICOM uploaded β€” CT view unavailable",
526
+ ha="center", va="center", transform=ax.transAxes, color=GRAY)
527
+ ax.axis("off"); ct_view = fig
528
+
529
+ return fvc_plot, ct_view, report_txt
530
+
531
+
532
+ def update_slice(slice_idx):
533
+ """Called by the slice slider to show a specific axial slice."""
534
+ vol = _LAST_VOLUME.get("vol")
535
+ if vol is None:
536
+ fig, ax = plt.subplots(figsize=(5, 5))
537
+ ax.text(0.5, 0.5, "Upload DICOM first", ha="center", va="center",
538
+ transform=ax.transAxes, color=GRAY)
539
+ ax.axis("off"); return fig
540
+ idx = int(np.clip(slice_idx, 0, vol.shape[0] - 1))
541
+ fig, axes = plt.subplots(1, 3, figsize=(13, 4.5), facecolor="black")
542
+ D, H, W = vol.shape
543
+ views = [
544
+ (vol[idx], f"Axial β€” slice {idx+1}/{D}"),
545
+ (vol[:, H//2, :], "Coronal"),
546
+ (vol[:, :, W//2], "Sagittal"),
547
+ ]
548
+ for ax, (img, title) in zip(axes, views):
549
+ ax.imshow(img, cmap="bone", vmin=0, vmax=1, aspect="auto")
550
+ ax.set_title(title, color="white", fontsize=10, pad=4)
551
+ ax.axis("off")
552
+ fig.patch.set_facecolor("black")
553
+ plt.tight_layout()
554
+ return fig
555
+
556
+
557
+ # ─────────────────────────────────────────────────────────────
558
+ # GRADIO UI
559
+ # ─────────────────────────────────────────────────────────────
560
+ css = """
561
+ .gradio-container { max-width: 1200px; margin: auto; }
562
+ h1 { text-align: center; color: #1e3a5f; }
563
+ .report-box textarea { font-family: monospace; font-size: 12px; }
564
+ """
565
+
566
+ with gr.Blocks(title="FibrosisNet-V4", theme=gr.themes.Soft(), css=css) as demo:
567
+ gr.Markdown("""
568
+ # 🫁 FibrosisNet-V4
569
+ ### Pulmonary Fibrosis Progression Prediction Β· Multi-Backbone 2.5D Deep Learning
570
+ *Upload DICOM CT slices + enter clinical data β†’ get FVC trajectory, lung view & clinical report*
571
+ """)
572
+
573
+ with gr.Row():
574
+ # ── LEFT COLUMN: Inputs ──
575
+ with gr.Column(scale=1, min_width=280):
576
+ gr.Markdown("### πŸ“‹ Patient Clinical Data")
577
+ age = gr.Slider(30, 90, value=65, step=1, label="Age (years)")
578
+ sex = gr.Radio(["Male", "Female"], value="Male", label="Sex")
579
+ fvc = gr.Number(value=2500, label="Baseline FVC (ml)")
580
+ percent = gr.Slider(20, 100, value=70, step=0.5,
581
+ label="Percent Predicted FVC (%)")
582
+ smoking = gr.Dropdown(
583
+ ["Never smoker", "Ex-smoker", "Currently smokes"],
584
+ value="Ex-smoker", label="Smoking Status"
585
+ )
586
+ gr.Markdown("### 🩻 CT DICOM Upload")
587
+ dicoms = gr.File(
588
+ label="Upload DICOM files (.dcm) β€” multiple OK",
589
+ file_count="multiple",
590
+ file_types=[".dcm", ".DCM"]
591
+ )
592
+ predict_btn = gr.Button("πŸ”¬ Run FibrosisNet Prediction",
593
+ variant="primary", size="lg")
594
+
595
+ # ── RIGHT COLUMN: Outputs ──
596
+ with gr.Column(scale=2):
597
+ with gr.Tabs():
598
+ with gr.Tab("πŸ“ˆ FVC Decline Graph"):
599
+ fvc_plot = gr.Plot(label="FVC Trajectory with Uncertainty Bands")
600
+
601
+ with gr.Tab("🫁 Lung CT Viewer"):
602
+ gr.Markdown("*Overview: axial Β· coronal Β· sagittal mid-planes*")
603
+ ct_view = gr.Plot(label="CT Multi-plane View")
604
+ gr.Markdown("---\n**Slice Explorer** (axial, drag slider after prediction)")
605
+ slice_slider = gr.Slider(0, 200, value=0, step=1,
606
+ label="Axial slice index")
607
+ slice_view = gr.Plot(label="Axial Slice Viewer")
608
+ slice_slider.change(fn=update_slice,
609
+ inputs=slice_slider,
610
+ outputs=slice_view)
611
+
612
+ with gr.Tab("πŸ“„ Clinical Report"):
613
+ report_box = gr.Textbox(
614
+ label="AI Clinical Report",
615
+ lines=28, max_lines=40,
616
+ elem_classes="report-box"
617
+ )
618
+
619
+ predict_btn.click(
620
+ fn=full_pipeline,
621
+ inputs=[age, sex, fvc, percent, smoking, dicoms],
622
+ outputs=[fvc_plot, ct_view, report_box],
623
+ )
624
+
625
+ gr.Markdown("""
626
+ ---
627
+ **Model:** Swin-Tiny 2.5D backbone Β· SE Attention Pooling Β· Cross-Attention Fusion Β· Trajectory Head
628
+ **Dataset:** OSIC Pulmonary Fibrosis Progression (Kaggle 2020) β€” 171 patients
629
+ **OOF Score:** βˆ’6.6629 (beats Kaggle baseline βˆ’6.6743)
630
+ ⚠️ *Research prototype β€” not for clinical use without physician oversight.*
631
+ """)
632
+
633
  demo.launch(server_name="0.0.0.0", server_port=7860)