Quantumstride commited on
Commit
de285d0
·
verified ·
1 Parent(s): 3a1057b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +558 -713
app.py CHANGED
@@ -1,10 +1,9 @@
1
  """
2
- FibrosisNet-V4 — Gradio App
3
- Upload full OSIC test.csv + CT DICOM files → auto-detect Patient ID
4
- → extract clinical data → run inference → FVC graph + CT viewer + report
5
  """
6
 
7
- import os, json, warnings, math
8
  import numpy as np
9
  import pandas as pd
10
  import gradio as gr
@@ -20,778 +19,624 @@ import timm
20
 
21
  warnings.filterwarnings("ignore")
22
 
23
- # ─────────────────────────────────────────────────────────────
24
- # CONFIG (must match training)
25
- # ─────────────────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
26
  IMG_SIZE = 224
27
  NUM_SLICES = 16
28
  HU_MIN, HU_MAX = -1000, 400
29
-
30
- TAB_FEATURES = [
31
- "BaselineFVC", "Percent", "Age", "Sex_enc", "Smoking_enc",
32
- "FVC_height_ratio", "percent_age_interaction",
33
- ]
34
  SIN_PERIODS = (10., 26., 52., 104.)
35
  SIN_DIM = len(SIN_PERIODS) * 2
36
- TAB_DIM = len(TAB_FEATURES) + SIN_DIM # 15
37
-
38
  FUSION_DIM = 512
39
  FUSION_HEADS = 8
40
  FUSION_DEPTH = 1
41
 
42
- BLUE = "#2563EB"; GREEN = "#059669"; CORAL = "#DC2626"
43
- GOLD = "#D97706"; GRAY = "#6B7280"; BG = "#F8FAFC"
44
 
45
- # ─────────────────────────────────────────────────────────────
46
- # MODEL (exact copy from notebook)
47
- # ─────────────────────────────────────────────────────────────
48
  class SEAttentionPool(nn.Module):
49
  def __init__(self, enc_dim, reduction=16):
50
  super().__init__()
51
- self.attn = nn.Sequential(nn.Linear(enc_dim, 256), nn.Tanh(), nn.Linear(256, 1))
52
- self.se = nn.Sequential(
53
- nn.Linear(enc_dim, enc_dim // reduction), nn.ReLU(inplace=True),
54
- nn.Linear(enc_dim // reduction, enc_dim), nn.Sigmoid(),
55
- )
56
- def forward(self, feat):
57
- w = F.softmax(self.attn(feat), dim=1)
58
- p = (feat * w).sum(dim=1)
59
- return p * self.se(p)
60
-
61
 
62
  class FusionTransformer(nn.Module):
63
- def __init__(self, ct_dim, tab_dim_in,
64
- fuse_dim=FUSION_DIM, n_heads=FUSION_HEADS, depth=FUSION_DEPTH):
65
  super().__init__()
66
- self.ct_proj = nn.Linear(ct_dim, fuse_dim)
67
- self.tab_proj = nn.Linear(tab_dim_in, fuse_dim)
68
- layer = nn.TransformerDecoderLayer(
69
- d_model=fuse_dim, nhead=n_heads, dim_feedforward=fuse_dim * 4,
70
- dropout=0.1, activation="gelu", batch_first=True, norm_first=True)
71
- self.cross_attn = nn.TransformerDecoder(layer, num_layers=depth)
72
- self.norm = nn.LayerNorm(fuse_dim)
73
- def forward(self, ct_seq, tab_feat):
74
- ct_kv = self.ct_proj(ct_seq)
75
- tab_q = self.tab_proj(tab_feat).unsqueeze(1)
76
- return self.norm(self.cross_attn(tab_q, ct_kv).squeeze(1))
77
-
78
 
79
  class TrajectoryHead(nn.Module):
80
- def __init__(self, in_dim):
81
  super().__init__()
82
- self.week_proj = nn.Linear(3, 64)
83
- self.fc = nn.Sequential(
84
- nn.Linear(in_dim + 64, 512), nn.LayerNorm(512), nn.GELU(), nn.Dropout(0.20),
85
- nn.Linear(512, 256), nn.LayerNorm(256), nn.GELU(), nn.Dropout(0.15),
86
- nn.Linear(256, 3),
87
- )
88
  with torch.no_grad():
89
  self.fc[-1].weight.data.zero_()
90
- self.fc[-1].bias.data = torch.tensor([-2., 0., 5.])
91
- self.sigma_rate_fc = nn.Linear(in_dim, 1)
92
-
93
- def _week_embed(self, w):
94
- return torch.stack([torch.sin(w / 52.0),
95
- torch.cos(w / 52.0),
96
- (w / 100.0).clamp(-1, 1)], dim=-1)
97
-
98
- def forward(self, feat, base_fvc, weeks):
99
- B, T = weeks.shape
100
- sigma_rate = torch.exp(self.sigma_rate_fc(feat)).clamp(0.01, 10.0)
101
- out = self.fc(torch.cat([
102
- feat.unsqueeze(1).expand(-1, T, -1),
103
- F.gelu(self.week_proj(self._week_embed(weeks))),
104
- ], dim=-1))
105
- slope, intercept = out[..., 0:1], out[..., 1:2]
106
- sigma_base = torch.exp(out[..., 2:3]).clamp(50, 500)
107
- mu = base_fvc.view(B, 1) + intercept.squeeze(-1) + slope.squeeze(-1) * weeks
108
- sigma = (sigma_base.squeeze(-1) + sigma_rate * weeks.abs()).clamp(70, 3000)
109
- return mu, sigma
110
-
111
 
112
  class FibrosisModel2p5D(nn.Module):
113
- def __init__(self, backbone_name, pretrained=False):
114
  super().__init__()
115
- self.backbone = timm.create_model(backbone_name, pretrained=pretrained,
116
- num_classes=0, global_pool="")
117
- enc_dim = self.backbone.num_features
118
- self.gap = nn.AdaptiveAvgPool2d(1)
119
- self.se_pool = SEAttentionPool(enc_dim)
120
- self.tab_mlp = nn.Sequential(
121
- nn.Linear(TAB_DIM, 256), nn.LayerNorm(256), nn.GELU(), nn.Dropout(0.1),
122
- nn.Linear(256, 128), nn.LayerNorm(128), nn.GELU(),
123
- )
124
- self.fusion = FusionTransformer(enc_dim, 128)
125
- self.head = TrajectoryHead(FUSION_DIM)
126
-
127
- def encode_ct(self, x):
128
- B, C, D, H, W = x.shape
129
- x2d = x.permute(0, 2, 1, 3, 4).reshape(B * D, C, H, W)
130
- raw = self.backbone.forward_features(x2d)
131
- feat = (raw[:, 0] if raw.ndim == 3 else
132
- raw.mean(dim=(1, 2)) if raw.shape[-1] == self.backbone.num_features else
133
- self.gap(raw).flatten(1))
134
- return feat.view(B, D, -1)
135
-
136
- def forward(self, vol, tab, base_fvc, weeks):
137
- ct_seq = self.encode_ct(vol)
138
- fused = self.fusion(ct_seq, self.tab_mlp(tab))
139
- return self.head(fused, base_fvc, weeks)
140
-
141
-
142
- # ─────────────────────────────────────────────────────────────
143
- # LOAD CHECKPOINT + NORM STATS
144
- # ─────────────────────────────────────────────────────────────
145
  def _load_model():
146
- for name in ["swin_tiny_patch4_window7_224.ms_in1k",
147
- "swin_tiny_patch4_window7_224"]:
148
- try:
149
- m = FibrosisModel2p5D(name, pretrained=False); break
150
- except Exception:
151
- continue
152
- ckpt_path = "swintiny_fold3.pt"
153
- if os.path.exists(ckpt_path):
154
- ckpt = torch.load(ckpt_path, map_location="cpu")
155
- state = ckpt.get("model_state_dict", ckpt.get("ema_state_dict", ckpt))
156
- state = {k.replace("_orig_mod.", ""): v for k, v in state.items()}
157
- miss, unex = m.load_state_dict(state, strict=False)
158
- print(f"✅ Checkpoint loaded missing={len(miss)} unexpected={len(unex)}")
159
- else:
160
- print("⚠️ swintiny_fold3.pt not found — demo mode (random weights)")
161
  m.eval(); return m
162
 
163
-
164
  def _load_norm():
165
  if os.path.exists("norm_stats.json"):
166
- ns = json.load(open("norm_stats.json"))
167
- return (np.array(ns["t_mean"], dtype=np.float32),
168
- np.array(ns["t_std"], dtype=np.float32))
169
- return (np.array([2700., 75., 65., 0.5, 1., 0.77, 1.07], dtype=np.float32),
170
- np.array([800., 18., 9., 0.5, 0.7, 0.15, 0.20], dtype=np.float32))
171
-
172
-
173
- MODEL = _load_model()
174
- T_MEAN, T_STD = _load_norm()
175
-
176
- # ─────────────────────────────────────────────────────────────
177
- # CSV → patient data (exact same logic as prepare_features)
178
- # ─────────────────────────────────────────────────────────────
179
- def prepare_features(df: pd.DataFrame) -> pd.DataFrame:
180
- """Exact replica of the notebook's prepare_features()."""
181
- df = df.copy()
182
-
183
- # normalise column names — handle any capitalisation
184
- df.columns = [c.strip() for c in df.columns]
185
-
186
- # Sex encoding
187
- df["Sex_enc"] = (df["Sex"].str.strip() == "Male").astype(float)
188
-
189
- # Smoking encoding — handles 'Never smoked' and 'Never smoker'
190
- smoke_map = {"Never smoked": 0., "Never smoker": 0.,
191
- "Ex-smoker": 1., "Currently smokes": 2.}
192
- df["Smoking_enc"] = df["SmokingStatus"].str.strip().map(smoke_map).fillna(0.)
193
-
194
- # Baseline (minimum-week) features per patient
195
- bl_idx = df.groupby("Patient")["Weeks"].idxmin()
196
- bl_map = df.loc[bl_idx].set_index("Patient")[["FVC", "Percent", "Age"]]
197
-
198
- df["BaselineFVC"] = df["Patient"].map(bl_map["FVC"])
199
- df["BaselineWeek"] = df.groupby("Patient")["Weeks"].transform("min")
200
- df["WeekDelta"] = df["Weeks"] - df["BaselineWeek"]
201
- df["Percent"] = df["Patient"].map(bl_map["Percent"])
202
- df["Age"] = df["Patient"].map(bl_map["Age"])
203
- df["DeltaFVC"] = df["FVC"] - df["BaselineFVC"]
204
-
205
- df["PredictedFVC"] = (df["BaselineFVC"] / (df["Percent"] / 100 + 1e-6)).clip(1000, 8000)
206
- df["FVC_height_ratio"] = df["BaselineFVC"] / (df["PredictedFVC"] + 1e-6)
207
- df["percent_age_interaction"] = (df["Percent"] / 100.0) * (df["Age"] / 70.0)
208
  return df
209
 
 
 
 
 
210
 
211
- def extract_patient(df_prepared: pd.DataFrame, patient_id: str):
212
- """
213
- Return (baseline_row, all_visits_df) for the given Patient ID.
214
- baseline_row — the week-0 (earliest week) row as a Series
215
- all_visits_df — all rows for that patient sorted by WeekDelta
216
- """
217
- pat_df = df_prepared[df_prepared["Patient"] == patient_id].copy()
218
- if pat_df.empty:
219
- return None, None
220
- pat_df = pat_df.sort_values("WeekDelta").reset_index(drop=True)
221
- baseline = pat_df.iloc[0] # lowest WeekDelta = baseline visit
222
- return baseline, pat_df
223
-
224
-
225
- def detect_patient_id_from_dicoms(dicom_files) -> str | None:
226
- """
227
- Try to read the Patient ID embedded in the DICOM tags.
228
- OSIC files use PatientID tag (0010,0020).
229
- """
230
- for f in (dicom_files or []):
231
  try:
232
- ds = pydicom.dcmread(f.name if hasattr(f, "name") else f, stop_before_pixels=True)
233
- pid = str(getattr(ds, "PatientID", "")).strip()
234
- if pid:
235
- return pid
236
- except Exception:
237
- continue
238
  return None
239
 
240
-
241
- # ─────────────────────────────────────────────────────────────
242
- # CT PREPROCESSING (exact from notebook)
243
- # ─────────────────────────────────────────────────────────────
244
- def _detect_lung_extent(vol, thr=0.06):
245
- m = vol.mean(axis=(1, 2))
246
- mask = m > thr
247
- if mask.sum() < 5:
248
- return 0, vol.shape[0] - 1
249
- return int(np.argmax(mask)), int(len(mask) - np.argmax(mask[::-1]) - 1)
250
-
251
-
252
- def _adaptive_sample(vol, n=NUM_SLICES, basal=0.65):
253
- lo, hi = _detect_lung_extent(vol)
254
- mid = (lo + hi) // 2
255
- nl = int(n * basal)
256
- idx = np.concatenate([
257
- np.linspace(lo, mid - 1, n - nl).astype(int),
258
- np.linspace(mid, hi, nl).astype(int),
259
- ]).clip(0, vol.shape[0] - 1)
260
- t = torch.from_numpy(vol[idx]).unsqueeze(0).unsqueeze(0).float()
261
- t = F.interpolate(t, size=(n, IMG_SIZE, IMG_SIZE),
262
- mode="trilinear", align_corners=False)
263
  return t.squeeze(0).squeeze(0).numpy()
264
 
265
-
266
- def _build_3ch(slices):
267
- return np.stack([
268
- slices,
269
- (slices > 0.05).astype(np.float32),
270
- np.clip((slices - 0.3) * 2.0, 0, 1),
271
- ], axis=0).astype(np.float32)
272
-
273
 
274
  def load_dicoms(files):
275
- if not files:
276
- return None
277
- slices, positions = [], []
278
  for f in files:
279
  try:
280
- ds = pydicom.dcmread(f.name if hasattr(f, "name") else f)
281
- img = ds.pixel_array.astype(np.float32)
282
- img = img * float(getattr(ds, "RescaleSlope", 1)) \
283
- + float(getattr(ds, "RescaleIntercept", 0))
284
- pos = float(getattr(ds, "ImagePositionPatient", [0, 0, 0])[-1]
285
- if hasattr(ds, "ImagePositionPatient") else 0)
286
  slices.append(img); positions.append(pos)
287
- except Exception:
288
- continue
289
- if not slices:
290
- return None
291
- vol = np.stack([slices[i] for i in np.argsort(positions)])
292
- return np.clip((vol - HU_MIN) / (HU_MAX - HU_MIN), 0, 1)
293
-
294
-
295
- # ─────────────────────────────────────────────────────────────
296
- # TABULAR FEATURES (exact from notebook)
297
- # ─────────────────────────────────────────────────────────────
298
- def _sinusoidal(w):
299
- return np.array([f(w / p) for p in SIN_PERIODS
300
- for f in (math.sin, math.cos)], dtype=np.float32)
301
-
302
-
303
- def build_tabular_from_row(baseline_row, baseline_week=0.):
304
- """Build the 15-dim feature vector from a prepared baseline row."""
305
- vals = np.array([baseline_row[f] for f in TAB_FEATURES], dtype=np.float32)
306
- norm = (vals - T_MEAN) / (T_STD + 1e-6)
307
- sin = _sinusoidal(baseline_week)
308
- return np.concatenate([norm, sin]) # (15,)
309
-
310
-
311
- # ─────────────────────────────────────────────────────────────
312
- # INFERENCE
313
- # ─────────────────────────────────────────────────────────────
314
- def run_inference(baseline_row, volume, baseline_week=0.):
315
- tab_np = build_tabular_from_row(baseline_row, baseline_week)
316
- tab_t = torch.from_numpy(tab_np).unsqueeze(0)
317
- bfvc_t = torch.tensor([float(baseline_row["BaselineFVC"])], dtype=torch.float32)
318
- weeks_t = torch.arange(0, 145, dtype=torch.float32).unsqueeze(0)
319
-
320
- if volume is not None:
321
- sl = _adaptive_sample(volume)
322
- vol_t = torch.from_numpy(_build_3ch(sl)).unsqueeze(0)
323
- else:
324
- vol_t = torch.zeros(1, 3, NUM_SLICES, IMG_SIZE, IMG_SIZE)
325
-
326
  with torch.no_grad():
327
- mu, sigma = MODEL(vol_t, tab_t, bfvc_t, weeks_t)
328
- return mu.squeeze().numpy(), sigma.squeeze().numpy()
329
-
330
-
331
- # ─────────────────────────────────────────────────────────────
332
- # FVC DECLINE PLOT
333
- # ─────────────────────────────────────────────────────────────
334
- def make_fvc_plot(baseline_row, all_visits, mu, sigma):
335
- fvc_bl = float(baseline_row["BaselineFVC"])
336
- norm_fvc = float(baseline_row["PredictedFVC"])
337
- pid = str(baseline_row["Patient"])
338
- weeks = np.arange(0, 145)
339
-
340
- # actual visit data from CSV
341
- vis_wk = all_visits["WeekDelta"].values.astype(float)
342
- vis_fvc = all_visits["FVC"].values.astype(float)
343
-
344
- fig = plt.figure(figsize=(14, 7), facecolor=BG)
345
- gs = gridspec.GridSpec(2, 2, figure=fig, hspace=0.42, wspace=0.36)
346
- ax_main = fig.add_subplot(gs[:, 0])
347
- ax_bar = fig.add_subplot(gs[0, 1])
348
- ax_sev = fig.add_subplot(gs[1, 1])
349
-
350
- # ── Trajectory ──
351
- ax_main.plot(weeks, mu, color=BLUE, lw=2.5, zorder=4, label="FibrosisNet-V4 Prediction")
352
- ax_main.fill_between(weeks, mu - sigma, mu + sigma,
353
- alpha=0.22, color=BLUE, label="±1σ uncertainty")
354
- ax_main.fill_between(weeks, mu - 2*sigma, mu + 2*sigma,
355
- alpha=0.09, color=BLUE, label="±2σ uncertainty")
356
- ax_main.axhline(fvc_bl, color=GRAY, ls="--", lw=1.5,
357
- label=f"Baseline FVC {fvc_bl:.0f} ml")
358
- ax_main.axhline(fvc_bl * 0.90, color=CORAL, ls=":", lw=1.8, label="−10% threshold")
359
- ax_main.axhline(fvc_bl * 0.80, color="#7f0000", ls=":", lw=1.2, alpha=0.7, label="−20% threshold")
360
- ax_main.axhline(norm_fvc, color=GREEN, ls="-.", lw=1.2, alpha=0.7,
361
- label=f"Est. normal {norm_fvc:.0f} ml")
362
-
363
- # ── Overlay ACTUAL CSV visits ──
364
- if len(vis_wk) > 0:
365
- ax_main.scatter(vis_wk, vis_fvc, color=CORAL, s=90, zorder=7,
366
- edgecolors="black", linewidths=0.8,
367
- label="Actual FVC (from CSV)")
368
- ax_main.plot(vis_wk, vis_fvc, color=CORAL, lw=1.5, ls="--", alpha=0.7, zorder=6)
369
- for wk, fv in zip(vis_wk, vis_fvc):
370
- ax_main.annotate(f"{fv:.0f}", xy=(wk, fv),
371
- xytext=(4, 7), textcoords="offset points",
372
- fontsize=7.5, color=CORAL, fontweight="bold")
373
-
374
- ax_main.scatter([0], [fvc_bl], color="black", s=95, zorder=8)
375
- for wk, lbl in [(26, "6m"), (52, "1yr"), (78, "18m"), (104, "2yr")]:
376
- ax_main.axvline(wk, color=GRAY, ls=":", lw=0.8, alpha=0.45)
377
- ax_main.text(wk + 1, mu.min() * 0.975, lbl, fontsize=7, color=GRAY)
378
-
379
- ax_main.set_xlabel("Weeks from Baseline", fontsize=11)
380
- ax_main.set_ylabel("FVC (ml)", fontsize=11)
381
- ax_main.set_title(f"FVC Trajectory — Patient: {pid}", fontweight="bold", fontsize=11)
382
- ax_main.legend(fontsize=7.5, loc="lower left")
383
- ax_main.grid(alpha=0.22); ax_main.set_facecolor(BG)
384
-
385
- # ── Key-timepoint bars ──
386
- cps = [0, 13, 26, 52, 78, 104, 144]
387
- clabs = ["0w", "3m", "6m", "1yr", "18m", "2yr", "End"]
388
- fvc_ck = [mu[min(w, 144)] for w in cps]
389
- bcols = [GREEN if v >= fvc_bl * 0.9 else
390
- GOLD if v >= fvc_bl * 0.8 else CORAL for v in fvc_ck]
391
- bars = ax_bar.bar(clabs, fvc_ck, color=bcols, edgecolor="white", linewidth=0.6)
392
- ax_bar.axhline(fvc_bl, color=GRAY, ls="--", lw=1.2, alpha=0.8)
393
- ax_bar.axhline(fvc_bl * 0.9, color=CORAL, ls=":", lw=1.2, alpha=0.8)
394
- ax_bar.set_ylabel("FVC (ml)", fontsize=9)
395
- ax_bar.set_title("Predicted FVC at Key Timepoints", fontweight="bold", fontsize=10)
396
- ax_bar.grid(axis="y", alpha=0.2); ax_bar.set_facecolor(BG)
397
- for bar, val in zip(bars, fvc_ck):
398
- ax_bar.text(bar.get_x() + bar.get_width() / 2,
399
- bar.get_height() + 15, f"{val:.0f}",
400
- ha="center", fontsize=7, fontweight="bold")
401
-
402
- # overlay actual on bar chart
403
- if len(vis_wk) > 0:
404
- bar_x, bar_y = [], []
405
- for wk, fv in zip(vis_wk, vis_fvc):
406
- ni = int(np.argmin(np.abs(np.array(cps) - int(wk))))
407
- bar_x.append(clabs[ni]); bar_y.append(fv)
408
- ax_bar.scatter(bar_x, bar_y, color=CORAL, zorder=5, s=55,
409
- edgecolors="black", linewidths=0.7, label="Actual")
410
  ax_bar.legend(fontsize=7)
411
 
412
- # ── Severity gauge ──
413
- dec_1yr = (fvc_bl - mu[52]) / fvc_bl * 100
414
- sev_label = ("Stable / Mild" if dec_1yr < 5 else
415
- "Moderate" if dec_1yr < 10 else "Severe / Rapid")
416
- sev_col = GREEN if dec_1yr < 5 else GOLD if dec_1yr < 10 else CORAL
417
- for (lo, hi), col in [((0,5),GREEN),((5,10),GOLD),((10,20),"#f97316"),((20,30),CORAL)]:
418
- ax_sev.barh(0, hi - lo, left=lo, color=col, height=0.38, alpha=0.55)
419
- ax_sev.axvline(float(np.clip(dec_1yr, 0, 29)), color="black", lw=3.5, zorder=5)
420
- ax_sev.set_xlim(0, 30); ax_sev.set_ylim(-0.5, 0.5); ax_sev.set_yticks([])
421
- ax_sev.set_xlabel("Annual FVC Decline (%)", fontsize=9)
422
- ax_sev.set_title(f"Severity: {sev_label} ({dec_1yr:.1f}%/yr)",
423
- fontweight="bold", fontsize=10, color=sev_col)
424
- for xt, xtl in zip([0,5,10,20,30], ["0%","5%","10%","20%","30%"]):
425
- ax_sev.text(xt, -0.43, xtl, fontsize=7, ha="center", color=GRAY)
426
- ax_sev.set_facecolor(BG)
427
-
428
- age = int(baseline_row["Age"])
429
- sex = "Male" if baseline_row["Sex_enc"] == 1.0 else "Female"
430
- pct = float(baseline_row["Percent"])
431
- fig.suptitle(
432
- f"FibrosisNet-V4 | Patient: {pid} | Age {age} {sex} "
433
- f"| Baseline FVC {fvc_bl:.0f} ml | {pct:.0f}% predicted",
434
- fontsize=10, fontweight="bold", y=0.99
435
- )
436
- plt.tight_layout()
437
- return fig
438
-
439
-
440
- # ─────────────────────────────────────────────────────────────
441
- # CT VIEWER
442
- # ─────────────────────────────────────────────────────────────
443
- _CACHE: dict = {"vol": None, "df": None}
444
-
445
 
446
  def make_multiview(volume):
447
- D, H, W = volume.shape
448
- fig, axes = plt.subplots(1, 3, figsize=(13, 4.5), facecolor="black")
449
- views = [(volume[D//2], f"Axial (mid {D//2+1}/{D})"),
450
- (volume[:, H//2, :], "Coronal (mid)"),
451
- (volume[:, :, W//2], "Sagittal (mid)")]
452
- for ax, (img, ttl) in zip(axes, views):
453
- im = ax.imshow(img, cmap="bone", vmin=0, vmax=1, aspect="auto")
454
- ax.set_title(ttl, color="white", fontsize=10, pad=4); ax.axis("off")
455
- fig.colorbar(im, ax=axes[-1], fraction=0.028, pad=0.02,
456
- label="HU [0→1]").ax.yaxis.label.set_color("white")
457
- fig.suptitle("CT Lung Volume — Multi-Plane View",
458
- color="white", fontsize=12, fontweight="bold")
459
  plt.tight_layout(); return fig
460
 
461
-
462
- def _empty_plot(msg):
463
- fig, ax = plt.subplots(figsize=(7, 3))
464
- ax.text(0.5, 0.5, msg, ha="center", va="center",
465
- transform=ax.transAxes, color=GRAY, fontsize=11)
466
- ax.axis("off"); return fig
467
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
 
469
  def update_slice(idx):
470
- vol = _CACHE.get("vol")
471
- if vol is None:
472
- return _empty_plot("Upload DICOM files and run prediction first")
473
- idx = int(np.clip(idx, 0, vol.shape[0] - 1))
474
- D, H, W = vol.shape
475
- fig, axes = plt.subplots(1, 3, figsize=(13, 4.5), facecolor="black")
476
- views = [(vol[idx], f"Axial — {idx+1}/{D}"),
477
- (vol[:, H//2, :], "Coronal"),
478
- (vol[:, :, W//2], "Sagittal")]
479
- for ax, (img, ttl) in zip(axes, views):
480
- ax.imshow(img, cmap="bone", vmin=0, vmax=1, aspect="auto")
481
- ax.set_title(ttl, color="white", fontsize=10, pad=4); ax.axis("off")
482
- fig.patch.set_facecolor("black")
483
- plt.tight_layout(); return fig
484
-
485
-
486
- # ─────────────────────────────────────────────────────────────
487
- # CLINICAL REPORT
488
- # ─────────────────────────────────────────────────────────────
489
- def build_report(baseline_row, all_visits, mu, sigma):
490
- pid = str(baseline_row["Patient"])
491
- age = int(baseline_row["Age"])
492
- sex = "Male" if baseline_row["Sex_enc"] == 1.0 else "Female"
493
- smoking = {0.: "Never smoker", 1.: "Ex-smoker", 2.: "Currently smokes"}.get(
494
- float(baseline_row["Smoking_enc"]), "Unknown")
495
- fvc_bl = float(baseline_row["BaselineFVC"])
496
- pct = float(baseline_row["Percent"])
497
- norm_fvc= float(baseline_row["PredictedFVC"])
498
-
499
- fvc_6m, fvc_1yr, fvc_2yr = mu[26], mu[52], mu[104]
500
- dec_1yr = fvc_bl - fvc_1yr
501
- dec_pct = dec_1yr / fvc_bl * 100
502
- sig_1yr = sigma[52]
503
-
504
- sev = "Mild" if pct >= 70 else "Moderate" if pct >= 50 else "Severe"
505
- traj, monitor = (
506
- ("STABLE — within expected physiological variation", "every 6 months")
507
- if dec_pct < 5 else
508
- ("SLOW DECLINE — clinically meaningful progression", "every 3–4 months")
509
- if dec_pct < 10 else
510
- ("RAPID DECLINE — urgent clinical attention warranted", "monthly or as indicated")
511
- )
512
- wks10 = next((w for w in range(145) if mu[w] <= fvc_bl * 0.90), None)
513
-
514
- # Observed vs predicted table from CSV visits
515
- vis_wk = all_visits["WeekDelta"].values.astype(float)
516
- vis_fvc = all_visits["FVC"].values.astype(float)
517
- obs_section = ""
518
- if len(vis_wk) > 0:
519
- lines = [
520
- "",
521
- "OBSERVED vs PREDICTED (from uploaded CSV)",
522
- f" {'Week':>6} {'Actual FVC':>10} {'Pred FVC':>10} {'Error':>10}",
523
- " " + "─" * 44,
524
- ]
525
- errs = []
526
- for wk, afvc in zip(vis_wk, vis_fvc):
527
- wi = int(np.clip(int(wk), 0, 144))
528
- pred = mu[wi]
529
- err = afvc - pred
530
- errs.append(abs(err))
531
- lines.append(f" {int(wk):>6} {afvc:>10.0f} {pred:>10.0f} {err:>+10.0f} ml")
532
- lines.append(f"\n Mean Absolute Error: {np.mean(errs):.1f} ml")
533
- obs_section = "\n".join(lines)
534
-
535
- report = f"""
536
- ╔══════════════════════════════════════════════════════════════╗
537
- ║ FibrosisNet-V4 — Clinical Summary Report ║
538
- ╚══════════════════════════════════════════════════════════════╝
539
-
540
- PATIENT
541
- ID : {pid}
542
- Age : {age} years
543
- Sex : {sex}
544
- Smoking History : {smoking}
545
- Baseline FVC : {fvc_bl:.0f} ml ({pct:.1f}% predicted)
546
- Estimated Normal : {norm_fvc:.0f} ml (GLI-based)
547
-
548
- HOW DATA WAS EXTRACTED
549
- ✔ Clinical features auto-extracted from uploaded CSV by Patient ID
550
- ✔ Baseline = earliest week visit in the CSV for this patient
551
- ✔ Model inputs: BaselineFVC · Percent · Age · Sex · Smoking
552
- + CT (16 adaptive slices) + sinusoidal week encoding
553
- ✘ Follow-up visits: overlaid on graph for comparison, NOT model inputs
554
-
555
- SEVERITY (ATS/ERS)
556
- ► {sev.upper()} ({pct:.1f}% predicted)
557
- Mild ≥70% | Moderate 50–69% | Severe <50%
558
-
559
- PREDICTED TRAJECTORY
560
- ► {traj}
561
-
562
- Predicted FVC:
563
- 6 months : {fvc_6m:.0f} ml (−{fvc_bl - fvc_6m:.0f} ml)
564
- 1 year : {fvc_1yr:.0f} ml (−{dec_1yr:.0f} ml, {dec_pct:.1f}%/yr)
565
- 2 years : {fvc_2yr:.0f} ml (−{fvc_bl - fvc_2yr:.0f} ml cumulative)
566
- Uncertainty ±1σ at 1yr: {fvc_1yr - sig_1yr:.0f} – {fvc_1yr + sig_1yr:.0f} ml
567
- {obs_section}
568
-
569
- TIME TO 10% DECLINE
570
- {'► Week ' + str(wks10) + f' (~{wks10//4} months)' if wks10 else '► Not reached within 2.5-year horizon'}
571
-
572
- MONITORING
573
- ► Spirometry {monitor}
574
- {'► Discuss antifibrotic therapy with specialist' if sev != 'Mild' or dec_pct >= 10 else '► Continue current management plan'}
575
-
576
- PATIENT SUMMARY
577
- {"Lung function is " + sev.lower() + "ly reduced. " +
578
- (f"Predicted annual decline ~{dec_pct:.0f}%. " +
579
- ("Close monitoring recommended." if dec_pct < 10 else "Urgent specialist review needed."))
580
- if dec_pct > 3 else "Lung function appears relatively stable over the next 2 years."}
581
-
582
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
583
- ⚠ AI research model — not for clinical use without physician oversight.
584
- OOF −6.6629 | Kaggle baseline −6.6743 (beats baseline ✓)
585
- ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
586
- """.strip()
587
- return report
588
-
589
-
590
- # ─────────────────────────────────────────────────────────────
591
- # GRADIO CALLBACKS
592
- # ─────────────────────────────────────────────────────────────
593
-
594
- # Step 1 — user uploads CSV → we return patient ID list
595
  def on_csv_upload(csv_file):
596
- if csv_file is None:
597
- return gr.update(choices=[], value=None), "Upload a CSV file first."
598
  try:
599
- df_raw = pd.read_csv(csv_file.name if hasattr(csv_file, "name") else csv_file)
600
- df_raw.columns = [c.strip() for c in df_raw.columns]
601
- if "Patient" not in df_raw.columns:
602
- return gr.update(choices=[], value=None), \
603
- "❌ 'Patient' column not found in CSV."
604
- df_prep = prepare_features(df_raw)
605
- _CACHE["df"] = df_prep
606
- pids = sorted(df_prep["Patient"].unique().tolist())
607
- info = (f"✅ CSV loaded — {len(pids)} patients, "
608
- f"{len(df_raw)} rows, "
609
- f"columns: {', '.join(df_raw.columns.tolist())}")
610
- return gr.update(choices=pids, value=pids[0] if pids else None), info
611
- except Exception as e:
612
- return gr.update(choices=[], value=None), f"❌ Error reading CSV: {e}"
613
-
614
-
615
- # Step 2 — user uploads DICOMs → try auto-detect Patient ID
616
  def on_dicom_upload(dicom_files):
617
- if not dicom_files:
618
- return gr.update(), "No DICOM files uploaded."
619
- pid = detect_patient_id_from_dicoms(dicom_files)
620
- df = _CACHE.get("df")
621
  if pid and df is not None and pid in df["Patient"].values:
622
- return gr.update(value=pid), f"✅ Auto-detected Patient ID from DICOM: **{pid}**"
623
- elif pid:
624
- return gr.update(), (f"⚠️ DICOM Patient ID '{pid}' not found in the uploaded CSV. "
625
- "Please select manually from the dropdown.")
626
- return gr.update(), "ℹ️ Could not read Patient ID from DICOM tags — please select manually."
627
-
628
-
629
- # Step 3 — show patient info card when dropdown changes
630
- def on_patient_select(patient_id):
631
- df = _CACHE.get("df")
632
- if df is None or not patient_id:
633
- return "Upload a CSV first."
634
- bl, visits = extract_patient(df, patient_id)
635
- if bl is None:
636
- return f"Patient '{patient_id}' not found."
637
- sex = "Male" if bl["Sex_enc"] == 1.0 else "Female"
638
- smoking = {0.:"Never smoker", 1.:"Ex-smoker", 2.:"Currently smokes"}.get(
639
- float(bl["Smoking_enc"]), "Unknown")
640
- visit_lines = "\n".join(
641
- f" Week {int(r['WeekDelta']):>4} → FVC = {r['FVC']:.0f} ml"
642
- for _, r in visits.iterrows()
643
- )
644
- return (f"Patient : {patient_id}\n"
645
- f"Age : {int(bl['Age'])} yrs\n"
646
- f"Sex : {sex}\n"
647
- f"Smoking : {smoking}\n"
648
- f"Baseline FVC : {bl['BaselineFVC']:.0f} ml ({bl['Percent']:.1f}% predicted)\n"
649
- f"Est. normal : {bl['PredictedFVC']:.0f} ml\n\n"
650
- f"All visits in CSV:\n{visit_lines}")
651
-
652
-
653
- # Step 4 — run full inference
654
- def run_all(patient_id, dicom_files):
655
- df = _CACHE.get("df")
656
- if df is None:
657
- return (_empty_plot("Upload CSV first"),
658
- _empty_plot("Upload CSV first"),
659
- "❌ Please upload the test CSV first.")
660
- if not patient_id:
661
- return (_empty_plot("Select a patient"),
662
- _empty_plot("Select a patient"),
663
- "❌ Please select a Patient ID.")
664
-
665
- bl, visits = extract_patient(df, patient_id)
666
- if bl is None:
667
- return (_empty_plot(f"Patient {patient_id} not found"),
668
- _empty_plot(""),
669
- f"❌ Patient '{patient_id}' not in CSV.")
670
-
671
- volume = load_dicoms(dicom_files) if dicom_files else None
672
- _CACHE["vol"] = volume
673
-
674
- baseline_week = float(bl.get("BaselineWeek", 0.))
675
- mu, sigma = run_inference(bl, volume, baseline_week)
676
-
677
- fvc_plot = make_fvc_plot(bl, visits, mu, sigma)
678
- ct_view = make_multiview(volume) if volume is not None else _empty_plot("No DICOM uploaded")
679
- report = build_report(bl, visits, mu, sigma)
680
-
681
- return fvc_plot, ct_view, report
682
-
683
-
684
- # ─────────────────────────────────────────────────────────────
685
- # GRADIO UI
686
- # ─────────────────────────────────────────────────────────────
687
- css = """
688
- .gradio-container { max-width: 1280px; margin: auto; }
689
- h1 { text-align: center; color: #1e3a5f; }
690
- .mono textarea { font-family: 'Courier New', monospace; font-size: 12px; }
691
- .info { background:#f0f4ff; border-radius:8px; padding:10px; font-size:12px; }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
692
  """
693
 
694
- with gr.Blocks(title="FibrosisNet-V4", theme=gr.themes.Soft(), css=css) as demo:
695
- gr.Markdown("""
696
- # 🫁 FibrosisNet-V4
697
- ### Pulmonary Fibrosis Progression Prediction · Multi-Backbone 2.5D Deep Learning
698
- **Upload the full OSIC test CSV → select patient → upload their CT → predict**
699
- """)
700
-
701
- with gr.Row():
702
- # ── LEFT COLUMN ──
703
- with gr.Column(scale=1, min_width=330):
704
-
705
- # Step 1
706
- gr.Markdown("### Step 1 — Upload OSIC Test CSV")
707
- gr.Markdown(
708
- "Upload `test.csv` (columns: `Patient, Weeks, FVC, Percent, Age, Sex, SmokingStatus`). "
709
- "All patients' data will be parsed automatically.",
710
- elem_classes="info"
711
- )
712
- csv_file = gr.File(label="Upload test.csv", file_types=[".csv"])
713
- csv_status = gr.Textbox(label="CSV Status", lines=2, interactive=False)
714
-
715
- # Step 2
716
- gr.Markdown("### Step 2 — Upload CT DICOM Slices")
717
- gr.Markdown(
718
- "Upload the `.dcm` files for **one patient's CT scan**. "
719
- "The Patient ID will be auto-read from the DICOM tags if present.",
720
- elem_classes="info"
721
- )
722
- dicom_files = gr.File(
723
- label="Upload .dcm files (one patient's CT)",
724
- file_count="multiple",
725
- file_types=[".dcm", ".DCM"]
726
- )
727
- dicom_status = gr.Textbox(label="DICOM Status", lines=2, interactive=False)
728
-
729
- # Step 3
730
- gr.Markdown("### Step 3 — Select / Confirm Patient ID")
731
- patient_dd = gr.Dropdown(
732
- label="Patient ID",
733
- choices=[], value=None,
734
- allow_custom_value=True,
735
- info="Auto-populated from CSV. Auto-selected if DICOM tags match."
736
- )
737
- patient_info = gr.Textbox(
738
- label="Patient Data Preview",
739
- lines=12, interactive=False,
740
- elem_classes="mono"
741
- )
742
-
743
- # Step 4
744
- predict_btn = gr.Button("🔬 Run FibrosisNet Prediction",
745
- variant="primary", size="lg")
746
-
747
- # ── RIGHT COLUMN ──
748
  with gr.Column(scale=2):
749
  with gr.Tabs():
750
  with gr.Tab("📈 FVC Decline Graph"):
751
  fvc_plot = gr.Plot(label="FVC Trajectory")
752
 
753
  with gr.Tab("🫁 CT Lung Viewer"):
754
- ct_view = gr.Plot(label="Multi-plane CT View")
755
- gr.Markdown("---\n**Axial Slice Explorer** — drag to scrub through CT slices")
756
- slice_slider = gr.Slider(0, 300, value=0, step=1, label="Axial Slice Index")
757
  slice_view = gr.Plot(label="Slice Viewer")
758
- slice_slider.change(fn=update_slice, inputs=slice_slider, outputs=slice_view)
759
 
760
  with gr.Tab("📄 Clinical Report"):
761
- report_box = gr.Textbox(label="Clinical Report",
762
- lines=38, max_lines=55,
763
- elem_classes="mono")
764
-
765
- # ── Wiring ──
766
- csv_file.upload(
767
- fn=on_csv_upload,
768
- inputs=csv_file,
769
- outputs=[patient_dd, csv_status]
770
- )
771
- dicom_files.upload(
772
- fn=on_dicom_upload,
773
- inputs=dicom_files,
774
- outputs=[patient_dd, dicom_status]
775
- )
776
- patient_dd.change(
777
- fn=on_patient_select,
778
- inputs=patient_dd,
779
- outputs=patient_info
780
- )
781
- predict_btn.click(
782
- fn=run_all,
783
- inputs=[patient_dd, dicom_files],
784
- outputs=[fvc_plot, ct_view, report_box]
785
- )
786
-
787
- gr.Markdown("""
788
- ---
789
- **CSV format:** `Patient, Weeks, FVC, Percent, Age, Sex, SmokingStatus`
790
- **Model inputs:** Baseline (week-min) FVC · %Predicted · Age · Sex · Smoking + CT + sinusoidal encoding
791
- **Follow-up visits:** plotted on graph for comparison — not model inputs
792
- **Architecture:** Swin-Tiny 2.5D · SE Attention · Cross-Attention Fusion · Trajectory Head
793
- **Performance:** OOF −6.6629 beats Kaggle baseline −6.6743 ✓
794
- ⚠️ *Research prototype — not for clinical use without physician oversight.*
795
- """)
796
-
797
- demo.launch(server_name="0.0.0.0", server_port=7860)
 
1
  """
2
+ FibrosisNet-V4 — Redesigned Gradio App
3
+ Clean 4-step layout · DICOM upload collapsed at bottom · PDF report download
 
4
  """
5
 
6
+ import os, json, warnings, math, io, datetime
7
  import numpy as np
8
  import pandas as pd
9
  import gradio as gr
 
19
 
20
  warnings.filterwarnings("ignore")
21
 
22
+ try:
23
+ from reportlab.lib.pagesizes import A4
24
+ from reportlab.lib import colors
25
+ from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
26
+ from reportlab.lib.units import cm
27
+ from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer,
28
+ Table, TableStyle, HRFlowable, Image as RLImage)
29
+ from reportlab.lib.enums import TA_CENTER, TA_LEFT
30
+ PDF_OK = True
31
+ except ImportError:
32
+ PDF_OK = False
33
+
34
  IMG_SIZE = 224
35
  NUM_SLICES = 16
36
  HU_MIN, HU_MAX = -1000, 400
37
+ TAB_FEATURES = ["BaselineFVC","Percent","Age","Sex_enc","Smoking_enc",
38
+ "FVC_height_ratio","percent_age_interaction"]
 
 
 
39
  SIN_PERIODS = (10., 26., 52., 104.)
40
  SIN_DIM = len(SIN_PERIODS) * 2
41
+ TAB_DIM = len(TAB_FEATURES) + SIN_DIM
 
42
  FUSION_DIM = 512
43
  FUSION_HEADS = 8
44
  FUSION_DEPTH = 1
45
 
46
+ C_NAVY="#0F2544"; C_BLUE="#1D6FA4"; C_TEAL="#0D9488"; C_GREEN="#059669"
47
+ C_AMBER="#D97706"; C_RED="#DC2626"; C_GRAY="#6B7280"; C_BG="#FAFBFD"
48
 
49
+ # ── Model ─────────────────────────────────────────────────────
 
 
50
  class SEAttentionPool(nn.Module):
51
  def __init__(self, enc_dim, reduction=16):
52
  super().__init__()
53
+ self.attn = nn.Sequential(nn.Linear(enc_dim,256),nn.Tanh(),nn.Linear(256,1))
54
+ self.se = nn.Sequential(nn.Linear(enc_dim,enc_dim//reduction),nn.ReLU(inplace=True),
55
+ nn.Linear(enc_dim//reduction,enc_dim),nn.Sigmoid())
56
+ def forward(self,feat):
57
+ w=F.softmax(self.attn(feat),dim=1); p=(feat*w).sum(dim=1)
58
+ return p*self.se(p)
 
 
 
 
59
 
60
  class FusionTransformer(nn.Module):
61
+ def __init__(self,ct_dim,tab_dim_in,fuse_dim=FUSION_DIM,n_heads=FUSION_HEADS,depth=FUSION_DEPTH):
 
62
  super().__init__()
63
+ self.ct_proj=nn.Linear(ct_dim,fuse_dim); self.tab_proj=nn.Linear(tab_dim_in,fuse_dim)
64
+ layer=nn.TransformerDecoderLayer(d_model=fuse_dim,nhead=n_heads,
65
+ dim_feedforward=fuse_dim*4,dropout=0.1,activation="gelu",
66
+ batch_first=True,norm_first=True)
67
+ self.cross_attn=nn.TransformerDecoder(layer,num_layers=depth)
68
+ self.norm=nn.LayerNorm(fuse_dim)
69
+ def forward(self,ct_seq,tab_feat):
70
+ return self.norm(self.cross_attn(self.tab_proj(tab_feat).unsqueeze(1),
71
+ self.ct_proj(ct_seq)).squeeze(1))
 
 
 
72
 
73
  class TrajectoryHead(nn.Module):
74
+ def __init__(self,in_dim):
75
  super().__init__()
76
+ self.week_proj=nn.Linear(3,64)
77
+ self.fc=nn.Sequential(nn.Linear(in_dim+64,512),nn.LayerNorm(512),nn.GELU(),nn.Dropout(0.20),
78
+ nn.Linear(512,256),nn.LayerNorm(256),nn.GELU(),nn.Dropout(0.15),
79
+ nn.Linear(256,3))
 
 
80
  with torch.no_grad():
81
  self.fc[-1].weight.data.zero_()
82
+ self.fc[-1].bias.data=torch.tensor([-2.,0.,5.])
83
+ self.sigma_rate_fc=nn.Linear(in_dim,1)
84
+ def _emb(self,w):
85
+ return torch.stack([torch.sin(w/52.),torch.cos(w/52.),(w/100.).clamp(-1,1)],dim=-1)
86
+ def forward(self,feat,base_fvc,weeks):
87
+ B,T=weeks.shape
88
+ sr=torch.exp(self.sigma_rate_fc(feat)).clamp(0.01,10.)
89
+ out=self.fc(torch.cat([feat.unsqueeze(1).expand(-1,T,-1),
90
+ F.gelu(self.week_proj(self._emb(weeks)))],dim=-1))
91
+ mu=(base_fvc.view(B,1)+out[...,1:2].squeeze(-1)+out[...,0:1].squeeze(-1)*weeks)
92
+ sigma=(torch.exp(out[...,2:3]).clamp(50,500).squeeze(-1)+sr*weeks.abs()).clamp(70,3000)
93
+ return mu,sigma
 
 
 
 
 
 
 
 
 
94
 
95
  class FibrosisModel2p5D(nn.Module):
96
+ def __init__(self,backbone_name,pretrained=False):
97
  super().__init__()
98
+ self.backbone=timm.create_model(backbone_name,pretrained=pretrained,num_classes=0,global_pool="")
99
+ enc_dim=self.backbone.num_features
100
+ self.gap=nn.AdaptiveAvgPool2d(1); self.se_pool=SEAttentionPool(enc_dim)
101
+ self.tab_mlp=nn.Sequential(nn.Linear(TAB_DIM,256),nn.LayerNorm(256),nn.GELU(),nn.Dropout(0.1),
102
+ nn.Linear(256,128),nn.LayerNorm(128),nn.GELU())
103
+ self.fusion=FusionTransformer(enc_dim,128); self.head=TrajectoryHead(FUSION_DIM)
104
+ def encode_ct(self,x):
105
+ B,C,D,H,W=x.shape; x2d=x.permute(0,2,1,3,4).reshape(B*D,C,H,W)
106
+ raw=self.backbone.forward_features(x2d)
107
+ feat=(raw[:,0] if raw.ndim==3 else
108
+ raw.mean(dim=(1,2)) if raw.shape[-1]==self.backbone.num_features else
109
+ self.gap(raw).flatten(1))
110
+ return feat.view(B,D,-1)
111
+ def forward(self,vol,tab,base_fvc,weeks):
112
+ return self.head(self.fusion(self.encode_ct(vol),self.tab_mlp(tab)),base_fvc,weeks)
113
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  def _load_model():
115
+ for name in ["swin_tiny_patch4_window7_224.ms_in1k","swin_tiny_patch4_window7_224"]:
116
+ try: m=FibrosisModel2p5D(name,pretrained=False); break
117
+ except: continue
118
+ if os.path.exists("swintiny_fold3.pt"):
119
+ ckpt=torch.load("swintiny_fold3.pt",map_location="cpu")
120
+ state=ckpt.get("model_state_dict",ckpt.get("ema_state_dict",ckpt))
121
+ state={k.replace("_orig_mod.",""):v for k,v in state.items()}
122
+ miss,unex=m.load_state_dict(state,strict=False)
123
+ print(f"Loaded | missing={len(miss)} unexpected={len(unex)}")
124
+ else: print("swintiny_fold3.pt not found — demo mode")
 
 
 
 
 
125
  m.eval(); return m
126
 
 
127
  def _load_norm():
128
  if os.path.exists("norm_stats.json"):
129
+ ns=json.load(open("norm_stats.json"))
130
+ return np.array(ns["t_mean"],dtype=np.float32),np.array(ns["t_std"],dtype=np.float32)
131
+ return (np.array([2700.,75.,65.,0.5,1.,0.77,1.07],dtype=np.float32),
132
+ np.array([800.,18.,9.,0.5,0.7,0.15,0.20],dtype=np.float32))
133
+
134
+ MODEL=_load_model(); T_MEAN,T_STD=_load_norm()
135
+
136
+ # ── Data ──────────────────────────────────────────────────────
137
+ def prepare_features(df):
138
+ df=df.copy(); df.columns=[c.strip() for c in df.columns]
139
+ df["Sex_enc"]=(df["Sex"].str.strip()=="Male").astype(float)
140
+ df["Smoking_enc"]=df["SmokingStatus"].str.strip().map(
141
+ {"Never smoked":0.,"Never smoker":0.,"Ex-smoker":1.,"Currently smokes":2.}).fillna(0.)
142
+ bl_idx=df.groupby("Patient")["Weeks"].idxmin()
143
+ bl_map=df.loc[bl_idx].set_index("Patient")[["FVC","Percent","Age"]]
144
+ df["BaselineFVC"]=df["Patient"].map(bl_map["FVC"])
145
+ df["BaselineWeek"]=df.groupby("Patient")["Weeks"].transform("min")
146
+ df["WeekDelta"]=df["Weeks"]-df["BaselineWeek"]
147
+ df["Percent"]=df["Patient"].map(bl_map["Percent"])
148
+ df["Age"]=df["Patient"].map(bl_map["Age"])
149
+ df["DeltaFVC"]=df["FVC"]-df["BaselineFVC"]
150
+ df["PredictedFVC"]=(df["BaselineFVC"]/(df["Percent"]/100+1e-6)).clip(1000,8000)
151
+ df["FVC_height_ratio"]=df["BaselineFVC"]/(df["PredictedFVC"]+1e-6)
152
+ df["percent_age_interaction"]=(df["Percent"]/100.)*(df["Age"]/70.)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
  return df
154
 
155
+ def extract_patient(df,pid):
156
+ pat=df[df["Patient"]==pid].sort_values("WeekDelta").reset_index(drop=True)
157
+ if pat.empty: return None,None
158
+ return pat.iloc[0],pat
159
 
160
+ def detect_pid(files):
161
+ for f in (files or []):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
162
  try:
163
+ ds=pydicom.dcmread(f.name if hasattr(f,"name") else f,stop_before_pixels=True)
164
+ pid=str(getattr(ds,"PatientID","")).strip()
165
+ if pid: return pid
166
+ except: continue
 
 
167
  return None
168
 
169
+ # ── CT ────────────────────────────────────────────────────────
170
+ def _extent(vol,thr=0.06):
171
+ m=vol.mean(axis=(1,2)); mask=m>thr
172
+ if mask.sum()<5: return 0,vol.shape[0]-1
173
+ return int(np.argmax(mask)),int(len(mask)-np.argmax(mask[::-1])-1)
174
+
175
+ def _sample(vol,n=NUM_SLICES,basal=0.65):
176
+ lo,hi=_extent(vol); mid=(lo+hi)//2; nl=int(n*basal)
177
+ idx=np.concatenate([np.linspace(lo,mid-1,n-nl).astype(int),
178
+ np.linspace(mid,hi,nl).astype(int)]).clip(0,vol.shape[0]-1)
179
+ t=torch.from_numpy(vol[idx]).unsqueeze(0).unsqueeze(0).float()
180
+ t=F.interpolate(t,size=(n,IMG_SIZE,IMG_SIZE),mode="trilinear",align_corners=False)
 
 
 
 
 
 
 
 
 
 
 
181
  return t.squeeze(0).squeeze(0).numpy()
182
 
183
+ def _3ch(sl):
184
+ return np.stack([sl,(sl>0.05).astype(np.float32),np.clip((sl-0.3)*2.,0,1)],axis=0).astype(np.float32)
 
 
 
 
 
 
185
 
186
  def load_dicoms(files):
187
+ if not files: return None
188
+ slices,positions=[],[]
 
189
  for f in files:
190
  try:
191
+ ds=pydicom.dcmread(f.name if hasattr(f,"name") else f)
192
+ img=ds.pixel_array.astype(np.float32)
193
+ img=img*float(getattr(ds,"RescaleSlope",1))+float(getattr(ds,"RescaleIntercept",0))
194
+ pos=float(getattr(ds,"ImagePositionPatient",[0,0,0])[-1] if hasattr(ds,"ImagePositionPatient") else 0)
 
 
195
  slices.append(img); positions.append(pos)
196
+ except: continue
197
+ if not slices: return None
198
+ vol=np.stack([slices[i] for i in np.argsort(positions)])
199
+ return np.clip((vol-HU_MIN)/(HU_MAX-HU_MIN),0,1)
200
+
201
+ # ── Features / Inference ──────────────────────────────────────
202
+ def _sin(w):
203
+ return np.array([f(w/p) for p in SIN_PERIODS for f in (math.sin,math.cos)],dtype=np.float32)
204
+
205
+ def build_tab(bl,bw=0.):
206
+ vals=np.array([bl[f] for f in TAB_FEATURES],dtype=np.float32)
207
+ return np.concatenate([(vals-T_MEAN)/(T_STD+1e-6),_sin(bw)])
208
+
209
+ def run_inference(bl,volume,bw=0.):
210
+ tab_t=torch.from_numpy(build_tab(bl,bw)).unsqueeze(0)
211
+ bfvc_t=torch.tensor([float(bl["BaselineFVC"])],dtype=torch.float32)
212
+ weeks_t=torch.arange(0,145,dtype=torch.float32).unsqueeze(0)
213
+ vol_t=(torch.from_numpy(_3ch(_sample(volume))).unsqueeze(0) if volume is not None
214
+ else torch.zeros(1,3,NUM_SLICES,IMG_SIZE,IMG_SIZE))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  with torch.no_grad():
216
+ mu,sigma=MODEL(vol_t,tab_t,bfvc_t,weeks_t)
217
+ return mu.squeeze().numpy(),sigma.squeeze().numpy()
218
+
219
+ # ── Plots ──────────────────────────────────────────────────────
220
+ def _empty(msg=""):
221
+ fig,ax=plt.subplots(figsize=(7,3),facecolor=C_BG)
222
+ ax.text(0.5,0.5,msg,ha="center",va="center",transform=ax.transAxes,
223
+ color=C_GRAY,fontsize=11,style="italic")
224
+ ax.set_facecolor(C_BG); ax.axis("off"); return fig
225
+
226
+ def make_fvc_plot(bl,visits,mu,sigma):
227
+ fvc_bl=float(bl["BaselineFVC"]); norm_fvc=float(bl["PredictedFVC"])
228
+ pid=str(bl["Patient"]); weeks=np.arange(0,145)
229
+ vis_wk=visits["WeekDelta"].values.astype(float)
230
+ vis_fvc=visits["FVC"].values.astype(float)
231
+ dec_1yr=(fvc_bl-mu[52])/fvc_bl*100
232
+
233
+ fig=plt.figure(figsize=(15,7),facecolor=C_BG)
234
+ gs=gridspec.GridSpec(2,3,figure=fig,hspace=0.45,wspace=0.38)
235
+ ax_main=fig.add_subplot(gs[:,0:2]); ax_bar=fig.add_subplot(gs[0,2]); ax_sev=fig.add_subplot(gs[1,2])
236
+
237
+ ax_main.set_facecolor(C_BG)
238
+ ax_main.fill_between(weeks,mu-2*sigma,mu+2*sigma,alpha=0.07,color=C_BLUE)
239
+ ax_main.fill_between(weeks,mu-sigma,mu+sigma,alpha=0.18,color=C_BLUE,label="±1σ confidence")
240
+ ax_main.plot(weeks,mu,color=C_BLUE,lw=2.8,zorder=4,label="FibrosisNet-V4 Prediction")
241
+ ax_main.axhline(fvc_bl,color=C_GRAY,ls="--",lw=1.6,alpha=0.8,label=f"Baseline {fvc_bl:.0f} ml")
242
+ ax_main.axhline(fvc_bl*0.90,color=C_AMBER,ls=":",lw=2.0,label="-10% threshold")
243
+ ax_main.axhline(fvc_bl*0.80,color=C_RED,ls=":",lw=1.4,alpha=0.7,label="-20% threshold")
244
+ ax_main.axhline(norm_fvc,color=C_TEAL,ls="-.",lw=1.3,alpha=0.75,label=f"Est. normal {norm_fvc:.0f} ml")
245
+ if len(vis_wk)>0:
246
+ ax_main.plot(vis_wk,vis_fvc,color=C_RED,lw=1.8,ls="--",alpha=0.8,zorder=6)
247
+ ax_main.scatter(vis_wk,vis_fvc,color=C_RED,s=100,zorder=7,edgecolors="white",lw=1.5,label="Actual FVC (CSV)")
248
+ for wk,fv in zip(vis_wk,vis_fvc):
249
+ ax_main.annotate(f"{fv:.0f}",xy=(wk,fv),xytext=(5,8),textcoords="offset points",
250
+ fontsize=8,color=C_RED,fontweight="bold")
251
+ ax_main.scatter([0],[fvc_bl],color=C_NAVY,s=110,zorder=8,edgecolors="white",lw=1.5)
252
+ for wk,lbl in [(26,"6mo"),(52,"1yr"),(78,"18mo"),(104,"2yr")]:
253
+ ax_main.axvline(wk,color=C_GRAY,ls=":",lw=0.8,alpha=0.4)
254
+ ax_main.text(wk+1,mu.min()*0.976,lbl,fontsize=7.5,color=C_GRAY)
255
+ ax_main.set_xlabel("Weeks from Baseline",fontsize=11,color=C_NAVY,labelpad=6)
256
+ ax_main.set_ylabel("Forced Vital Capacity (ml)",fontsize=11,color=C_NAVY,labelpad=6)
257
+ ax_main.set_title(f"FVC Decline Trajectory · Patient: {pid}",
258
+ fontsize=13,fontweight="bold",color=C_NAVY,pad=10)
259
+ ax_main.legend(fontsize=8,loc="lower left",framealpha=0.9,edgecolor="#DDE3EC",fancybox=True)
260
+ ax_main.grid(alpha=0.18,color=C_GRAY); ax_main.tick_params(colors=C_GRAY)
261
+ for sp in ax_main.spines.values(): sp.set_edgecolor("#DDE3EC")
262
+
263
+ cps=[0,13,26,52,78,104,144]; clabs=["0w","3m","6m","1yr","18m","2yr","End"]
264
+ fvc_ck=[mu[min(w,144)] for w in cps]
265
+ bcols=[C_GREEN if v>=fvc_bl*0.9 else C_AMBER if v>=fvc_bl*0.8 else C_RED for v in fvc_ck]
266
+ bars=ax_bar.bar(clabs,fvc_ck,color=bcols,edgecolor="white",lw=0.8,width=0.65)
267
+ ax_bar.axhline(fvc_bl,color=C_GRAY,ls="--",lw=1.2,alpha=0.7)
268
+ ax_bar.axhline(fvc_bl*0.9,color=C_AMBER,ls=":",lw=1.2,alpha=0.7)
269
+ ax_bar.set_ylabel("FVC (ml)",fontsize=9,color=C_NAVY)
270
+ ax_bar.set_title("Key Timepoints",fontweight="bold",fontsize=10,color=C_NAVY)
271
+ ax_bar.set_facecolor(C_BG); ax_bar.grid(axis="y",alpha=0.18)
272
+ ax_bar.tick_params(axis="x",labelsize=8,colors=C_GRAY); ax_bar.tick_params(axis="y",colors=C_GRAY)
273
+ for sp in ax_bar.spines.values(): sp.set_edgecolor("#DDE3EC")
274
+ for bar,val in zip(bars,fvc_ck):
275
+ ax_bar.text(bar.get_x()+bar.get_width()/2,bar.get_height()+12,
276
+ f"{val:.0f}",ha="center",fontsize=6.5,fontweight="bold",color=C_NAVY)
277
+ if len(vis_wk)>0:
278
+ bx,by=[],[]
279
+ for wk,fv in zip(vis_wk,vis_fvc):
280
+ ni=int(np.argmin(np.abs(np.array(cps)-int(wk)))); bx.append(clabs[ni]); by.append(fv)
281
+ ax_bar.scatter(bx,by,color=C_RED,zorder=5,s=50,edgecolors="white",lw=1,label="Actual")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
282
  ax_bar.legend(fontsize=7)
283
 
284
+ sev_label=("Stable / Mild" if dec_1yr<5 else "Moderate" if dec_1yr<10 else "Severe / Rapid")
285
+ sev_col=C_GREEN if dec_1yr<5 else C_AMBER if dec_1yr<10 else C_RED
286
+ for (lo,hi),col in [((0,5),C_GREEN),((5,10),C_AMBER),((10,20),"#f97316"),((20,30),C_RED)]:
287
+ ax_sev.barh(0,hi-lo,left=lo,color=col,height=0.45,alpha=0.60)
288
+ mx=float(np.clip(dec_1yr,0,29))
289
+ ax_sev.axvline(mx,color=C_NAVY,lw=4,zorder=5)
290
+ ax_sev.scatter([mx],[0],color="white",s=80,zorder=6,edgecolors=C_NAVY,lw=2)
291
+ ax_sev.set_xlim(0,30); ax_sev.set_ylim(-0.6,0.6); ax_sev.set_yticks([])
292
+ ax_sev.set_xlabel("Annual FVC Decline (%)",fontsize=9,color=C_NAVY)
293
+ ax_sev.set_title(f"{sev_label}\n{dec_1yr:.1f}%/year",fontweight="bold",fontsize=10,color=sev_col,pad=6)
294
+ for xt,xtl in zip([0,5,10,20,30],["0%","5%","10%","20%","30%"]):
295
+ ax_sev.text(xt,-0.50,xtl,fontsize=7,ha="center",color=C_GRAY)
296
+ ax_sev.set_facecolor(C_BG)
297
+ for sp in ax_sev.spines.values(): sp.set_edgecolor("#DDE3EC")
298
+
299
+ age=int(bl["Age"]); sex="Male" if bl["Sex_enc"]==1. else "Female"
300
+ fig.suptitle(f"FibrosisNet-V4 · Age {age} {sex} · Baseline FVC {fvc_bl:.0f} ml · {float(bl['Percent']):.0f}% predicted",
301
+ fontsize=10.5,color=C_NAVY,y=1.00,fontweight="bold")
302
+ plt.tight_layout(); return fig
 
 
 
 
 
 
 
 
 
 
 
 
 
 
303
 
304
  def make_multiview(volume):
305
+ D,H,W=volume.shape
306
+ fig,axes=plt.subplots(1,3,figsize=(14,4.8),facecolor="#0A1628")
307
+ views=[(volume[D//2],f"Axial (mid {D//2+1}/{D})"),(volume[:,H//2,:],"Coronal (mid)"),(volume[:,:,W//2],"Sagittal (mid)")]
308
+ for ax,(img,ttl) in zip(axes,views):
309
+ im=ax.imshow(img,cmap="bone",vmin=0,vmax=1,aspect="auto")
310
+ ax.set_title(ttl,color="#8BBFD4",fontsize=10.5,pad=6,fontweight="bold"); ax.axis("off")
311
+ cb=fig.colorbar(im,ax=axes[-1],fraction=0.028,pad=0.02)
312
+ cb.set_label("HU Normalized [0-1]",color="#8BBFD4",fontsize=8)
313
+ plt.setp(cb.ax.yaxis.get_ticklabels(),color="#8BBFD4")
314
+ fig.suptitle("CT Lung Volume — Multi-Plane View",color="white",fontsize=12,fontweight="bold",y=1.01)
 
 
315
  plt.tight_layout(); return fig
316
 
317
+ # ── PDF ────────────────────────────────────────────────────────
318
+ def generate_pdf(bl,visits,mu,sigma,fvc_fig):
319
+ if not PDF_OK: return None
320
+ buf=io.BytesIO()
321
+ doc=SimpleDocTemplate(buf,pagesize=A4,leftMargin=2*cm,rightMargin=2*cm,topMargin=2*cm,bottomMargin=2*cm)
322
+ W_PAGE=A4[0]-4*cm; styles=getSampleStyleSheet()
323
+ def S(name,**kw):
324
+ base=kw.pop("parent","Normal")
325
+ return ParagraphStyle(name,parent=styles[base],**kw)
326
+ sTitle=S("sTitle",fontSize=22,textColor=colors.HexColor(C_NAVY),fontName="Helvetica-Bold",spaceAfter=4,alignment=TA_CENTER)
327
+ sSub=S("sSub",fontSize=10,textColor=colors.HexColor(C_BLUE),fontName="Helvetica",spaceAfter=12,alignment=TA_CENTER)
328
+ sH1=S("sH1",fontSize=13,textColor=colors.HexColor(C_NAVY),fontName="Helvetica-Bold",spaceBefore=14,spaceAfter=5)
329
+ sNorm=S("sNorm",fontSize=9.5,textColor=colors.HexColor("#374151"),fontName="Helvetica",spaceAfter=4,leading=14)
330
+ sWarn=S("sWarn",fontSize=8,textColor=colors.HexColor("#92400E"),fontName="Helvetica-Oblique",alignment=TA_CENTER)
331
+ sFooter=S("sFooter",fontSize=7.5,textColor=colors.HexColor(C_GRAY),fontName="Helvetica",alignment=TA_CENTER)
332
+
333
+ pid=str(bl["Patient"]); age=int(bl["Age"])
334
+ sex="Male" if bl["Sex_enc"]==1. else "Female"
335
+ smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
336
+ fvc_bl=float(bl["BaselineFVC"]); pct=float(bl["Percent"]); norm=float(bl["PredictedFVC"])
337
+ fvc_6m=mu[26]; fvc_1yr=mu[52]; fvc_2yr=mu[104]
338
+ dec_pct=(fvc_bl-fvc_1yr)/fvc_bl*100; sig_1yr=sigma[52]
339
+ sev="Mild" if pct>=70 else "Moderate" if pct>=50 else "Severe"
340
+ sev_hex=C_GREEN if sev=="Mild" else C_AMBER if sev=="Moderate" else C_RED
341
+ traj,monitor=(("STABLE","every 6 months") if dec_pct<5 else
342
+ ("SLOW DECLINE","every 3-4 months") if dec_pct<10 else
343
+ ("RAPID DECLINE","monthly"))
344
+ wks10=next((w for w in range(145) if mu[w]<=fvc_bl*0.90),None)
345
+ vis_wk=visits["WeekDelta"].values.astype(float); vis_fvc=visits["FVC"].values.astype(float)
346
+
347
+ story=[]
348
+ story.append(Paragraph("FibrosisNet-V4",sTitle))
349
+ story.append(Paragraph("Pulmonary Fibrosis Progression Report",sSub))
350
+ story.append(Paragraph(f"Generated: {datetime.datetime.now().strftime('%d %B %Y, %H:%M')} | Model: Swin-Tiny 2.5D | OOF: -6.6629",sSub))
351
+ story.append(HRFlowable(width="100%",thickness=2,color=colors.HexColor(C_NAVY),spaceAfter=14))
352
+
353
+ story.append(Paragraph("Patient Profile",sH1))
354
+ pat_data=[["Patient ID",pid,"Age",f"{age} years"],["Sex",sex,"Smoking",smoking],
355
+ ["Baseline FVC",f"{fvc_bl:.0f} ml","% Predicted",f"{pct:.1f}%"],
356
+ ["Est. Normal FVC",f"{norm:.0f} ml","Model Input","Baseline visit only"]]
357
+ pt=Table(pat_data,colWidths=[3.2*cm,5.8*cm,3.2*cm,5.8*cm])
358
+ pt.setStyle(TableStyle([
359
+ ("BACKGROUND",(0,0),(-1,-1),colors.HexColor("#F8FAFC")),
360
+ ("BACKGROUND",(0,0),(0,-1),colors.HexColor("#E8EEF7")),
361
+ ("BACKGROUND",(2,0),(2,-1),colors.HexColor("#E8EEF7")),
362
+ ("FONTNAME",(0,0),(0,-1),"Helvetica-Bold"),("FONTNAME",(2,0),(2,-1),"Helvetica-Bold"),
363
+ ("FONTSIZE",(0,0),(-1,-1),9),
364
+ ("TEXTCOLOR",(0,0),(0,-1),colors.HexColor(C_NAVY)),("TEXTCOLOR",(2,0),(2,-1),colors.HexColor(C_NAVY)),
365
+ ("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#DDE3EC")),
366
+ ("ROWBACKGROUNDS",(0,0),(-1,-1),[colors.HexColor("#F8FAFC"),colors.HexColor("#F1F5F9")]),
367
+ ("TOPPADDING",(0,0),(-1,-1),5),("BOTTOMPADDING",(0,0),(-1,-1),5),("LEFTPADDING",(0,0),(-1,-1),8)]))
368
+ story.append(pt); story.append(Spacer(1,10))
369
+
370
+ story.append(Paragraph("Severity Assessment",sH1))
371
+ sv_data=[[f"ATS/ERS: {sev.upper()}",f"{pct:.1f}% predicted FVC","Mild >=70% | Moderate 50-69% | Severe <50%"]]
372
+ st=Table(sv_data,colWidths=[W_PAGE/3]*3)
373
+ st.setStyle(TableStyle([
374
+ ("BACKGROUND",(0,0),(-1,-1),colors.HexColor(sev_hex+"33" if len(sev_hex)==7 else "#05966933")),
375
+ ("FONTNAME",(0,0),(0,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,-1),9),
376
+ ("TEXTCOLOR",(0,0),(0,0),colors.HexColor(sev_hex)),("TEXTCOLOR",(1,0),(2,0),colors.HexColor("#374151")),
377
+ ("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#DDE3EC")),
378
+ ("TOPPADDING",(0,0),(-1,-1),7),("BOTTOMPADDING",(0,0),(-1,-1),7),
379
+ ("LEFTPADDING",(0,0),(-1,-1),8),("ALIGN",(0,0),(-1,-1),"CENTER")]))
380
+ story.append(st); story.append(Spacer(1,6))
381
+ story.append(Paragraph(f"<b>Trajectory:</b> {traj}",sNorm))
382
+
383
+ story.append(Paragraph("Predicted FVC Trajectory",sH1))
384
+ pred_data=[["Timepoint","Predicted FVC","Change","Uncertainty (1sigma)"],
385
+ ["6 months (wk 26)",f"{fvc_6m:.0f} ml",f"-{fvc_bl-fvc_6m:.0f} ml ({(fvc_bl-fvc_6m)/fvc_bl*100:.1f}%)",f"+/-{sigma[26]:.0f} ml"],
386
+ ["1 year (wk 52)",f"{fvc_1yr:.0f} ml",f"-{fvc_bl-fvc_1yr:.0f} ml ({dec_pct:.1f}%/yr)",f"+/-{sig_1yr:.0f} ml"],
387
+ ["2 years (wk 104)",f"{fvc_2yr:.0f} ml",f"-{fvc_bl-fvc_2yr:.0f} ml ({(fvc_bl-fvc_2yr)/fvc_bl*100:.1f}%)",f"+/-{sigma[104]:.0f} ml"]]
388
+ prt=Table(pred_data,colWidths=[W_PAGE*0.25]*4)
389
+ prt.setStyle(TableStyle([
390
+ ("BACKGROUND",(0,0),(-1,0),colors.HexColor(C_NAVY)),("TEXTCOLOR",(0,0),(-1,0),colors.white),
391
+ ("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,-1),9),
392
+ ("ROWBACKGROUNDS",(0,1),(-1,-1),[colors.HexColor("#F8FAFC"),colors.HexColor("#F1F5F9")]),
393
+ ("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#DDE3EC")),
394
+ ("TOPPADDING",(0,0),(-1,-1),5),("BOTTOMPADDING",(0,0),(-1,-1),5),
395
+ ("LEFTPADDING",(0,0),(-1,-1),8),("ALIGN",(1,1),(-1,-1),"CENTER")]))
396
+ story.append(prt); story.append(Spacer(1,6))
397
+ thr_txt=(f"Week {wks10} (~{wks10//4} months)" if wks10 else "Not reached within 2.5-year horizon")
398
+ story.append(Paragraph(f"<b>Time to 10% FVC decline:</b> {thr_txt}",sNorm))
399
+
400
+ if len(vis_wk)>0:
401
+ story.append(Paragraph("Observed vs Predicted",sH1))
402
+ obs=[["Week","Actual FVC","Predicted FVC","Error"]]
403
+ errs=[]
404
+ for wk,afvc in zip(vis_wk,vis_fvc):
405
+ wi=int(np.clip(int(wk),0,144)); pred=mu[wi]; err=afvc-pred; errs.append(abs(err))
406
+ obs.append([f"Week {int(wk)}",f"{afvc:.0f} ml",f"{pred:.0f} ml",f"{'+' if err>=0 else ''}{err:.0f} ml"])
407
+ obs.append(["","","Mean Absolute Error",f"{np.mean(errs):.1f} ml"])
408
+ ot=Table(obs,colWidths=[W_PAGE*0.25]*4)
409
+ ot.setStyle(TableStyle([
410
+ ("BACKGROUND",(0,0),(-1,0),colors.HexColor(C_BLUE)),("TEXTCOLOR",(0,0),(-1,0),colors.white),
411
+ ("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTNAME",(0,-1),(-1,-1),"Helvetica-Bold"),
412
+ ("FONTSIZE",(0,0),(-1,-1),9),
413
+ ("ROWBACKGROUNDS",(0,1),(-1,-2),[colors.HexColor("#F8FAFC"),colors.HexColor("#F1F5F9")]),
414
+ ("BACKGROUND",(0,-1),(-1,-1),colors.HexColor("#E8EEF7")),
415
+ ("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#DDE3EC")),
416
+ ("TOPPADDING",(0,0),(-1,-1),5),("BOTTOMPADDING",(0,0),(-1,-1),5),
417
+ ("LEFTPADDING",(0,0),(-1,-1),8),("ALIGN",(1,1),(-1,-1),"CENTER")]))
418
+ story.append(ot); story.append(Spacer(1,6))
419
+
420
+ story.append(Paragraph("FVC Trajectory Chart",sH1))
421
+ fig_buf=io.BytesIO(); fvc_fig.savefig(fig_buf,format="png",dpi=130,bbox_inches="tight",facecolor=C_BG)
422
+ fig_buf.seek(0)
423
+ story.append(RLImage(fig_buf,width=W_PAGE,height=W_PAGE*7/15)); story.append(Spacer(1,8))
424
+
425
+ story.append(Paragraph("Clinical Recommendations",sH1))
426
+ for r in [f"Spirometry monitoring: <b>{monitor}</b>",
427
+ "6-minute walk test at each follow-up visit",
428
+ ("Discuss antifibrotic therapy (nintedanib / pirfenidone) with pulmonologist"
429
+ if sev!="Mild" or dec_pct>=10 else "Continue current management plan")]:
430
+ story.append(Paragraph(f"- {r}",sNorm))
431
+
432
+ story.append(Spacer(1,14))
433
+ story.append(HRFlowable(width="100%",thickness=1,color=colors.HexColor("#DDE3EC"),spaceAfter=8))
434
+ story.append(Paragraph(
435
+ "This report is generated by an AI research model (FibrosisNet-V4) for research purposes only. "
436
+ "It must not replace clinical diagnosis or treatment decisions without a qualified pulmonologist's review.",sWarn))
437
+ story.append(Spacer(1,4))
438
+ story.append(Paragraph(f"FibrosisNet-V4 | Swin-Tiny 2.5D | OOF -6.6629 vs Kaggle baseline -6.6743 | Balaji R, NIT Calicut, May 2026",sFooter))
439
+ doc.build(story); buf.seek(0); return buf.getvalue()
440
+
441
+ # ── Slice viewer ───────────────────────────────────────────────
442
+ _CACHE={"vol":None,"df":None,"last_fig":None,"last_bl":None,"last_visits":None,"last_mu":None,"last_sigma":None}
443
 
444
  def update_slice(idx):
445
+ vol=_CACHE.get("vol")
446
+ if vol is None: return _empty("Upload DICOM files and run prediction first")
447
+ idx=int(np.clip(idx,0,vol.shape[0]-1)); D,H,W=vol.shape
448
+ fig,axes=plt.subplots(1,3,figsize=(14,4.8),facecolor="#0A1628")
449
+ for ax,(img,ttl) in zip(axes,[(vol[idx],f"Axial {idx+1}/{D}"),(vol[:,H//2,:],"Coronal"),(vol[:,:,W//2],"Sagittal")]):
450
+ ax.imshow(img,cmap="bone",vmin=0,vmax=1,aspect="auto")
451
+ ax.set_title(ttl,color="#8BBFD4",fontsize=10,pad=4,fontweight="bold"); ax.axis("off")
452
+ fig.patch.set_facecolor("#0A1628"); plt.tight_layout(); return fig
453
+
454
+ # ── Callbacks ──────────────────────────────────────────────────
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
455
  def on_csv_upload(csv_file):
456
+ if csv_file is None: return gr.update(choices=[],value=None),"Upload a CSV file first."
 
457
  try:
458
+ df_raw=pd.read_csv(csv_file.name if hasattr(csv_file,"name") else csv_file)
459
+ df_raw.columns=[c.strip() for c in df_raw.columns]
460
+ if "Patient" not in df_raw.columns: return gr.update(choices=[],value=None),"'Patient' column not found."
461
+ df_prep=prepare_features(df_raw); _CACHE["df"]=df_prep
462
+ pids=sorted(df_prep["Patient"].unique().tolist())
463
+ msg=f"Loaded {len(pids)} patients | {len(df_raw)} rows | cols: {', '.join(df_raw.columns[:5].tolist())}"
464
+ return gr.update(choices=pids,value=pids[0] if pids else None),msg
465
+ except Exception as e: return gr.update(choices=[],value=None),f"Error: {e}"
466
+
 
 
 
 
 
 
 
 
467
  def on_dicom_upload(dicom_files):
468
+ if not dicom_files: return gr.update(),"No DICOM files uploaded."
469
+ n=len(dicom_files); pid=detect_pid(dicom_files); df=_CACHE.get("df")
 
 
470
  if pid and df is not None and pid in df["Patient"].values:
471
+ return gr.update(value=pid),f"{n} files | Auto-matched Patient ID: {pid}"
472
+ elif pid: return gr.update(),f"{n} files | DICOM ID '{pid}' not in CSV — select manually"
473
+ return gr.update(),f"{n} files | No Patient ID in DICOM tags — select manually"
474
+
475
+ def on_patient_select(pid):
476
+ df=_CACHE.get("df")
477
+ if df is None or not pid: return "Upload a CSV first."
478
+ bl,visits=extract_patient(df,pid)
479
+ if bl is None: return f"Patient '{pid}' not found."
480
+ sex="Male" if bl["Sex_enc"]==1. else "Female"
481
+ smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
482
+ lines="\n".join(f" Week {int(r['WeekDelta']):>4} -> FVC = {r['FVC']:.0f} ml" for _,r in visits.iterrows())
483
+ return (f"Patient : {pid}\n"
484
+ f"Age/Sex : {int(bl['Age'])} yrs / {sex} / {smoking}\n"
485
+ f"Baseline FVC : {bl['BaselineFVC']:.0f} ml ({bl['Percent']:.1f}% predicted)\n"
486
+ f"Est. normal : {bl['PredictedFVC']:.0f} ml\n\nAll visits:\n{lines}")
487
+
488
+ def run_all(pid,dicom_files):
489
+ df=_CACHE.get("df")
490
+ if df is None: return _empty("Upload CSV first"),_empty(""),"Upload CSV first.",gr.update(visible=False),gr.update(visible=False)
491
+ if not pid: return _empty("Select a patient"),_empty(""),"Select a Patient ID.",gr.update(visible=False),gr.update(visible=False)
492
+ bl,visits=extract_patient(df,pid)
493
+ if bl is None: return _empty(f"Patient {pid} not found"),_empty(""),"Not found.",gr.update(visible=False),gr.update(visible=False)
494
+ volume=load_dicoms(dicom_files) if dicom_files else None
495
+ _CACHE["vol"]=volume
496
+ mu,sigma=run_inference(bl,volume,float(bl.get("BaselineWeek",0.)))
497
+ fvc_fig=make_fvc_plot(bl,visits,mu,sigma)
498
+ ct_view=make_multiview(volume) if volume is not None else _empty("No DICOM uploaded — CT view unavailable")
499
+ _CACHE.update({"last_fig":fvc_fig,"last_bl":bl,"last_visits":visits,"last_mu":mu,"last_sigma":sigma})
500
+
501
+ fvc_bl=float(bl["BaselineFVC"]); pct=float(bl["Percent"])
502
+ sev="Mild" if pct>=70 else "Moderate" if pct>=50 else "Severe"
503
+ dec_pct=(fvc_bl-mu[52])/fvc_bl*100
504
+ traj,monitor=(("STABLE","every 6 months") if dec_pct<5 else
505
+ ("SLOW DECLINE","every 3-4 months") if dec_pct<10 else ("RAPID DECLINE","monthly"))
506
+ wks10=next((w for w in range(145) if mu[w]<=fvc_bl*0.90),None)
507
+ vis_wk=visits["WeekDelta"].values.astype(float); vis_fvc=visits["FVC"].values.astype(float)
508
+ obs=""
509
+ if len(vis_wk)>0:
510
+ rows=[f" {'Week':>6} {'Actual':>8} {'Predicted':>10} {'Error':>8}"," "+"-"*38]
511
+ errs=[]
512
+ for wk,afvc in zip(vis_wk,vis_fvc):
513
+ wi=int(np.clip(int(wk),0,144)); pred=mu[wi]; err=afvc-pred; errs.append(abs(err))
514
+ rows.append(f" {int(wk):>6} {afvc:>8.0f} {pred:>10.0f} {err:>+8.0f} ml")
515
+ rows.append(f"\n Mean Absolute Error: {np.mean(errs):.1f} ml")
516
+ obs="\nOBSERVED vs PREDICTED\n"+"\n".join(rows)
517
+
518
+ sex="Male" if bl["Sex_enc"]==1. else "Female"
519
+ smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
520
+ report=(f"FIBROSISNET-V4 -- CLINICAL SUMMARY\n{'='*52}\n\n"
521
+ f"Patient : {pid}\n"
522
+ f"Age/Sex : {int(bl['Age'])} yrs / {sex} / {smoking}\n"
523
+ f"Baseline FVC : {fvc_bl:.0f} ml ({pct:.1f}% predicted)\n"
524
+ f"Est. Normal : {float(bl['PredictedFVC']):.0f} ml\n\n"
525
+ f"SEVERITY (ATS/ERS)\n {sev.upper()} -- {pct:.1f}% predicted FVC\n"
526
+ f" Mild >=70% | Moderate 50-69% | Severe <50%\n\n"
527
+ f"TRAJECTORY\n {traj}\n"
528
+ f" 6 months : {mu[26]:.0f} ml (-{fvc_bl-mu[26]:.0f} ml)\n"
529
+ f" 1 year : {mu[52]:.0f} ml (-{fvc_bl-mu[52]:.0f} ml, {dec_pct:.1f}%/yr)\n"
530
+ f" 2 years : {mu[104]:.0f} ml (-{fvc_bl-mu[104]:.0f} ml cumulative)\n"
531
+ f" +/-1sigma at 1yr: {mu[52]-sigma[52]:.0f} - {mu[52]+sigma[52]:.0f} ml\n"
532
+ f"\n10% DECLINE THRESHOLD\n"
533
+ f" {'Week '+str(wks10)+f' (~{wks10//4} months)' if wks10 else 'Not reached in 2.5-yr horizon'}\n"
534
+ f"{obs}\n\nMONITORING\n Spirometry {monitor}\n"
535
+ f" {'Discuss antifibrotic therapy with specialist' if sev!='Mild' or dec_pct>=10 else 'Continue current management plan'}\n\n"
536
+ f"{'='*52}\n"
537
+ f"AI research model -- Not for clinical use without physician oversight\n"
538
+ f"OOF -6.6629 | Kaggle baseline -6.6743 (beats baseline)")
539
+ return fvc_fig,ct_view,report,gr.update(visible=True),gr.update(visible=False)
540
+
541
+ def on_download_pdf():
542
+ bl=_CACHE.get("last_bl"); visits=_CACHE.get("last_visits")
543
+ mu=_CACHE.get("last_mu"); sigma=_CACHE.get("last_sigma"); fig=_CACHE.get("last_fig")
544
+ if bl is None or mu is None: return None
545
+ pdf_bytes=generate_pdf(bl,visits,mu,sigma,fig)
546
+ if pdf_bytes is None: return None
547
+ pid=str(bl["Patient"])[:20]; path=f"/tmp/FibrosisNet_{pid}.pdf"
548
+ with open(path,"wb") as f: f.write(pdf_bytes)
549
+ return path
550
+
551
+ # ── CSS ────────────────────────────────────────────────────────
552
+ CSS="""
553
+ :root{--navy:#0F2544;--blue:#1D6FA4;--teal:#0D9488;--green:#059669;
554
+ --amber:#D97706;--red:#DC2626;--gray:#6B7280;--border:#DDE3EC;--bg:#FAFBFD;}
555
+ .gradio-container{max-width:1340px!important;margin:0 auto!important;background:var(--bg)!important;}
556
+ .app-hdr{background:linear-gradient(135deg,#0F2544 0%,#1a3a6b 55%,#1D6FA4 100%);
557
+ border-radius:14px;padding:26px 36px;margin-bottom:20px;
558
+ box-shadow:0 8px 32px rgba(15,37,68,.18);}
559
+ .app-hdr h1{color:white;font-size:26px;font-weight:700;letter-spacing:-.5px;margin:0 0 4px;}
560
+ .app-hdr p{color:#8BBFD4;font-size:12.5px;margin:0;}
561
+ .step-hdr{font-size:11px;font-weight:700;letter-spacing:.9px;text-transform:uppercase;
562
+ color:var(--navy);border-left:3px solid var(--blue);padding-left:10px;
563
+ margin:16px 0 8px;display:block;}
564
+ .run-btn button{background:linear-gradient(135deg,#0F2544 0%,#1D6FA4 100%)!important;
565
+ border:none!important;border-radius:10px!important;font-size:15px!important;
566
+ font-weight:600!important;box-shadow:0 4px 16px rgba(15,37,68,.25)!important;color:white!important;}
567
+ .pdf-btn button{background:linear-gradient(135deg,#059669 0%,#0D9488 100%)!important;
568
+ border:none!important;border-radius:8px!important;font-size:13px!important;
569
+ font-weight:600!important;box-shadow:0 3px 12px rgba(5,150,105,.25)!important;color:white!important;}
570
+ .report-mono textarea{font-family:'Courier New',monospace!important;font-size:11.5px!important;
571
+ line-height:1.7!important;background:#0F2544!important;color:#8BBFD4!important;
572
+ border-radius:8px!important;border:none!important;}
573
+ .patient-box textarea{font-family:'Courier New',monospace!important;font-size:12px!important;
574
+ background:#F8FAFC!important;border:1px solid var(--border)!important;
575
+ border-radius:8px!important;color:var(--navy)!important;line-height:1.65!important;}
576
+ .status-box textarea{background:#F0F9FF!important;border:1px solid #BAE6FD!important;
577
+ border-radius:8px!important;font-size:12px!important;color:#0369A1!important;font-weight:500!important;}
578
+ .dicom-upload .file-preview{max-height:140px!important;overflow-y:auto!important;}
579
  """
580
 
581
+ with gr.Blocks(title="FibrosisNet-V4",css=CSS,theme=gr.themes.Base()) as demo:
582
+ gr.HTML('<div class="app-hdr"><h1>🫁 FibrosisNet-V4</h1>'
583
+ '<p>Pulmonary Fibrosis Progression Prediction &nbsp;·&nbsp; '
584
+ 'Multi-Backbone 2.5D Deep Learning &nbsp;·&nbsp; '
585
+ 'Swin-Tiny · SE Attention · Cross-Attention Fusion &nbsp;·&nbsp; '
586
+ 'OOF -6.6629 beats Kaggle baseline -6.6743 ✓</p></div>')
587
+
588
+ with gr.Row(equal_height=False):
589
+ with gr.Column(scale=1,min_width=340):
590
+ gr.HTML('<span class="step-hdr">Step 1 — Upload Test CSV</span>')
591
+ csv_file = gr.File(label="test.csv",file_types=[".csv"])
592
+ csv_status = gr.Textbox(label="Status",lines=2,interactive=False,elem_classes="status-box")
593
+
594
+ gr.HTML('<span class="step-hdr">Step 2 — Select Patient</span>')
595
+ patient_dd = gr.Dropdown(label="Patient ID",choices=[],value=None,allow_custom_value=True)
596
+ patient_info = gr.Textbox(label="Patient Preview",lines=9,interactive=False,elem_classes="patient-box")
597
+
598
+ gr.HTML('<span class="step-hdr">Step 3 — Run Prediction</span>')
599
+ predict_btn = gr.Button("🔬 Run FibrosisNet Prediction",elem_classes="run-btn",size="lg")
600
+
601
+ gr.HTML('<span class="step-hdr">Step 4 — Upload CT DICOM (Optional)</span>')
602
+ with gr.Accordion("🩻 Upload DICOM Slices",open=False):
603
+ gr.Markdown("Upload `.dcm` files. Patient ID auto-read from tags. File list is scrollable.",elem_classes="status-box")
604
+ dicom_files = gr.File(label="DICOM files (.dcm)",file_count="multiple",
605
+ file_types=[".dcm",".DCM"],elem_classes="dicom-upload")
606
+ dicom_status = gr.Textbox(label="DICOM Status",lines=2,interactive=False,elem_classes="status-box")
607
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
608
  with gr.Column(scale=2):
609
  with gr.Tabs():
610
  with gr.Tab("📈 FVC Decline Graph"):
611
  fvc_plot = gr.Plot(label="FVC Trajectory")
612
 
613
  with gr.Tab("🫁 CT Lung Viewer"):
614
+ ct_view = gr.Plot(label="Multi-Plane CT")
615
+ gr.Markdown("---\n**Slice Explorer** — drag to scrub through axial slices")
616
+ slice_slider = gr.Slider(0,300,value=0,step=1,label="Axial Slice")
617
  slice_view = gr.Plot(label="Slice Viewer")
618
+ slice_slider.change(fn=update_slice,inputs=slice_slider,outputs=slice_view)
619
 
620
  with gr.Tab("📄 Clinical Report"):
621
+ with gr.Row():
622
+ gr.Markdown("### Clinical Summary")
623
+ pdf_btn = gr.Button("⬇️ Download PDF Report",elem_classes="pdf-btn",size="sm",visible=False)
624
+ report_box = gr.Textbox(label="Report",lines=36,max_lines=60,
625
+ interactive=False,elem_classes="report-mono")
626
+ pdf_output = gr.File(label="PDF Download",visible=False)
627
+
628
+ csv_file.upload(fn=on_csv_upload,inputs=csv_file,outputs=[patient_dd,csv_status])
629
+ dicom_files.upload(fn=on_dicom_upload,inputs=dicom_files,outputs=[patient_dd,dicom_status])
630
+ patient_dd.change(fn=on_patient_select,inputs=patient_dd,outputs=patient_info)
631
+ predict_btn.click(fn=run_all,inputs=[patient_dd,dicom_files],
632
+ outputs=[fvc_plot,ct_view,report_box,pdf_btn,pdf_output])
633
+ pdf_btn.click(fn=on_download_pdf,inputs=[],outputs=pdf_output)
634
+ pdf_btn.click(fn=lambda:gr.update(visible=True),inputs=[],outputs=pdf_output)
635
+
636
+ gr.HTML('<div style="text-align:center;margin-top:20px;padding:14px;border-top:1px solid #DDE3EC;'
637
+ 'color:#9CA3AF;font-size:12px;">'
638
+ '<b style="color:#0F2544;">FibrosisNet-V4</b> &nbsp;·&nbsp; Balaji R, NIT Calicut, May 2026 '
639
+ '&nbsp;·&nbsp; OSIC Pulmonary Fibrosis Progression '
640
+ '&nbsp;·&nbsp; Research prototype — not for clinical use</div>')
641
+
642
+ demo.launch(server_name="0.0.0.0",server_port=7860)