Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,10 +1,9 @@
|
|
| 1 |
"""
|
| 2 |
-
FibrosisNet-V4 — Gradio App
|
| 3 |
-
|
| 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 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
IMG_SIZE = 224
|
| 27 |
NUM_SLICES = 16
|
| 28 |
HU_MIN, HU_MAX = -1000, 400
|
| 29 |
-
|
| 30 |
-
|
| 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
|
| 37 |
-
|
| 38 |
FUSION_DIM = 512
|
| 39 |
FUSION_HEADS = 8
|
| 40 |
FUSION_DEPTH = 1
|
| 41 |
|
| 42 |
-
|
| 43 |
-
|
| 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,
|
| 52 |
-
self.se = nn.Sequential(
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
)
|
| 56 |
-
|
| 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,
|
| 64 |
-
fuse_dim=FUSION_DIM, n_heads=FUSION_HEADS, depth=FUSION_DEPTH):
|
| 65 |
super().__init__()
|
| 66 |
-
self.ct_proj
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
self.
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 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,
|
| 81 |
super().__init__()
|
| 82 |
-
self.week_proj
|
| 83 |
-
self.fc
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
nn.Linear(256, 3),
|
| 87 |
-
)
|
| 88 |
with torch.no_grad():
|
| 89 |
self.fc[-1].weight.data.zero_()
|
| 90 |
-
self.fc[-1].bias.data
|
| 91 |
-
self.sigma_rate_fc
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
B,
|
| 100 |
-
|
| 101 |
-
|
| 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,
|
| 114 |
super().__init__()
|
| 115 |
-
self.backbone
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
self.
|
| 119 |
-
|
| 120 |
-
self.
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
)
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 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 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 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
|
| 167 |
-
return
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
""
|
| 181 |
-
df
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
df
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
df["
|
| 188 |
-
|
| 189 |
-
|
| 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
|
| 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
|
| 233 |
-
pid
|
| 234 |
-
if pid:
|
| 235 |
-
|
| 236 |
-
except Exception:
|
| 237 |
-
continue
|
| 238 |
return None
|
| 239 |
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
|
| 249 |
-
|
| 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 |
-
|
| 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 |
-
|
| 277 |
-
slices, positions = [], []
|
| 278 |
for f in files:
|
| 279 |
try:
|
| 280 |
-
ds
|
| 281 |
-
img
|
| 282 |
-
img
|
| 283 |
-
|
| 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
|
| 288 |
-
|
| 289 |
-
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
| 294 |
-
|
| 295 |
-
|
| 296 |
-
|
| 297 |
-
|
| 298 |
-
|
| 299 |
-
|
| 300 |
-
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 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,
|
| 328 |
-
return mu.squeeze().numpy(),
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
fig
|
| 345 |
-
gs
|
| 346 |
-
ax_main
|
| 347 |
-
|
| 348 |
-
|
| 349 |
-
|
| 350 |
-
|
| 351 |
-
ax_main.plot(weeks,
|
| 352 |
-
ax_main.
|
| 353 |
-
|
| 354 |
-
ax_main.
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
| 358 |
-
|
| 359 |
-
|
| 360 |
-
|
| 361 |
-
|
| 362 |
-
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
ax_main.
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 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 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 416 |
-
|
| 417 |
-
|
| 418 |
-
|
| 419 |
-
ax_sev.
|
| 420 |
-
ax_sev.
|
| 421 |
-
ax_sev.
|
| 422 |
-
|
| 423 |
-
|
| 424 |
-
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
age
|
| 429 |
-
|
| 430 |
-
|
| 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,
|
| 448 |
-
fig,
|
| 449 |
-
views
|
| 450 |
-
|
| 451 |
-
|
| 452 |
-
|
| 453 |
-
|
| 454 |
-
|
| 455 |
-
|
| 456 |
-
|
| 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
|
| 463 |
-
|
| 464 |
-
|
| 465 |
-
|
| 466 |
-
|
| 467 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 468 |
|
| 469 |
def update_slice(idx):
|
| 470 |
-
vol
|
| 471 |
-
if vol is None:
|
| 472 |
-
|
| 473 |
-
|
| 474 |
-
|
| 475 |
-
|
| 476 |
-
|
| 477 |
-
|
| 478 |
-
|
| 479 |
-
|
| 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
|
| 600 |
-
df_raw.columns
|
| 601 |
-
if "Patient" not in df_raw.columns:
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 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 |
-
|
| 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),
|
| 623 |
-
elif pid:
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
| 632 |
-
|
| 633 |
-
|
| 634 |
-
|
| 635 |
-
|
| 636 |
-
|
| 637 |
-
|
| 638 |
-
|
| 639 |
-
|
| 640 |
-
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
)
|
| 644 |
-
return (f"Patient
|
| 645 |
-
|
| 646 |
-
|
| 647 |
-
|
| 648 |
-
|
| 649 |
-
|
| 650 |
-
|
| 651 |
-
|
| 652 |
-
|
| 653 |
-
|
| 654 |
-
|
| 655 |
-
|
| 656 |
-
|
| 657 |
-
|
| 658 |
-
|
| 659 |
-
|
| 660 |
-
if
|
| 661 |
-
|
| 662 |
-
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
|
| 666 |
-
|
| 667 |
-
|
| 668 |
-
|
| 669 |
-
|
| 670 |
-
|
| 671 |
-
|
| 672 |
-
|
| 673 |
-
|
| 674 |
-
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
| 686 |
-
|
| 687 |
-
|
| 688 |
-
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 692 |
"""
|
| 693 |
|
| 694 |
-
with gr.Blocks(title="FibrosisNet-V4",
|
| 695 |
-
gr.
|
| 696 |
-
|
| 697 |
-
|
| 698 |
-
|
| 699 |
-
|
| 700 |
-
|
| 701 |
-
with gr.Row():
|
| 702 |
-
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
gr.
|
| 708 |
-
|
| 709 |
-
|
| 710 |
-
|
| 711 |
-
)
|
| 712 |
-
|
| 713 |
-
|
| 714 |
-
|
| 715 |
-
|
| 716 |
-
|
| 717 |
-
|
| 718 |
-
|
| 719 |
-
|
| 720 |
-
|
| 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-
|
| 755 |
-
gr.Markdown("---\n**
|
| 756 |
-
slice_slider = gr.Slider(0,
|
| 757 |
slice_view = gr.Plot(label="Slice Viewer")
|
| 758 |
-
slice_slider.change(fn=update_slice,
|
| 759 |
|
| 760 |
with gr.Tab("📄 Clinical Report"):
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
| 767 |
-
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
)
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
|
| 780 |
-
|
| 781 |
-
|
| 782 |
-
|
| 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 · '
|
| 584 |
+
'Multi-Backbone 2.5D Deep Learning · '
|
| 585 |
+
'Swin-Tiny · SE Attention · Cross-Attention Fusion · '
|
| 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> · Balaji R, NIT Calicut, May 2026 '
|
| 639 |
+
' · OSIC Pulmonary Fibrosis Progression '
|
| 640 |
+
' · Research prototype — not for clinical use</div>')
|
| 641 |
+
|
| 642 |
+
demo.launch(server_name="0.0.0.0",server_port=7860)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|