Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
"""
|
| 2 |
-
FibrosisNet-V4 β Redesigned Gradio App
|
| 3 |
-
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os, json, warnings, math, io, datetime
|
|
@@ -14,6 +14,7 @@ import matplotlib
|
|
| 14 |
matplotlib.use("Agg")
|
| 15 |
import matplotlib.pyplot as plt
|
| 16 |
import matplotlib.gridspec as gridspec
|
|
|
|
| 17 |
import pydicom
|
| 18 |
import timm
|
| 19 |
|
|
@@ -25,12 +26,16 @@ try:
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
| 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
|
|
@@ -39,14 +44,46 @@ TAB_FEATURES = ["BaselineFVC","Percent","Age","Sex_enc","Smoking_enc",
|
|
| 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 |
-
|
| 47 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 48 |
|
| 49 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
class SEAttentionPool(nn.Module):
|
| 51 |
def __init__(self, enc_dim, reduction=16):
|
| 52 |
super().__init__()
|
|
@@ -54,29 +91,24 @@ class SEAttentionPool(nn.Module):
|
|
| 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 |
-
|
| 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.])
|
|
@@ -84,11 +116,9 @@ class TrajectoryHead(nn.Module):
|
|
| 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 |
-
|
| 89 |
-
|
| 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 |
|
|
@@ -96,8 +126,8 @@ 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.
|
| 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)
|
|
@@ -105,8 +135,7 @@ class FibrosisModel2p5D(nn.Module):
|
|
| 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)
|
|
@@ -133,7 +162,7 @@ def _load_norm():
|
|
| 133 |
|
| 134 |
MODEL=_load_model(); T_MEAN,T_STD=_load_norm()
|
| 135 |
|
| 136 |
-
# ββ
|
| 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)
|
|
@@ -166,7 +195,7 @@ def detect_pid(files):
|
|
| 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
|
|
@@ -198,7 +227,6 @@ def load_dicoms(files):
|
|
| 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 |
|
|
@@ -216,12 +244,12 @@ def run_inference(bl,volume,bw=0.):
|
|
| 216 |
mu,sigma=MODEL(vol_t,tab_t,bfvc_t,weeks_t)
|
| 217 |
return mu.squeeze().numpy(),sigma.squeeze().numpy()
|
| 218 |
|
| 219 |
-
# ββ
|
| 220 |
def _empty(msg=""):
|
| 221 |
-
fig,ax=plt.subplots(figsize=(
|
| 222 |
ax.text(0.5,0.5,msg,ha="center",va="center",transform=ax.transAxes,
|
| 223 |
-
color=
|
| 224 |
-
ax.
|
| 225 |
|
| 226 |
def make_fvc_plot(bl,visits,mu,sigma):
|
| 227 |
fvc_bl=float(bl["BaselineFVC"]); norm_fvc=float(bl["PredictedFVC"])
|
|
@@ -230,106 +258,177 @@ def make_fvc_plot(bl,visits,mu,sigma):
|
|
| 230 |
vis_fvc=visits["FVC"].values.astype(float)
|
| 231 |
dec_1yr=(fvc_bl-mu[52])/fvc_bl*100
|
| 232 |
|
| 233 |
-
fig=plt.figure(figsize=(
|
| 234 |
-
|
| 235 |
-
|
| 236 |
-
|
| 237 |
-
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
ax_main
|
| 241 |
-
|
| 242 |
-
|
| 243 |
-
|
| 244 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 245 |
if len(vis_wk)>0:
|
| 246 |
-
ax_main.plot(vis_wk,vis_fvc,color=
|
| 247 |
-
ax_main.scatter(vis_wk,vis_fvc,color=
|
|
|
|
| 248 |
for wk,fv in zip(vis_wk,vis_fvc):
|
| 249 |
-
ax_main.annotate(f"{fv:.0f}",xy=(wk,fv),xytext=(5,
|
| 250 |
-
fontsize=
|
| 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=[
|
| 266 |
-
bars=ax_bar.bar(clabs,fvc_ck,color=bcols,edgecolor="
|
| 267 |
-
ax_bar.axhline(fvc_bl,color=
|
| 268 |
-
ax_bar.axhline(fvc_bl*0.9,color=
|
| 269 |
-
ax_bar.
|
| 270 |
-
ax_bar.
|
| 271 |
-
ax_bar.
|
| 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()+
|
| 276 |
-
f"{val:.0f}",ha="center",fontsize=6.5,fontweight="bold",color=
|
| 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=
|
| 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=
|
| 286 |
-
|
| 287 |
-
|
|
|
|
| 288 |
mx=float(np.clip(dec_1yr,0,29))
|
| 289 |
-
ax_sev.axvline(mx,color=
|
| 290 |
-
ax_sev.scatter([mx],[0],color=
|
| 291 |
-
ax_sev.set_xlim(0,30); ax_sev.set_ylim(-0.
|
| 292 |
-
ax_sev.set_xlabel("Annual FVC Decline (%)",fontsize=9,
|
| 293 |
-
ax_sev.set_title(f"{sev_label}\n{dec_1yr:.1f}%/year",
|
|
|
|
| 294 |
for xt,xtl in zip([0,5,10,20,30],["0%","5%","10%","20%","30%"]):
|
| 295 |
-
ax_sev.text(xt,-0.
|
| 296 |
-
ax_sev.
|
| 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"
|
| 301 |
-
fontsize=10
|
| 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=(
|
| 307 |
-
|
|
|
|
|
|
|
|
|
|
| 308 |
for ax,(img,ttl) in zip(axes,views):
|
| 309 |
-
|
| 310 |
-
ax.
|
| 311 |
-
|
| 312 |
-
|
| 313 |
-
|
| 314 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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,
|
| 322 |
-
|
| 323 |
-
|
| 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")
|
|
@@ -337,140 +436,197 @@ def generate_pdf(bl,visits,mu,sigma,fvc_fig):
|
|
| 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 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
|
|
|
|
|
|
| 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 |
-
|
| 349 |
-
|
| 350 |
-
story.append(Paragraph(
|
| 351 |
-
story.append(
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
pt.setStyle(TableStyle([
|
| 359 |
-
("BACKGROUND",(0,0),(-1,-1),
|
| 360 |
-
("
|
| 361 |
-
("
|
| 362 |
-
("
|
| 363 |
-
("
|
| 364 |
-
("
|
| 365 |
-
("
|
| 366 |
-
|
| 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 |
-
|
| 371 |
-
|
| 372 |
-
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 389 |
prt.setStyle(TableStyle([
|
| 390 |
-
("BACKGROUND",(0,0),(-1,0),
|
| 391 |
-
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,
|
| 392 |
-
("ROWBACKGROUNDS",(0,1),(-1,-1),[
|
| 393 |
-
("
|
| 394 |
-
("
|
| 395 |
-
("
|
|
|
|
|
|
|
|
|
|
| 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",
|
| 402 |
-
|
| 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 |
-
|
| 407 |
-
|
| 408 |
-
|
|
|
|
|
|
|
|
|
|
| 409 |
ot.setStyle(TableStyle([
|
| 410 |
-
("BACKGROUND",(0,0),(-1,0),
|
| 411 |
-
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("
|
| 412 |
-
("
|
| 413 |
-
("
|
| 414 |
-
("
|
| 415 |
-
("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#
|
| 416 |
-
("TOPPADDING",(0,0),(-1,-1),
|
| 417 |
-
("LEFTPADDING",(0,0),(-1,-1),
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
|
| 421 |
-
|
|
|
|
|
|
|
|
|
|
| 422 |
fig_buf.seek(0)
|
| 423 |
-
story.append(RLImage(fig_buf,width=
|
|
|
|
| 424 |
|
| 425 |
-
|
| 426 |
-
|
| 427 |
-
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 431 |
|
| 432 |
-
|
| 433 |
-
story.append(
|
|
|
|
| 434 |
story.append(Paragraph(
|
| 435 |
-
"This report is
|
| 436 |
-
"It must not
|
|
|
|
| 437 |
story.append(Spacer(1,4))
|
| 438 |
-
story.append(Paragraph(
|
| 439 |
-
|
|
|
|
|
|
|
| 440 |
|
| 441 |
-
|
| 442 |
-
_CACHE={"vol":None,"df":None,"last_fig":None,"last_bl":None,"last_visits":None,"last_mu":None,"last_sigma":None}
|
| 443 |
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
|
| 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
|
| 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:
|
|
|
|
| 461 |
df_prep=prepare_features(df_raw); _CACHE["df"]=df_prep
|
| 462 |
pids=sorted(df_prep["Patient"].unique().tolist())
|
| 463 |
-
msg=f"
|
|
|
|
| 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"
|
| 466 |
|
| 467 |
def on_dicom_upload(dicom_files):
|
| 468 |
-
if not dicom_files: return gr.update(),"No DICOM files
|
| 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
|
| 472 |
-
elif pid: return gr.update(),f"{n} files
|
| 473 |
-
return gr.update(),f"{n} files
|
| 474 |
|
| 475 |
def on_patient_select(pid):
|
| 476 |
df=_CACHE.get("df")
|
|
@@ -479,63 +635,83 @@ def on_patient_select(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}
|
| 483 |
-
|
| 484 |
-
|
| 485 |
-
f"
|
| 486 |
-
f"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.",
|
| 491 |
-
if not pid: return _empty("Select a patient"),_empty(""),"Select a Patient ID.",
|
| 492 |
bl,visits=extract_patient(df,pid)
|
| 493 |
-
if bl is None: return _empty(f"Patient {pid} not found"),_empty(""),"Not found.",
|
| 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
|
|
|
|
| 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
|
| 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}
|
| 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}
|
| 515 |
-
rows.append(f"\n Mean Absolute Error
|
| 516 |
-
obs="\nOBSERVED
|
| 517 |
|
| 518 |
-
|
| 519 |
-
|
| 520 |
-
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
|
| 524 |
-
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
|
| 529 |
-
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
|
| 533 |
-
|
| 534 |
-
|
| 535 |
-
|
| 536 |
-
|
| 537 |
-
|
| 538 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 539 |
return fvc_fig,ct_view,report,gr.update(visible=True),gr.update(visible=False)
|
| 540 |
|
| 541 |
def on_download_pdf():
|
|
@@ -544,87 +720,348 @@ def on_download_pdf():
|
|
| 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 |
-
|
| 548 |
with open(path,"wb") as f: f.write(pdf_bytes)
|
| 549 |
return path
|
| 550 |
|
| 551 |
# ββ CSS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 552 |
CSS="""
|
| 553 |
-
:
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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("π
|
| 611 |
-
fvc_plot = gr.Plot(label="
|
| 612 |
-
|
| 613 |
-
with gr.Tab("π«
|
| 614 |
-
ct_view = gr.Plot(label="
|
| 615 |
-
gr.
|
| 616 |
-
|
| 617 |
-
|
|
|
|
| 618 |
slice_slider.change(fn=update_slice,inputs=slice_slider,outputs=slice_view)
|
| 619 |
|
| 620 |
-
with gr.Tab("π
|
| 621 |
with gr.Row():
|
| 622 |
-
gr.
|
| 623 |
-
pdf_btn = gr.Button("β¬
|
| 624 |
-
|
| 625 |
-
|
| 626 |
-
|
|
|
|
| 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)
|
|
@@ -633,10 +1070,4 @@ with gr.Blocks(title="FibrosisNet-V4",css=CSS,theme=gr.themes.Base()) as demo:
|
|
| 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)
|
|
|
|
| 1 |
"""
|
| 2 |
+
FibrosisNet-V4 β Premium Redesigned Gradio App
|
| 3 |
+
Precision-medical aesthetic: deep navy + cyan, Syne + IBM Plex Mono
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os, json, warnings, math, io, datetime
|
|
|
|
| 14 |
matplotlib.use("Agg")
|
| 15 |
import matplotlib.pyplot as plt
|
| 16 |
import matplotlib.gridspec as gridspec
|
| 17 |
+
from matplotlib import rcParams
|
| 18 |
import pydicom
|
| 19 |
import timm
|
| 20 |
|
|
|
|
| 26 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 27 |
from reportlab.lib.units import cm
|
| 28 |
from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer,
|
| 29 |
+
Table, TableStyle, HRFlowable, Image as RLImage,
|
| 30 |
+
KeepTogether)
|
| 31 |
+
from reportlab.lib.enums import TA_CENTER, TA_LEFT, TA_RIGHT
|
| 32 |
+
from reportlab.pdfbase import pdfmetrics
|
| 33 |
+
from reportlab.pdfbase.ttfonts import TTFont
|
| 34 |
PDF_OK = True
|
| 35 |
except ImportError:
|
| 36 |
PDF_OK = False
|
| 37 |
|
| 38 |
+
# ββ CONFIG ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
IMG_SIZE = 224
|
| 40 |
NUM_SLICES = 16
|
| 41 |
HU_MIN, HU_MAX = -1000, 400
|
|
|
|
| 44 |
SIN_PERIODS = (10., 26., 52., 104.)
|
| 45 |
SIN_DIM = len(SIN_PERIODS) * 2
|
| 46 |
TAB_DIM = len(TAB_FEATURES) + SIN_DIM
|
| 47 |
+
FUSION_DIM = 512; FUSION_HEADS = 8; FUSION_DEPTH = 1
|
|
|
|
|
|
|
| 48 |
|
| 49 |
+
# Color palette β precision medical
|
| 50 |
+
P = dict(
|
| 51 |
+
navy = "#050E1F",
|
| 52 |
+
navy2 = "#0A1628",
|
| 53 |
+
navy3 = "#0F2142",
|
| 54 |
+
blue = "#0D5EAF",
|
| 55 |
+
cyan = "#00C9E0",
|
| 56 |
+
cyan2 = "#00A8BC",
|
| 57 |
+
teal = "#0B8C7A",
|
| 58 |
+
green = "#00B87C",
|
| 59 |
+
amber = "#E8971A",
|
| 60 |
+
red = "#E03C3C",
|
| 61 |
+
slate = "#1E2D47",
|
| 62 |
+
slate2 = "#253550",
|
| 63 |
+
border = "#1C2E4A",
|
| 64 |
+
text = "#D0DCF0",
|
| 65 |
+
muted = "#6B82A8",
|
| 66 |
+
bg = "#070E1D",
|
| 67 |
+
)
|
| 68 |
|
| 69 |
+
# matplotlib style
|
| 70 |
+
rcParams.update({
|
| 71 |
+
"font.family": "DejaVu Sans",
|
| 72 |
+
"axes.facecolor": P["navy2"],
|
| 73 |
+
"figure.facecolor": P["navy"],
|
| 74 |
+
"text.color": P["text"],
|
| 75 |
+
"axes.labelcolor": P["text"],
|
| 76 |
+
"xtick.color": P["muted"],
|
| 77 |
+
"ytick.color": P["muted"],
|
| 78 |
+
"axes.edgecolor": P["border"],
|
| 79 |
+
"grid.color": P["border"],
|
| 80 |
+
"grid.alpha": 0.4,
|
| 81 |
+
"legend.framealpha": 0.85,
|
| 82 |
+
"legend.edgecolor": P["border"],
|
| 83 |
+
"legend.facecolor": P["slate"],
|
| 84 |
+
})
|
| 85 |
+
|
| 86 |
+
# ββ MODEL βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 87 |
class SEAttentionPool(nn.Module):
|
| 88 |
def __init__(self, enc_dim, reduction=16):
|
| 89 |
super().__init__()
|
|
|
|
| 91 |
self.se = nn.Sequential(nn.Linear(enc_dim,enc_dim//reduction),nn.ReLU(inplace=True),
|
| 92 |
nn.Linear(enc_dim//reduction,enc_dim),nn.Sigmoid())
|
| 93 |
def forward(self,feat):
|
| 94 |
+
w=F.softmax(self.attn(feat),dim=1); p=(feat*w).sum(dim=1); return p*self.se(p)
|
|
|
|
| 95 |
|
| 96 |
class FusionTransformer(nn.Module):
|
| 97 |
def __init__(self,ct_dim,tab_dim_in,fuse_dim=FUSION_DIM,n_heads=FUSION_HEADS,depth=FUSION_DEPTH):
|
| 98 |
super().__init__()
|
| 99 |
self.ct_proj=nn.Linear(ct_dim,fuse_dim); self.tab_proj=nn.Linear(tab_dim_in,fuse_dim)
|
| 100 |
layer=nn.TransformerDecoderLayer(d_model=fuse_dim,nhead=n_heads,
|
| 101 |
+
dim_feedforward=fuse_dim*4,dropout=0.1,activation="gelu",batch_first=True,norm_first=True)
|
| 102 |
+
self.cross_attn=nn.TransformerDecoder(layer,num_layers=depth); self.norm=nn.LayerNorm(fuse_dim)
|
|
|
|
|
|
|
| 103 |
def forward(self,ct_seq,tab_feat):
|
| 104 |
+
return self.norm(self.cross_attn(self.tab_proj(tab_feat).unsqueeze(1),self.ct_proj(ct_seq)).squeeze(1))
|
|
|
|
| 105 |
|
| 106 |
class TrajectoryHead(nn.Module):
|
| 107 |
def __init__(self,in_dim):
|
| 108 |
super().__init__()
|
| 109 |
self.week_proj=nn.Linear(3,64)
|
| 110 |
self.fc=nn.Sequential(nn.Linear(in_dim+64,512),nn.LayerNorm(512),nn.GELU(),nn.Dropout(0.20),
|
| 111 |
+
nn.Linear(512,256),nn.LayerNorm(256),nn.GELU(),nn.Dropout(0.15),nn.Linear(256,3))
|
|
|
|
| 112 |
with torch.no_grad():
|
| 113 |
self.fc[-1].weight.data.zero_()
|
| 114 |
self.fc[-1].bias.data=torch.tensor([-2.,0.,5.])
|
|
|
|
| 116 |
def _emb(self,w):
|
| 117 |
return torch.stack([torch.sin(w/52.),torch.cos(w/52.),(w/100.).clamp(-1,1)],dim=-1)
|
| 118 |
def forward(self,feat,base_fvc,weeks):
|
| 119 |
+
B,T=weeks.shape; sr=torch.exp(self.sigma_rate_fc(feat)).clamp(0.01,10.)
|
| 120 |
+
out=self.fc(torch.cat([feat.unsqueeze(1).expand(-1,T,-1),F.gelu(self.week_proj(self._emb(weeks)))],dim=-1))
|
| 121 |
+
mu=base_fvc.view(B,1)+out[...,1:2].squeeze(-1)+out[...,0:1].squeeze(-1)*weeks
|
|
|
|
|
|
|
| 122 |
sigma=(torch.exp(out[...,2:3]).clamp(50,500).squeeze(-1)+sr*weeks.abs()).clamp(70,3000)
|
| 123 |
return mu,sigma
|
| 124 |
|
|
|
|
| 126 |
def __init__(self,backbone_name,pretrained=False):
|
| 127 |
super().__init__()
|
| 128 |
self.backbone=timm.create_model(backbone_name,pretrained=pretrained,num_classes=0,global_pool="")
|
| 129 |
+
enc_dim=self.backbone.num_features; self.gap=nn.AdaptiveAvgPool2d(1)
|
| 130 |
+
self.se_pool=SEAttentionPool(enc_dim)
|
| 131 |
self.tab_mlp=nn.Sequential(nn.Linear(TAB_DIM,256),nn.LayerNorm(256),nn.GELU(),nn.Dropout(0.1),
|
| 132 |
nn.Linear(256,128),nn.LayerNorm(128),nn.GELU())
|
| 133 |
self.fusion=FusionTransformer(enc_dim,128); self.head=TrajectoryHead(FUSION_DIM)
|
|
|
|
| 135 |
B,C,D,H,W=x.shape; x2d=x.permute(0,2,1,3,4).reshape(B*D,C,H,W)
|
| 136 |
raw=self.backbone.forward_features(x2d)
|
| 137 |
feat=(raw[:,0] if raw.ndim==3 else
|
| 138 |
+
raw.mean(dim=(1,2)) if raw.shape[-1]==self.backbone.num_features else self.gap(raw).flatten(1))
|
|
|
|
| 139 |
return feat.view(B,D,-1)
|
| 140 |
def forward(self,vol,tab,base_fvc,weeks):
|
| 141 |
return self.head(self.fusion(self.encode_ct(vol),self.tab_mlp(tab)),base_fvc,weeks)
|
|
|
|
| 162 |
|
| 163 |
MODEL=_load_model(); T_MEAN,T_STD=_load_norm()
|
| 164 |
|
| 165 |
+
# ββ DATA ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 166 |
def prepare_features(df):
|
| 167 |
df=df.copy(); df.columns=[c.strip() for c in df.columns]
|
| 168 |
df["Sex_enc"]=(df["Sex"].str.strip()=="Male").astype(float)
|
|
|
|
| 195 |
except: continue
|
| 196 |
return None
|
| 197 |
|
| 198 |
+
# ββ CT PREPROCESSING ββββββββββββββββββββββββββββββββββββββββββ
|
| 199 |
def _extent(vol,thr=0.06):
|
| 200 |
m=vol.mean(axis=(1,2)); mask=m>thr
|
| 201 |
if mask.sum()<5: return 0,vol.shape[0]-1
|
|
|
|
| 227 |
vol=np.stack([slices[i] for i in np.argsort(positions)])
|
| 228 |
return np.clip((vol-HU_MIN)/(HU_MAX-HU_MIN),0,1)
|
| 229 |
|
|
|
|
| 230 |
def _sin(w):
|
| 231 |
return np.array([f(w/p) for p in SIN_PERIODS for f in (math.sin,math.cos)],dtype=np.float32)
|
| 232 |
|
|
|
|
| 244 |
mu,sigma=MODEL(vol_t,tab_t,bfvc_t,weeks_t)
|
| 245 |
return mu.squeeze().numpy(),sigma.squeeze().numpy()
|
| 246 |
|
| 247 |
+
# ββ PLOTS βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 248 |
def _empty(msg=""):
|
| 249 |
+
fig,ax=plt.subplots(figsize=(8,3.5))
|
| 250 |
ax.text(0.5,0.5,msg,ha="center",va="center",transform=ax.transAxes,
|
| 251 |
+
color=P["muted"],fontsize=12,style="italic",alpha=0.7)
|
| 252 |
+
ax.axis("off"); return fig
|
| 253 |
|
| 254 |
def make_fvc_plot(bl,visits,mu,sigma):
|
| 255 |
fvc_bl=float(bl["BaselineFVC"]); norm_fvc=float(bl["PredictedFVC"])
|
|
|
|
| 258 |
vis_fvc=visits["FVC"].values.astype(float)
|
| 259 |
dec_1yr=(fvc_bl-mu[52])/fvc_bl*100
|
| 260 |
|
| 261 |
+
fig=plt.figure(figsize=(16,7.5))
|
| 262 |
+
fig.patch.set_facecolor(P["navy"])
|
| 263 |
+
gs=gridspec.GridSpec(2,3,figure=fig,hspace=0.50,wspace=0.38)
|
| 264 |
+
ax_main=fig.add_subplot(gs[:,0:2])
|
| 265 |
+
ax_bar=fig.add_subplot(gs[0,2])
|
| 266 |
+
ax_sev=fig.add_subplot(gs[1,2])
|
| 267 |
+
|
| 268 |
+
for ax in [ax_main,ax_bar,ax_sev]:
|
| 269 |
+
ax.set_facecolor(P["navy2"])
|
| 270 |
+
for sp in ax.spines.values(): sp.set_edgecolor(P["border"])
|
| 271 |
+
|
| 272 |
+
# ββ Gradient confidence bands ββ
|
| 273 |
+
for alpha,mult in [(0.06,2),(0.14,1)]:
|
| 274 |
+
ax_main.fill_between(weeks,mu-mult*sigma,mu+mult*sigma,alpha=alpha,color=P["cyan"])
|
| 275 |
+
|
| 276 |
+
ax_main.plot(weeks,mu,color=P["cyan"],lw=2.5,zorder=5,label="FibrosisNet-V4 Prediction")
|
| 277 |
+
|
| 278 |
+
# Reference lines
|
| 279 |
+
ax_main.axhline(fvc_bl,color=P["muted"],ls="--",lw=1.4,alpha=0.7,label=f"Baseline {fvc_bl:.0f} ml")
|
| 280 |
+
ax_main.axhline(fvc_bl*0.90,color=P["amber"],ls=":",lw=1.8,label="β10% threshold",alpha=0.9)
|
| 281 |
+
ax_main.axhline(fvc_bl*0.80,color=P["red"],ls=":",lw=1.3,alpha=0.65,label="β20% threshold")
|
| 282 |
+
ax_main.axhline(norm_fvc,color=P["teal"],ls="-.",lw=1.2,alpha=0.65,label=f"Est. normal {norm_fvc:.0f} ml")
|
| 283 |
+
|
| 284 |
+
# Week milestone bands
|
| 285 |
+
for wk,lbl in [(26,"6 mo"),(52,"1 yr"),(78,"18 mo"),(104,"2 yr")]:
|
| 286 |
+
ax_main.axvline(wk,color=P["border"],ls="-",lw=0.6,alpha=0.5)
|
| 287 |
+
ax_main.text(wk+1,ax_main.get_ylim()[0] if False else mu.min()*0.973,
|
| 288 |
+
lbl,fontsize=7.5,color=P["muted"],va="bottom")
|
| 289 |
+
|
| 290 |
+
# Actual visits
|
| 291 |
if len(vis_wk)>0:
|
| 292 |
+
ax_main.plot(vis_wk,vis_fvc,color=P["red"],lw=1.6,ls="--",alpha=0.75,zorder=6)
|
| 293 |
+
ax_main.scatter(vis_wk,vis_fvc,color=P["red"],s=90,zorder=7,
|
| 294 |
+
edgecolors=P["navy"],linewidths=1.8,label="Actual FVC (CSV)")
|
| 295 |
for wk,fv in zip(vis_wk,vis_fvc):
|
| 296 |
+
ax_main.annotate(f"{fv:.0f}",xy=(wk,fv),xytext=(5,9),textcoords="offset points",
|
| 297 |
+
fontsize=7.5,color=P["red"],fontweight="bold")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 298 |
|
| 299 |
+
ax_main.scatter([0],[fvc_bl],color=P["cyan"],s=120,zorder=8,edgecolors=P["navy"],lw=2)
|
| 300 |
+
ax_main.set_xlabel("Weeks from Baseline",fontsize=11,labelpad=8)
|
| 301 |
+
ax_main.set_ylabel("Forced Vital Capacity (ml)",fontsize=11,labelpad=8)
|
| 302 |
+
ax_main.set_title(f"FVC Decline Trajectory Β· Patient {pid}",
|
| 303 |
+
fontsize=13,fontweight="bold",color=P["text"],pad=12)
|
| 304 |
+
leg=ax_main.legend(fontsize=8,loc="lower left",fancybox=True)
|
| 305 |
+
leg.get_frame().set_linewidth(0)
|
| 306 |
+
ax_main.grid(True,alpha=0.25)
|
| 307 |
+
|
| 308 |
+
# ββ Timepoint bar chart ββ
|
| 309 |
cps=[0,13,26,52,78,104,144]; clabs=["0w","3m","6m","1yr","18m","2yr","End"]
|
| 310 |
fvc_ck=[mu[min(w,144)] for w in cps]
|
| 311 |
+
bcols=[P["green"] if v>=fvc_bl*0.9 else P["amber"] if v>=fvc_bl*0.8 else P["red"] for v in fvc_ck]
|
| 312 |
+
bars=ax_bar.bar(clabs,fvc_ck,color=bcols,edgecolor=P["navy"],lw=1.2,width=0.68,zorder=3)
|
| 313 |
+
ax_bar.axhline(fvc_bl,color=P["muted"],ls="--",lw=1.1,alpha=0.7,zorder=4)
|
| 314 |
+
ax_bar.axhline(fvc_bl*0.9,color=P["amber"],ls=":",lw=1.1,alpha=0.7,zorder=4)
|
| 315 |
+
ax_bar.set_title("FVC at Key Timepoints",fontweight="bold",fontsize=10,pad=8)
|
| 316 |
+
ax_bar.grid(axis="y",alpha=0.25,zorder=0)
|
| 317 |
+
ax_bar.tick_params(axis="x",labelsize=8)
|
|
|
|
|
|
|
| 318 |
for bar,val in zip(bars,fvc_ck):
|
| 319 |
+
ax_bar.text(bar.get_x()+bar.get_width()/2,bar.get_height()+18,
|
| 320 |
+
f"{val:.0f}",ha="center",fontsize=6.5,fontweight="bold",color=P["text"])
|
| 321 |
if len(vis_wk)>0:
|
| 322 |
bx,by=[],[]
|
| 323 |
for wk,fv in zip(vis_wk,vis_fvc):
|
| 324 |
ni=int(np.argmin(np.abs(np.array(cps)-int(wk)))); bx.append(clabs[ni]); by.append(fv)
|
| 325 |
+
ax_bar.scatter(bx,by,color=P["red"],zorder=6,s=55,edgecolors=P["navy"],lw=1.5,label="Actual")
|
| 326 |
ax_bar.legend(fontsize=7)
|
| 327 |
|
| 328 |
+
# ββ Severity gauge ββ
|
| 329 |
sev_label=("Stable / Mild" if dec_1yr<5 else "Moderate" if dec_1yr<10 else "Severe / Rapid")
|
| 330 |
+
sev_col=P["green"] if dec_1yr<5 else P["amber"] if dec_1yr<10 else P["red"]
|
| 331 |
+
bands=[((0,5),P["green"]),((5,10),P["amber"]),((10,20),"#D06020"),((20,30),P["red"])]
|
| 332 |
+
for (lo,hi),col in bands:
|
| 333 |
+
ax_sev.barh(0,hi-lo,left=lo,color=col,height=0.5,alpha=0.5)
|
| 334 |
mx=float(np.clip(dec_1yr,0,29))
|
| 335 |
+
ax_sev.axvline(mx,color="white",lw=3.5,zorder=5)
|
| 336 |
+
ax_sev.scatter([mx],[0],color=sev_col,s=100,zorder=6,edgecolors="white",lw=2)
|
| 337 |
+
ax_sev.set_xlim(0,30); ax_sev.set_ylim(-0.8,0.8); ax_sev.set_yticks([])
|
| 338 |
+
ax_sev.set_xlabel("Annual FVC Decline (%)",fontsize=9,labelpad=6)
|
| 339 |
+
ax_sev.set_title(f"{sev_label}\n{dec_1yr:.1f}% / year",
|
| 340 |
+
fontweight="bold",fontsize=10,color=sev_col,pad=8)
|
| 341 |
for xt,xtl in zip([0,5,10,20,30],["0%","5%","10%","20%","30%"]):
|
| 342 |
+
ax_sev.text(xt,-0.65,xtl,fontsize=7,ha="center",color=P["muted"])
|
| 343 |
+
ax_sev.grid(axis="x",alpha=0.2)
|
|
|
|
| 344 |
|
| 345 |
age=int(bl["Age"]); sex="Male" if bl["Sex_enc"]==1. else "Female"
|
| 346 |
+
fig.suptitle(f"Age {age} Β· {sex} Β· Baseline FVC {fvc_bl:.0f} ml Β· {float(bl['Percent']):.0f}% predicted",
|
| 347 |
+
fontsize=10,color=P["muted"],y=1.01,fontweight="normal")
|
| 348 |
plt.tight_layout(); return fig
|
| 349 |
|
| 350 |
def make_multiview(volume):
|
| 351 |
D,H,W=volume.shape
|
| 352 |
+
fig,axes=plt.subplots(1,3,figsize=(15,5.2))
|
| 353 |
+
fig.patch.set_facecolor(P["navy"])
|
| 354 |
+
views=[(volume[D//2],f"Axial Β· slice {D//2+1}/{D}"),
|
| 355 |
+
(volume[:,H//2,:],"Coronal Β· mid"),
|
| 356 |
+
(volume[:,:,W//2],"Sagittal Β· mid")]
|
| 357 |
for ax,(img,ttl) in zip(axes,views):
|
| 358 |
+
ax.set_facecolor(P["navy"])
|
| 359 |
+
im=ax.imshow(img,cmap="bone",vmin=0,vmax=1,aspect="auto",interpolation="bicubic")
|
| 360 |
+
ax.set_title(ttl,color=P["cyan"],fontsize=10,pad=8,fontweight="bold")
|
| 361 |
+
ax.axis("off")
|
| 362 |
+
cb=fig.colorbar(im,ax=axes[-1],fraction=0.026,pad=0.02)
|
| 363 |
+
cb.set_label("HU [0 β 1]",color=P["muted"],fontsize=8)
|
| 364 |
+
plt.setp(cb.ax.yaxis.get_ticklabels(),color=P["muted"])
|
| 365 |
+
cb.outline.set_edgecolor(P["border"])
|
| 366 |
+
fig.suptitle("CT Lung Volume β Multi-Plane Reconstruction",
|
| 367 |
+
color=P["text"],fontsize=12,fontweight="bold",y=1.02)
|
| 368 |
+
plt.tight_layout(); return fig
|
| 369 |
+
|
| 370 |
+
def update_slice(idx):
|
| 371 |
+
vol=_CACHE.get("vol")
|
| 372 |
+
if vol is None: return _empty("Upload DICOM files and run prediction first")
|
| 373 |
+
idx=int(np.clip(idx,0,vol.shape[0]-1)); D,H,W=vol.shape
|
| 374 |
+
fig,axes=plt.subplots(1,3,figsize=(15,5.2))
|
| 375 |
+
fig.patch.set_facecolor(P["navy"])
|
| 376 |
+
for ax,(img,ttl) in zip(axes,[(vol[idx],f"Axial Β· {idx+1} / {D}"),
|
| 377 |
+
(vol[:,H//2,:],"Coronal"),(vol[:,:,W//2],"Sagittal")]):
|
| 378 |
+
ax.set_facecolor(P["navy"])
|
| 379 |
+
ax.imshow(img,cmap="bone",vmin=0,vmax=1,aspect="auto",interpolation="bicubic")
|
| 380 |
+
ax.set_title(ttl,color=P["cyan"],fontsize=10,pad=8,fontweight="bold"); ax.axis("off")
|
| 381 |
plt.tight_layout(); return fig
|
| 382 |
|
| 383 |
+
# ββ PDF REPORT ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 384 |
def generate_pdf(bl,visits,mu,sigma,fvc_fig):
|
| 385 |
if not PDF_OK: return None
|
| 386 |
buf=io.BytesIO()
|
| 387 |
+
doc=SimpleDocTemplate(buf,pagesize=A4,
|
| 388 |
+
leftMargin=2*cm,rightMargin=2*cm,topMargin=2.2*cm,bottomMargin=2*cm)
|
| 389 |
+
W=A4[0]-4*cm; styles=getSampleStyleSheet()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
|
| 391 |
+
# Colors
|
| 392 |
+
cNavy = colors.HexColor("#0F2142")
|
| 393 |
+
cBlue = colors.HexColor("#0D5EAF")
|
| 394 |
+
cCyan = colors.HexColor("#00A8BC")
|
| 395 |
+
cGreen = colors.HexColor("#00B87C")
|
| 396 |
+
cAmber = colors.HexColor("#E8971A")
|
| 397 |
+
cRed = colors.HexColor("#E03C3C")
|
| 398 |
+
cSlate = colors.HexColor("#1E2D47")
|
| 399 |
+
cText = colors.HexColor("#1E293B")
|
| 400 |
+
cMuted = colors.HexColor("#64748B")
|
| 401 |
+
cLight = colors.HexColor("#F0F4FA")
|
| 402 |
+
cWhite = colors.white
|
| 403 |
+
|
| 404 |
+
def PS(name,**kw):
|
| 405 |
+
return ParagraphStyle(name,parent=styles.get(kw.pop("parent","Normal"),styles["Normal"]),**kw)
|
| 406 |
+
|
| 407 |
+
sDisplay = PS("Display", fontSize=28, fontName="Helvetica-Bold",
|
| 408 |
+
textColor=cNavy, alignment=TA_CENTER, spaceAfter=2)
|
| 409 |
+
sSubtitle= PS("Subtitle",fontSize=11, fontName="Helvetica",
|
| 410 |
+
textColor=cBlue, alignment=TA_CENTER, spaceAfter=6)
|
| 411 |
+
sMeta = PS("Meta", fontSize=8.5,fontName="Helvetica",
|
| 412 |
+
textColor=cMuted,alignment=TA_CENTER,spaceAfter=16)
|
| 413 |
+
sSection = PS("Section", fontSize=12, fontName="Helvetica-Bold",
|
| 414 |
+
textColor=cNavy, spaceBefore=18, spaceAfter=6,
|
| 415 |
+
borderPadding=(0,0,4,0))
|
| 416 |
+
sBody = PS("Body", fontSize=9.5, fontName="Helvetica",
|
| 417 |
+
textColor=cText, leading=15, spaceAfter=5)
|
| 418 |
+
sMono = PS("Mono", fontSize=9, fontName="Courier",
|
| 419 |
+
textColor=cText, leading=13, spaceAfter=3)
|
| 420 |
+
sLabel = PS("Label", fontSize=8, fontName="Helvetica-Bold",
|
| 421 |
+
textColor=cMuted, spaceAfter=2)
|
| 422 |
+
sBullet = PS("Bullet", fontSize=9.5, fontName="Helvetica",
|
| 423 |
+
textColor=cText, leading=15, leftIndent=12, spaceAfter=4)
|
| 424 |
+
sWarn = PS("Warn", fontSize=8, fontName="Helvetica-Oblique",
|
| 425 |
+
textColor=colors.HexColor("#92400E"), alignment=TA_CENTER)
|
| 426 |
+
sFooter = PS("Footer", fontSize=7.5, fontName="Helvetica",
|
| 427 |
+
textColor=cMuted, alignment=TA_CENTER)
|
| 428 |
+
sBadge = PS("Badge", fontSize=11, fontName="Helvetica-Bold",
|
| 429 |
+
alignment=TA_CENTER)
|
| 430 |
+
|
| 431 |
+
# Patient data
|
| 432 |
pid=str(bl["Patient"]); age=int(bl["Age"])
|
| 433 |
sex="Male" if bl["Sex_enc"]==1. else "Female"
|
| 434 |
smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
|
|
|
|
| 436 |
fvc_6m=mu[26]; fvc_1yr=mu[52]; fvc_2yr=mu[104]
|
| 437 |
dec_pct=(fvc_bl-fvc_1yr)/fvc_bl*100; sig_1yr=sigma[52]
|
| 438 |
sev="Mild" if pct>=70 else "Moderate" if pct>=50 else "Severe"
|
| 439 |
+
sev_col=cGreen if sev=="Mild" else cAmber if sev=="Moderate" else cRed
|
| 440 |
+
sev_bg=(colors.HexColor("#D1FAE5") if sev=="Mild" else
|
| 441 |
+
colors.HexColor("#FEF3C7") if sev=="Moderate" else colors.HexColor("#FEE2E2"))
|
| 442 |
+
traj,monitor=(("Stable β within expected physiological variation","every 6 months") if dec_pct<5 else
|
| 443 |
+
("Slow Decline β clinically meaningful progression","every 3β4 months") if dec_pct<10 else
|
| 444 |
+
("Rapid Decline β urgent clinical attention warranted","monthly"))
|
| 445 |
wks10=next((w for w in range(145) if mu[w]<=fvc_bl*0.90),None)
|
| 446 |
vis_wk=visits["WeekDelta"].values.astype(float); vis_fvc=visits["FVC"].values.astype(float)
|
| 447 |
|
| 448 |
story=[]
|
| 449 |
+
|
| 450 |
+
# ββ Title block ββ
|
| 451 |
+
story.append(Paragraph("FibrosisNet-V4", sDisplay))
|
| 452 |
+
story.append(Paragraph("Pulmonary Fibrosis Progression Report", sSubtitle))
|
| 453 |
+
story.append(Paragraph(
|
| 454 |
+
f"Generated {datetime.datetime.now().strftime('%d %B %Y at %H:%M')} Β· "
|
| 455 |
+
f"Swin-Tiny 2.5D Β· OOF β6.6629 Β· Beats Kaggle baseline β", sMeta))
|
| 456 |
+
|
| 457 |
+
# Decorative rule
|
| 458 |
+
story.append(HRFlowable(width="100%",thickness=3,color=cNavy,spaceAfter=0))
|
| 459 |
+
story.append(HRFlowable(width="100%",thickness=1,color=cCyan,spaceBefore=2,spaceAfter=16))
|
| 460 |
+
|
| 461 |
+
# ββ Patient profile ββ
|
| 462 |
+
story.append(Paragraph("Patient Profile", sSection))
|
| 463 |
+
def cell(label, value, bg=cLight):
|
| 464 |
+
return [Paragraph(f"<font color='#64748B' size='8'>{label}</font><br/>"
|
| 465 |
+
f"<font name='Helvetica-Bold' size='10'>{value}</font>",
|
| 466 |
+
PS(f"c{label}",fontSize=10,leading=14))]
|
| 467 |
+
|
| 468 |
+
profile_data=[
|
| 469 |
+
[cell("PATIENT ID", pid), cell("AGE", f"{age} years"), cell("SEX", sex)],
|
| 470 |
+
[cell("SMOKING HISTORY", smoking), cell("BASELINE FVC", f"{fvc_bl:.0f} ml"),
|
| 471 |
+
cell("% PREDICTED", f"{pct:.1f}%")],
|
| 472 |
+
[cell("ESTIMATED NORMAL FVC", f"{norm:.0f} ml"),
|
| 473 |
+
cell("MODEL INPUTS","Baseline visit only (CT + tabular)"),
|
| 474 |
+
cell("FOLLOW-UP VISITS",f"{len(vis_wk)} recorded in CSV")],
|
| 475 |
+
]
|
| 476 |
+
pt=Table(profile_data,colWidths=[W/3]*3)
|
| 477 |
pt.setStyle(TableStyle([
|
| 478 |
+
("BACKGROUND",(0,0),(-1,-1),cLight),
|
| 479 |
+
("ROWBACKGROUNDS",(0,0),(-1,-1),[cLight,colors.HexColor("#E8EEF8")]),
|
| 480 |
+
("BOX",(0,0),(-1,-1),1,colors.HexColor("#CBD5E1")),
|
| 481 |
+
("INNERGRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
|
| 482 |
+
("TOPPADDING",(0,0),(-1,-1),8),("BOTTOMPADDING",(0,0),(-1,-1),8),
|
| 483 |
+
("LEFTPADDING",(0,0),(-1,-1),10),("RIGHTPADDING",(0,0),(-1,-1),8),
|
| 484 |
+
("VALIGN",(0,0),(-1,-1),"MIDDLE"),
|
| 485 |
+
]))
|
|
|
|
| 486 |
story.append(pt); story.append(Spacer(1,10))
|
| 487 |
|
| 488 |
+
# ββ Severity badge ββ
|
| 489 |
+
story.append(Paragraph("Severity Assessment (ATS / ERS Classification)", sSection))
|
| 490 |
+
sev_badge_style=PS("SevBadge",fontSize=15,fontName="Helvetica-Bold",
|
| 491 |
+
textColor=sev_col,alignment=TA_CENTER)
|
| 492 |
+
sev_sub=PS("SevSub",fontSize=9,fontName="Helvetica",
|
| 493 |
+
textColor=cMuted,alignment=TA_CENTER,spaceAfter=2)
|
| 494 |
+
sev_tbl=Table([[Paragraph(f"{sev.upper()}",sev_badge_style)],
|
| 495 |
+
[Paragraph(f"{pct:.1f}% predicted FVC Β· Mild β₯70% | Moderate 50β69% | Severe <50%",sev_sub)]],
|
| 496 |
+
colWidths=[W])
|
| 497 |
+
sev_tbl.setStyle(TableStyle([
|
| 498 |
+
("BACKGROUND",(0,0),(-1,-1),sev_bg),
|
| 499 |
+
("BOX",(0,0),(-1,-1),1.5,sev_col),
|
| 500 |
+
("TOPPADDING",(0,0),(-1,-1),10),("BOTTOMPADDING",(0,0),(-1,-1),8),
|
| 501 |
+
]))
|
| 502 |
+
story.append(sev_tbl); story.append(Spacer(1,8))
|
| 503 |
+
story.append(Paragraph(f"<b>Trajectory Classification:</b> {traj}", sBody))
|
| 504 |
+
|
| 505 |
+
# ββ Predictions table ββ
|
| 506 |
+
story.append(Paragraph("Predicted FVC Trajectory", sSection))
|
| 507 |
+
ph=["Timepoint","Predicted FVC","Change from Baseline","Β± 1Ο Uncertainty Range"]
|
| 508 |
+
pd_rows=[
|
| 509 |
+
["6 months (Week 26)", f"{fvc_6m:.0f} ml",
|
| 510 |
+
f"β{fvc_bl-fvc_6m:.0f} ml ({(fvc_bl-fvc_6m)/fvc_bl*100:.1f}%)",
|
| 511 |
+
f"{fvc_6m-sigma[26]:.0f} β {fvc_6m+sigma[26]:.0f} ml"],
|
| 512 |
+
["1 year (Week 52)", f"{fvc_1yr:.0f} ml",
|
| 513 |
+
f"β{fvc_bl-fvc_1yr:.0f} ml ({dec_pct:.1f}% / yr)",
|
| 514 |
+
f"{fvc_1yr-sig_1yr:.0f} β {fvc_1yr+sig_1yr:.0f} ml"],
|
| 515 |
+
["2 years (Week 104)", f"{fvc_2yr:.0f} ml",
|
| 516 |
+
f"β{fvc_bl-fvc_2yr:.0f} ml ({(fvc_bl-fvc_2yr)/fvc_bl*100:.1f}%)",
|
| 517 |
+
f"{fvc_2yr-sigma[104]:.0f} β {fvc_2yr+sigma[104]:.0f} ml"],
|
| 518 |
+
]
|
| 519 |
+
prt=Table([ph]+pd_rows,colWidths=[W*0.28,W*0.17,W*0.30,W*0.25])
|
| 520 |
prt.setStyle(TableStyle([
|
| 521 |
+
("BACKGROUND",(0,0),(-1,0),cNavy),("TEXTCOLOR",(0,0),(-1,0),cWhite),
|
| 522 |
+
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,0),9),
|
| 523 |
+
("ROWBACKGROUNDS",(0,1),(-1,-1),[cLight,colors.HexColor("#E8EEF8")]),
|
| 524 |
+
("FONTSIZE",(0,1),(-1,-1),9),("FONTNAME",(0,1),(0,-1),"Helvetica-Bold"),
|
| 525 |
+
("TEXTCOLOR",(0,1),(0,-1),cNavy),
|
| 526 |
+
("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
|
| 527 |
+
("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),
|
| 528 |
+
("LEFTPADDING",(0,0),(-1,-1),9),("ALIGN",(1,1),(-1,-1),"CENTER"),
|
| 529 |
+
]))
|
| 530 |
story.append(prt); story.append(Spacer(1,6))
|
|
|
|
|
|
|
| 531 |
|
| 532 |
+
thr_txt=(f"Week {wks10} (~{wks10//4} months from baseline)" if wks10
|
| 533 |
+
else "Not reached within the 2.5-year prediction horizon")
|
| 534 |
+
story.append(Paragraph(f"<b>Time to 10% FVC decline threshold:</b> {thr_txt}", sBody))
|
| 535 |
+
|
| 536 |
+
# ββ Observed vs predicted ββ
|
| 537 |
if len(vis_wk)>0:
|
| 538 |
+
story.append(Paragraph("Observed vs Predicted (Actual Clinical Visits from CSV)", sSection))
|
| 539 |
+
obs_h=["Visit Week","Actual FVC","Predicted FVC","Error","Within Β±1Ο?"]
|
| 540 |
+
obs_rows=[]; errs=[]
|
| 541 |
for wk,afvc in zip(vis_wk,vis_fvc):
|
| 542 |
wi=int(np.clip(int(wk),0,144)); pred=mu[wi]; err=afvc-pred; errs.append(abs(err))
|
| 543 |
+
within="β" if abs(err)<=sigma[wi] else "β"
|
| 544 |
+
obs_rows.append([f"Week {int(wk)}",f"{afvc:.0f} ml",f"{pred:.0f} ml",
|
| 545 |
+
f"{'+' if err>=0 else ''}{err:.0f} ml",within])
|
| 546 |
+
mae=np.mean(errs)
|
| 547 |
+
obs_rows.append(["","","Mean Absolute Error",f"{mae:.1f} ml",""])
|
| 548 |
+
ot=Table([obs_h]+obs_rows,colWidths=[W*0.16,W*0.18,W*0.20,W*0.16,W*0.15])
|
| 549 |
ot.setStyle(TableStyle([
|
| 550 |
+
("BACKGROUND",(0,0),(-1,0),cBlue),("TEXTCOLOR",(0,0),(-1,0),cWhite),
|
| 551 |
+
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,0),9),
|
| 552 |
+
("ROWBACKGROUNDS",(0,1),(-1,-2),[cLight,colors.HexColor("#E8EEF8")]),
|
| 553 |
+
("BACKGROUND",(0,-1),(-1,-1),colors.HexColor("#E8EEF8")),
|
| 554 |
+
("FONTNAME",(0,-1),(-1,-1),"Helvetica-Bold"),("FONTSIZE",(0,-1),(-1,-1),9),
|
| 555 |
+
("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
|
| 556 |
+
("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),
|
| 557 |
+
("LEFTPADDING",(0,0),(-1,-1),9),("ALIGN",(1,1),(-1,-1),"CENTER"),
|
| 558 |
+
]))
|
| 559 |
+
story.append(ot); story.append(Spacer(1,4))
|
| 560 |
+
|
| 561 |
+
# ββ FVC chart ββ
|
| 562 |
+
story.append(Paragraph("FVC Decline Trajectory Chart", sSection))
|
| 563 |
+
fig_buf=io.BytesIO()
|
| 564 |
+
fvc_fig.savefig(fig_buf,format="png",dpi=140,bbox_inches="tight")
|
| 565 |
fig_buf.seek(0)
|
| 566 |
+
story.append(RLImage(fig_buf,width=W,height=W*7.5/16))
|
| 567 |
+
story.append(Spacer(1,10))
|
| 568 |
|
| 569 |
+
# ββ Recommendations ββ
|
| 570 |
+
story.append(Paragraph("Clinical Recommendations", sSection))
|
| 571 |
+
recs=[
|
| 572 |
+
f"<b>Spirometry monitoring:</b> {monitor}",
|
| 573 |
+
"<b>Physical assessment:</b> 6-minute walk test at each follow-up visit",
|
| 574 |
+
"<b>Treatment:</b> " + (
|
| 575 |
+
"Discuss antifibrotic therapy (nintedanib / pirfenidone) with a pulmonologist"
|
| 576 |
+
if sev!="Mild" or dec_pct>=10 else
|
| 577 |
+
"Continue current management plan; reassess if trajectory worsens"),
|
| 578 |
+
"<b>Patient education:</b> Pulmonary rehabilitation referral recommended",
|
| 579 |
+
]
|
| 580 |
+
for r in recs:
|
| 581 |
+
story.append(Paragraph(f" β’ {r}", sBullet))
|
| 582 |
+
story.append(Spacer(1,6))
|
| 583 |
+
summary=("Lung function is relatively stable over the predicted horizon."
|
| 584 |
+
if dec_pct<=3 else
|
| 585 |
+
f"Lung function is {sev.lower()}ly reduced. Predicted annual decline ~{dec_pct:.0f}%. "
|
| 586 |
+
+("Close monitoring is recommended." if dec_pct<10
|
| 587 |
+
else "Urgent specialist review and treatment discussion is strongly recommended."))
|
| 588 |
+
story.append(Paragraph(f"<b>Patient-Facing Summary:</b> {summary}", sBody))
|
| 589 |
|
| 590 |
+
# ββ Footer ββ
|
| 591 |
+
story.append(Spacer(1,16))
|
| 592 |
+
story.append(HRFlowable(width="100%",thickness=1,color=colors.HexColor("#CBD5E1"),spaceAfter=8))
|
| 593 |
story.append(Paragraph(
|
| 594 |
+
"β This report is produced by an AI research model for academic and research purposes only. "
|
| 595 |
+
"It must not substitute for clinical diagnosis or treatment decisions without evaluation "
|
| 596 |
+
"by a qualified pulmonologist.", sWarn))
|
| 597 |
story.append(Spacer(1,4))
|
| 598 |
+
story.append(Paragraph(
|
| 599 |
+
f"FibrosisNet-V4 Β· Swin-Tiny 2.5D Backbone Β· "
|
| 600 |
+
f"OOF β6.6629 vs Kaggle baseline β6.6743 Β· "
|
| 601 |
+
f"Balaji R Β· NIT Calicut Β· May 2026", sFooter))
|
| 602 |
|
| 603 |
+
doc.build(story); buf.seek(0); return buf.getvalue()
|
|
|
|
| 604 |
|
| 605 |
+
# ββ CACHE & CALLBACKS βββββββββββββββββββββββββββββββββββββββββ
|
| 606 |
+
_CACHE={"vol":None,"df":None,"last_fig":None,"last_bl":None,
|
| 607 |
+
"last_visits":None,"last_mu":None,"last_sigma":None}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 608 |
|
|
|
|
| 609 |
def on_csv_upload(csv_file):
|
| 610 |
+
if csv_file is None: return gr.update(choices=[],value=None),"Upload a CSV file."
|
| 611 |
try:
|
| 612 |
df_raw=pd.read_csv(csv_file.name if hasattr(csv_file,"name") else csv_file)
|
| 613 |
df_raw.columns=[c.strip() for c in df_raw.columns]
|
| 614 |
+
if "Patient" not in df_raw.columns:
|
| 615 |
+
return gr.update(choices=[],value=None),"'Patient' column not found."
|
| 616 |
df_prep=prepare_features(df_raw); _CACHE["df"]=df_prep
|
| 617 |
pids=sorted(df_prep["Patient"].unique().tolist())
|
| 618 |
+
msg=(f"β
{len(pids)} patients Β· {len(df_raw)} rows\n"
|
| 619 |
+
f"Columns: {', '.join(df_raw.columns[:6].tolist())}")
|
| 620 |
return gr.update(choices=pids,value=pids[0] if pids else None),msg
|
| 621 |
+
except Exception as e: return gr.update(choices=[],value=None),f"β {e}"
|
| 622 |
|
| 623 |
def on_dicom_upload(dicom_files):
|
| 624 |
+
if not dicom_files: return gr.update(),"No DICOM files."
|
| 625 |
n=len(dicom_files); pid=detect_pid(dicom_files); df=_CACHE.get("df")
|
| 626 |
if pid and df is not None and pid in df["Patient"].values:
|
| 627 |
+
return gr.update(value=pid),f"β
{n} files Β· Patient ID auto-matched:\n{pid}"
|
| 628 |
+
elif pid: return gr.update(),f"β {n} files Β· ID '{pid}' not in CSV\nSelect manually below"
|
| 629 |
+
return gr.update(),f"βΉ {n} files uploaded\nNo Patient ID in DICOM tags β select manually"
|
| 630 |
|
| 631 |
def on_patient_select(pid):
|
| 632 |
df=_CACHE.get("df")
|
|
|
|
| 635 |
if bl is None: return f"Patient '{pid}' not found."
|
| 636 |
sex="Male" if bl["Sex_enc"]==1. else "Female"
|
| 637 |
smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
|
| 638 |
+
lines="\n".join(f" Week {int(r['WeekDelta']):>4} βΊ {r['FVC']:.0f} ml" for _,r in visits.iterrows())
|
| 639 |
+
sev="Mild" if float(bl['Percent'])>=70 else "Moderate" if float(bl['Percent'])>=50 else "Severe"
|
| 640 |
+
return (f"ID βΊ {pid}\n"
|
| 641 |
+
f"Age/Sex βΊ {int(bl['Age'])} yrs / {sex}\n"
|
| 642 |
+
f"Smoking βΊ {smoking}\n"
|
| 643 |
+
f"Baseline βΊ {bl['BaselineFVC']:.0f} ml ({bl['Percent']:.1f}% predicted)\n"
|
| 644 |
+
f"Normal βΊ {bl['PredictedFVC']:.0f} ml (estimated)\n"
|
| 645 |
+
f"Severity βΊ {sev}\n\n"
|
| 646 |
+
f"Recorded Visits\n{'β'*24}\n{lines}")
|
| 647 |
|
| 648 |
def run_all(pid,dicom_files):
|
| 649 |
+
NO=(gr.update(visible=False),gr.update(visible=False))
|
| 650 |
df=_CACHE.get("df")
|
| 651 |
+
if df is None: return _empty("Upload CSV first"),_empty(""),"Upload CSV first.",*NO
|
| 652 |
+
if not pid: return _empty("Select a patient"),_empty(""),"Select a Patient ID.",*NO
|
| 653 |
bl,visits=extract_patient(df,pid)
|
| 654 |
+
if bl is None: return _empty(f"Patient {pid} not found"),_empty(""),"Not found.",*NO
|
| 655 |
volume=load_dicoms(dicom_files) if dicom_files else None
|
| 656 |
_CACHE["vol"]=volume
|
| 657 |
mu,sigma=run_inference(bl,volume,float(bl.get("BaselineWeek",0.)))
|
| 658 |
fvc_fig=make_fvc_plot(bl,visits,mu,sigma)
|
| 659 |
+
ct_view=(make_multiview(volume) if volume is not None
|
| 660 |
+
else _empty("No DICOM uploaded β CT view unavailable"))
|
| 661 |
_CACHE.update({"last_fig":fvc_fig,"last_bl":bl,"last_visits":visits,"last_mu":mu,"last_sigma":sigma})
|
| 662 |
|
| 663 |
fvc_bl=float(bl["BaselineFVC"]); pct=float(bl["Percent"])
|
| 664 |
sev="Mild" if pct>=70 else "Moderate" if pct>=50 else "Severe"
|
| 665 |
dec_pct=(fvc_bl-mu[52])/fvc_bl*100
|
| 666 |
traj,monitor=(("STABLE","every 6 months") if dec_pct<5 else
|
| 667 |
+
("SLOW DECLINE","every 3β4 months") if dec_pct<10 else ("RAPID DECLINE","monthly"))
|
| 668 |
wks10=next((w for w in range(145) if mu[w]<=fvc_bl*0.90),None)
|
| 669 |
vis_wk=visits["WeekDelta"].values.astype(float); vis_fvc=visits["FVC"].values.astype(float)
|
| 670 |
+
sex="Male" if bl["Sex_enc"]==1. else "Female"
|
| 671 |
+
smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
|
| 672 |
+
|
| 673 |
obs=""
|
| 674 |
if len(vis_wk)>0:
|
| 675 |
+
rows=[f" {'Week':>6} {'Actual':>8} {'Predicted':>10} {'Error':>8}"," "+"β"*42]
|
| 676 |
errs=[]
|
| 677 |
for wk,afvc in zip(vis_wk,vis_fvc):
|
| 678 |
wi=int(np.clip(int(wk),0,144)); pred=mu[wi]; err=afvc-pred; errs.append(abs(err))
|
| 679 |
+
rows.append(f" {int(wk):>6} {afvc:>8.0f} {pred:>10.0f} {err:>+8.0f} ml")
|
| 680 |
+
rows.append(f"\n Mean Absolute Error βΊ {np.mean(errs):.1f} ml")
|
| 681 |
+
obs="\n\nOBSERVED vs PREDICTED\n"+"\n".join(rows)
|
| 682 |
|
| 683 |
+
report=(
|
| 684 |
+
f" FIBROSISNET-V4 Β· CLINICAL SUMMARY\n"
|
| 685 |
+
f"{'β'*50}\n\n"
|
| 686 |
+
f" PATIENT\n"
|
| 687 |
+
f" ID βΊ {pid}\n"
|
| 688 |
+
f" Age / Sex βΊ {int(bl['Age'])} yrs / {sex}\n"
|
| 689 |
+
f" Smoking βΊ {smoking}\n"
|
| 690 |
+
f" Baseline βΊ {fvc_bl:.0f} ml ({pct:.1f}% predicted)\n"
|
| 691 |
+
f" Normal βΊ {float(bl['PredictedFVC']):.0f} ml (estimated)\n\n"
|
| 692 |
+
f"{'β'*50}\n"
|
| 693 |
+
f" SEVERITY (ATS/ERS)\n"
|
| 694 |
+
f" βΊ {sev.upper()} β {pct:.1f}% predicted FVC\n"
|
| 695 |
+
f" Mild β₯70% β Moderate 50β69% β Severe <50%\n\n"
|
| 696 |
+
f"{'β'*50}\n"
|
| 697 |
+
f" TRAJECTORY\n"
|
| 698 |
+
f" βΊ {traj}\n\n"
|
| 699 |
+
f" 6 months βΊ {mu[26]:.0f} ml (β{fvc_bl-mu[26]:.0f} ml)\n"
|
| 700 |
+
f" 1 year βΊ {mu[52]:.0f} ml (β{fvc_bl-mu[52]:.0f} ml Β· {dec_pct:.1f}%/yr)\n"
|
| 701 |
+
f" 2 years βΊ {mu[104]:.0f} ml (β{fvc_bl-mu[104]:.0f} ml cumulative)\n"
|
| 702 |
+
f" Β±1Ο at 1yr βΊ {mu[52]-sigma[52]:.0f} β {mu[52]+sigma[52]:.0f} ml\n\n"
|
| 703 |
+
f"{'β'*50}\n"
|
| 704 |
+
f" 10% DECLINE THRESHOLD\n"
|
| 705 |
+
f" βΊ {'Week '+str(wks10)+f' (~{wks10//4} months)' if wks10 else 'Not reached within 2.5-yr horizon'}\n"
|
| 706 |
+
f"{obs}\n\n"
|
| 707 |
+
f"{'β'*50}\n"
|
| 708 |
+
f" MONITORING\n"
|
| 709 |
+
f" βΊ Spirometry {monitor}\n"
|
| 710 |
+
f" βΊ {'Discuss antifibrotic therapy with specialist' if sev!='Mild' or dec_pct>=10 else 'Continue current management plan'}\n\n"
|
| 711 |
+
f"{'β'*50}\n"
|
| 712 |
+
f" β AI research model Β· Not for clinical use\n"
|
| 713 |
+
f" OOF β6.6629 β Kaggle baseline β6.6743 β"
|
| 714 |
+
)
|
| 715 |
return fvc_fig,ct_view,report,gr.update(visible=True),gr.update(visible=False)
|
| 716 |
|
| 717 |
def on_download_pdf():
|
|
|
|
| 720 |
if bl is None or mu is None: return None
|
| 721 |
pdf_bytes=generate_pdf(bl,visits,mu,sigma,fig)
|
| 722 |
if pdf_bytes is None: return None
|
| 723 |
+
path=f"/tmp/FibrosisNet_{str(bl['Patient'])[:20]}.pdf"
|
| 724 |
with open(path,"wb") as f: f.write(pdf_bytes)
|
| 725 |
return path
|
| 726 |
|
| 727 |
# ββ CSS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 728 |
CSS="""
|
| 729 |
+
@import url('https://fonts.googleapis.com/css2?family=Syne:wght@400;500;600;700;800&family=IBM+Plex+Mono:wght@300;400;500&family=IBM+Plex+Sans:wght@300;400;500;600&display=swap');
|
| 730 |
+
|
| 731 |
+
:root{
|
| 732 |
+
--navy:#050E1F; --navy2:#0A1628; --navy3:#0F2142; --navy4:#162035;
|
| 733 |
+
--blue:#0D5EAF; --cyan:#00C9E0; --cyan2:#00A8BC;
|
| 734 |
+
--green:#00B87C; --amber:#E8971A; --red:#E03C3C;
|
| 735 |
+
--slate:#1E2D47; --border:#1C2E4A; --border2:#253550;
|
| 736 |
+
--text:#D0DCF0; --muted:#6B82A8; --muted2:#4A637D;
|
| 737 |
+
--radius:12px; --radius-sm:8px;
|
| 738 |
+
}
|
| 739 |
+
|
| 740 |
+
/* ββ Global ββ */
|
| 741 |
+
*{box-sizing:border-box;}
|
| 742 |
+
body,.gradio-container{
|
| 743 |
+
background:var(--navy) !important;
|
| 744 |
+
font-family:'IBM Plex Sans',sans-serif !important;
|
| 745 |
+
color:var(--text) !important;
|
| 746 |
+
}
|
| 747 |
+
.gradio-container{max-width:1380px !important; margin:0 auto !important;}
|
| 748 |
+
|
| 749 |
+
/* ββ Scrollbar ββ */
|
| 750 |
+
::-webkit-scrollbar{width:4px;height:4px;}
|
| 751 |
+
::-webkit-scrollbar-track{background:var(--navy2);}
|
| 752 |
+
::-webkit-scrollbar-thumb{background:var(--border2);border-radius:2px;}
|
| 753 |
+
|
| 754 |
+
/* ββ Header ββ */
|
| 755 |
+
.fn-header{
|
| 756 |
+
background:linear-gradient(135deg,#050E1F 0%,#0A1D38 45%,#0D3060 100%);
|
| 757 |
+
border:1px solid var(--border2);border-radius:16px;
|
| 758 |
+
padding:32px 42px 28px;margin-bottom:22px;
|
| 759 |
+
box-shadow:0 0 0 1px rgba(0,201,224,0.08),0 20px 60px rgba(0,0,0,0.5);
|
| 760 |
+
position:relative;overflow:hidden;
|
| 761 |
+
}
|
| 762 |
+
.fn-header::before{
|
| 763 |
+
content:'';position:absolute;top:-60px;right:-60px;
|
| 764 |
+
width:280px;height:280px;border-radius:50%;
|
| 765 |
+
background:radial-gradient(circle,rgba(0,201,224,0.07) 0%,transparent 70%);
|
| 766 |
+
pointer-events:none;
|
| 767 |
+
}
|
| 768 |
+
.fn-header::after{
|
| 769 |
+
content:'';position:absolute;bottom:-40px;left:30%;
|
| 770 |
+
width:200px;height:200px;border-radius:50%;
|
| 771 |
+
background:radial-gradient(circle,rgba(13,94,175,0.08) 0%,transparent 70%);
|
| 772 |
+
pointer-events:none;
|
| 773 |
+
}
|
| 774 |
+
.fn-logo{
|
| 775 |
+
font-family:'Syne',sans-serif !important;
|
| 776 |
+
font-size:32px;font-weight:800;letter-spacing:-1px;
|
| 777 |
+
color:white;margin:0 0 6px;
|
| 778 |
+
background:linear-gradient(135deg,#ffffff 0%,#00C9E0 100%);
|
| 779 |
+
-webkit-background-clip:text;-webkit-text-fill-color:transparent;background-clip:text;
|
| 780 |
+
}
|
| 781 |
+
.fn-tagline{color:var(--muted);font-size:13px;letter-spacing:.2px;margin:0;}
|
| 782 |
+
.fn-badges{display:flex;gap:8px;margin-top:14px;flex-wrap:wrap;}
|
| 783 |
+
.fn-badge{
|
| 784 |
+
background:rgba(0,201,224,0.08);border:1px solid rgba(0,201,224,0.2);
|
| 785 |
+
color:var(--cyan);font-size:11px;font-weight:500;letter-spacing:.4px;
|
| 786 |
+
padding:3px 10px;border-radius:20px;
|
| 787 |
+
font-family:'IBM Plex Mono',monospace;
|
| 788 |
+
}
|
| 789 |
+
|
| 790 |
+
/* ββ Step cards ββ */
|
| 791 |
+
.step-wrap{
|
| 792 |
+
background:var(--navy4);border:1px solid var(--border);
|
| 793 |
+
border-radius:var(--radius);margin-bottom:10px;
|
| 794 |
+
overflow:hidden;transition:border-color .2s;
|
| 795 |
+
}
|
| 796 |
+
.step-wrap:hover{border-color:var(--border2);}
|
| 797 |
+
.step-head{
|
| 798 |
+
display:flex;align-items:center;gap:10px;
|
| 799 |
+
padding:12px 16px 8px;
|
| 800 |
+
}
|
| 801 |
+
.step-num{
|
| 802 |
+
width:24px;height:24px;border-radius:50%;
|
| 803 |
+
background:linear-gradient(135deg,var(--blue),var(--cyan2));
|
| 804 |
+
display:flex;align-items:center;justify-content:center;
|
| 805 |
+
font-family:'Syne',sans-serif;font-size:12px;font-weight:700;color:white;
|
| 806 |
+
flex-shrink:0;box-shadow:0 0 12px rgba(0,201,224,0.25);
|
| 807 |
+
}
|
| 808 |
+
.step-title{
|
| 809 |
+
font-family:'Syne',sans-serif;font-size:13px;font-weight:600;
|
| 810 |
+
color:var(--text);letter-spacing:.2px;
|
| 811 |
+
}
|
| 812 |
+
.step-body{padding:0 16px 14px;}
|
| 813 |
+
|
| 814 |
+
/* ββ Form inputs ββ */
|
| 815 |
+
label{
|
| 816 |
+
font-family:'IBM Plex Sans',sans-serif !important;
|
| 817 |
+
font-size:11.5px !important;font-weight:500 !important;
|
| 818 |
+
color:var(--muted) !important;letter-spacing:.3px !important;
|
| 819 |
+
text-transform:uppercase !important;
|
| 820 |
+
}
|
| 821 |
+
input,textarea,select,.gr-input,.gr-textarea{
|
| 822 |
+
background:var(--slate) !important;
|
| 823 |
+
border:1px solid var(--border) !important;
|
| 824 |
+
border-radius:var(--radius-sm) !important;
|
| 825 |
+
color:var(--text) !important;
|
| 826 |
+
font-family:'IBM Plex Sans',sans-serif !important;
|
| 827 |
+
font-size:13px !important;
|
| 828 |
+
transition:border-color .2s,box-shadow .2s !important;
|
| 829 |
+
}
|
| 830 |
+
input:focus,textarea:focus{
|
| 831 |
+
border-color:var(--cyan2) !important;
|
| 832 |
+
box-shadow:0 0 0 3px rgba(0,201,224,0.12) !important;outline:none !important;
|
| 833 |
+
}
|
| 834 |
+
|
| 835 |
+
/* Status boxes */
|
| 836 |
+
.status-out textarea{
|
| 837 |
+
background:rgba(0,201,224,0.04) !important;
|
| 838 |
+
border:1px solid rgba(0,201,224,0.15) !important;
|
| 839 |
+
color:var(--cyan) !important;
|
| 840 |
+
font-family:'IBM Plex Mono',monospace !important;
|
| 841 |
+
font-size:11.5px !important;line-height:1.6 !important;
|
| 842 |
+
}
|
| 843 |
+
|
| 844 |
+
/* Patient preview */
|
| 845 |
+
.pat-preview textarea{
|
| 846 |
+
background:var(--navy2) !important;
|
| 847 |
+
border:1px solid var(--border2) !important;
|
| 848 |
+
color:var(--text) !important;
|
| 849 |
+
font-family:'IBM Plex Mono',monospace !important;
|
| 850 |
+
font-size:12px !important;line-height:1.75 !important;
|
| 851 |
+
border-radius:var(--radius-sm) !important;
|
| 852 |
+
}
|
| 853 |
+
|
| 854 |
+
/* Report box */
|
| 855 |
+
.report-out textarea{
|
| 856 |
+
background:var(--navy2) !important;
|
| 857 |
+
border:1px solid var(--border2) !important;
|
| 858 |
+
color:var(--text) !important;
|
| 859 |
+
font-family:'IBM Plex Mono',monospace !important;
|
| 860 |
+
font-size:12px !important;line-height:1.8 !important;
|
| 861 |
+
border-radius:var(--radius-sm) !important;
|
| 862 |
+
padding:16px !important;
|
| 863 |
+
}
|
| 864 |
+
|
| 865 |
+
/* Dropdown */
|
| 866 |
+
.gr-dropdown select,.gr-dropdown input{
|
| 867 |
+
background:var(--slate) !important;color:var(--text) !important;
|
| 868 |
+
border:1px solid var(--border) !important;
|
| 869 |
+
}
|
| 870 |
+
|
| 871 |
+
/* ββ Buttons ββ */
|
| 872 |
+
.run-btn button{
|
| 873 |
+
background:linear-gradient(135deg,#0D5EAF 0%,#00A8BC 100%) !important;
|
| 874 |
+
border:none !important;border-radius:10px !important;
|
| 875 |
+
font-family:'Syne',sans-serif !important;
|
| 876 |
+
font-size:15px !important;font-weight:700 !important;
|
| 877 |
+
letter-spacing:.3px !important;color:white !important;
|
| 878 |
+
padding:16px !important;width:100% !important;
|
| 879 |
+
box-shadow:0 4px 24px rgba(0,168,188,0.3) !important;
|
| 880 |
+
transition:all .25s !important;
|
| 881 |
+
}
|
| 882 |
+
.run-btn button:hover{
|
| 883 |
+
box-shadow:0 6px 32px rgba(0,168,188,0.45) !important;
|
| 884 |
+
transform:translateY(-2px) !important;
|
| 885 |
+
}
|
| 886 |
+
.run-btn button:active{transform:translateY(0) !important;}
|
| 887 |
+
|
| 888 |
+
.pdf-btn button{
|
| 889 |
+
background:linear-gradient(135deg,#00B87C 0%,#0B8C7A 100%) !important;
|
| 890 |
+
border:none !important;border-radius:8px !important;
|
| 891 |
+
font-family:'Syne',sans-serif !important;
|
| 892 |
+
font-size:13px !important;font-weight:600 !important;
|
| 893 |
+
color:white !important;
|
| 894 |
+
box-shadow:0 3px 16px rgba(0,184,124,0.3) !important;
|
| 895 |
+
transition:all .2s !important;
|
| 896 |
+
}
|
| 897 |
+
.pdf-btn button:hover{box-shadow:0 5px 20px rgba(0,184,124,0.45) !important;transform:translateY(-1px) !important;}
|
| 898 |
+
|
| 899 |
+
/* ββ Tabs ββ */
|
| 900 |
+
.tab-nav{
|
| 901 |
+
background:var(--navy3) !important;
|
| 902 |
+
border-bottom:1px solid var(--border) !important;
|
| 903 |
+
border-radius:var(--radius) var(--radius) 0 0 !important;
|
| 904 |
+
}
|
| 905 |
+
.tab-nav button{
|
| 906 |
+
font-family:'Syne',sans-serif !important;
|
| 907 |
+
font-size:13px !important;font-weight:600 !important;
|
| 908 |
+
color:var(--muted) !important;
|
| 909 |
+
border-bottom:2px solid transparent !important;
|
| 910 |
+
padding:12px 18px !important;
|
| 911 |
+
transition:all .2s !important;
|
| 912 |
+
}
|
| 913 |
+
.tab-nav button.selected{
|
| 914 |
+
color:var(--cyan) !important;
|
| 915 |
+
border-bottom:2px solid var(--cyan) !important;
|
| 916 |
+
background:transparent !important;
|
| 917 |
+
}
|
| 918 |
+
.tab-nav button:hover{color:var(--text) !important;}
|
| 919 |
+
|
| 920 |
+
/* Tab content */
|
| 921 |
+
.tabitem{
|
| 922 |
+
background:var(--navy3) !important;
|
| 923 |
+
border:1px solid var(--border) !important;
|
| 924 |
+
border-top:none !important;
|
| 925 |
+
border-radius:0 0 var(--radius) var(--radius) !important;
|
| 926 |
+
padding:16px !important;
|
| 927 |
+
}
|
| 928 |
+
|
| 929 |
+
/* ββ Output panels ββ */
|
| 930 |
+
.output-plot{
|
| 931 |
+
background:var(--navy2) !important;
|
| 932 |
+
border:1px solid var(--border) !important;
|
| 933 |
+
border-radius:var(--radius-sm) !important;
|
| 934 |
+
}
|
| 935 |
+
|
| 936 |
+
/* ββ DICOM accordion ββ */
|
| 937 |
+
.gr-accordion{
|
| 938 |
+
background:var(--navy4) !important;
|
| 939 |
+
border:1px solid var(--border) !important;
|
| 940 |
+
border-radius:var(--radius) !important;
|
| 941 |
+
}
|
| 942 |
+
.gr-accordion-header{
|
| 943 |
+
background:transparent !important;color:var(--text) !important;
|
| 944 |
+
font-family:'Syne',sans-serif !important;font-weight:600 !important;
|
| 945 |
+
font-size:13px !important;
|
| 946 |
+
}
|
| 947 |
+
.dicom-upload .file-preview{max-height:150px !important;overflow-y:auto !important;}
|
| 948 |
+
|
| 949 |
+
/* ββ Report header row ββ */
|
| 950 |
+
.report-header{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;}
|
| 951 |
+
.report-label{font-family:'Syne',sans-serif;font-size:14px;font-weight:700;color:var(--text);}
|
| 952 |
+
|
| 953 |
+
/* ββ Footer ββ */
|
| 954 |
+
.fn-footer{
|
| 955 |
+
text-align:center;margin-top:24px;padding:16px;
|
| 956 |
+
border-top:1px solid var(--border);
|
| 957 |
+
color:var(--muted2);font-size:11.5px;
|
| 958 |
+
font-family:'IBM Plex Mono',monospace;letter-spacing:.2px;
|
| 959 |
+
}
|
| 960 |
+
|
| 961 |
+
/* Slider */
|
| 962 |
+
input[type=range]{accent-color:var(--cyan) !important;}
|
| 963 |
+
|
| 964 |
+
/* File upload */
|
| 965 |
+
.file-preview{background:var(--slate) !important;border-color:var(--border) !important;}
|
| 966 |
+
.file-name{color:var(--text) !important;font-size:12px !important;}
|
| 967 |
"""
|
| 968 |
|
| 969 |
+
# ββ GRADIO APP ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 970 |
with gr.Blocks(title="FibrosisNet-V4",css=CSS,theme=gr.themes.Base()) as demo:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 971 |
|
| 972 |
+
# Header
|
| 973 |
+
gr.HTML("""
|
| 974 |
+
<div class="fn-header">
|
| 975 |
+
<div class="fn-logo">π« FibrosisNet-V4</div>
|
| 976 |
+
<p class="fn-tagline">Pulmonary Fibrosis Progression Prediction Β· Multi-Backbone 2.5D Deep Learning</p>
|
| 977 |
+
<div class="fn-badges">
|
| 978 |
+
<span class="fn-badge">Swin-Tiny 2.5D</span>
|
| 979 |
+
<span class="fn-badge">SE Attention Pooling</span>
|
| 980 |
+
<span class="fn-badge">Cross-Attention Fusion</span>
|
| 981 |
+
<span class="fn-badge">Calibrated Uncertainty</span>
|
| 982 |
+
<span class="fn-badge">OOF β6.6629 β</span>
|
| 983 |
+
</div>
|
| 984 |
+
</div>
|
| 985 |
+
""")
|
| 986 |
+
|
| 987 |
+
with gr.Row(equal_height=False, variant="panel"):
|
| 988 |
+
|
| 989 |
+
# ββ LEFT PANEL ββ
|
| 990 |
+
with gr.Column(scale=1, min_width=360):
|
| 991 |
+
|
| 992 |
+
# Step 1
|
| 993 |
+
gr.HTML("""<div class="step-wrap"><div class="step-head">
|
| 994 |
+
<div class="step-num">1</div>
|
| 995 |
+
<div class="step-title">Upload OSIC Test CSV</div></div></div>""")
|
| 996 |
+
csv_file = gr.File(label="test.csv Β· Patient Β· Weeks Β· FVC Β· Percent Β· Age Β· Sex Β· SmokingStatus",
|
| 997 |
+
file_types=[".csv"])
|
| 998 |
+
csv_status = gr.Textbox(label="CSV Status", lines=2, interactive=False,
|
| 999 |
+
elem_classes="status-out")
|
| 1000 |
+
|
| 1001 |
+
# Step 2
|
| 1002 |
+
gr.HTML("""<div class="step-wrap"><div class="step-head">
|
| 1003 |
+
<div class="step-num">2</div>
|
| 1004 |
+
<div class="step-title">Select Patient</div></div></div>""")
|
| 1005 |
+
patient_dd = gr.Dropdown(label="Patient ID Β· auto-populated from CSV",
|
| 1006 |
+
choices=[], value=None, allow_custom_value=True)
|
| 1007 |
+
patient_info = gr.Textbox(label="Patient Preview", lines=10,
|
| 1008 |
+
interactive=False, elem_classes="pat-preview")
|
| 1009 |
+
|
| 1010 |
+
# Step 3
|
| 1011 |
+
gr.HTML("""<div class="step-wrap"><div class="step-head">
|
| 1012 |
+
<div class="step-num">3</div>
|
| 1013 |
+
<div class="step-title">Run Prediction</div></div></div>""")
|
| 1014 |
+
predict_btn = gr.Button("π¬ Run FibrosisNet-V4 Prediction",
|
| 1015 |
+
elem_classes="run-btn", size="lg")
|
| 1016 |
+
|
| 1017 |
+
# Step 4 β DICOM (collapsed, scrollable list)
|
| 1018 |
+
gr.HTML("""<div class="step-wrap"><div class="step-head">
|
| 1019 |
+
<div class="step-num">4</div>
|
| 1020 |
+
<div class="step-title">Upload CT DICOM <span style="color:var(--muted);font-size:11px;font-weight:400">(optional)</span></div></div></div>""")
|
| 1021 |
+
with gr.Accordion("π©» Open DICOM Upload", open=False):
|
| 1022 |
+
gr.HTML('<p style="color:var(--muted);font-size:11.5px;padding:0 4px 8px;font-family:\'IBM Plex Sans\'">'
|
| 1023 |
+
'Upload <code>.dcm</code> slices for one patient\'s CT. '
|
| 1024 |
+
'Patient ID is auto-read from DICOM tags. '
|
| 1025 |
+
'The file list scrolls β it will not push the Predict button off screen.</p>')
|
| 1026 |
+
dicom_files = gr.File(label="DICOM slices (.dcm)",
|
| 1027 |
+
file_count="multiple",
|
| 1028 |
+
file_types=[".dcm",".DCM"],
|
| 1029 |
+
elem_classes="dicom-upload")
|
| 1030 |
+
dicom_status = gr.Textbox(label="DICOM Status", lines=2,
|
| 1031 |
+
interactive=False, elem_classes="status-out")
|
| 1032 |
+
|
| 1033 |
+
# ββ RIGHT PANEL ββ
|
| 1034 |
with gr.Column(scale=2):
|
| 1035 |
with gr.Tabs():
|
| 1036 |
+
with gr.Tab("π FVC Decline Graph"):
|
| 1037 |
+
fvc_plot = gr.Plot(label="", elem_classes="output-plot")
|
| 1038 |
+
|
| 1039 |
+
with gr.Tab("π« CT Lung Viewer"):
|
| 1040 |
+
ct_view = gr.Plot(label="", elem_classes="output-plot")
|
| 1041 |
+
gr.HTML('<p style="color:var(--muted);font-size:11.5px;margin:10px 0 4px;font-family:\'IBM Plex Mono\'">'
|
| 1042 |
+
'β Slice Explorer: drag slider to browse axial slices β</p>')
|
| 1043 |
+
slice_slider = gr.Slider(0,300,value=0,step=1,label="Axial Slice Index")
|
| 1044 |
+
slice_view = gr.Plot(label="", elem_classes="output-plot")
|
| 1045 |
slice_slider.change(fn=update_slice,inputs=slice_slider,outputs=slice_view)
|
| 1046 |
|
| 1047 |
+
with gr.Tab("π Clinical Report"):
|
| 1048 |
with gr.Row():
|
| 1049 |
+
gr.HTML('<div class="report-label">Clinical Summary Report</div>')
|
| 1050 |
+
pdf_btn = gr.Button("β¬ Download PDF",
|
| 1051 |
+
elem_classes="pdf-btn", size="sm", visible=False)
|
| 1052 |
+
report_box = gr.Textbox(label="", lines=36, max_lines=65,
|
| 1053 |
+
interactive=False, elem_classes="report-out")
|
| 1054 |
+
pdf_output = gr.File(label="PDF Ready", visible=False)
|
| 1055 |
|
| 1056 |
+
gr.HTML("""
|
| 1057 |
+
<div class="fn-footer">
|
| 1058 |
+
FibrosisNet-V4 Β· Balaji R Β· NIT Calicut Β· May 2026
|
| 1059 |
+
Β· OSIC Pulmonary Fibrosis Progression Β·
|
| 1060 |
+
β Research prototype β not for clinical use without physician oversight
|
| 1061 |
+
</div>
|
| 1062 |
+
""")
|
| 1063 |
+
|
| 1064 |
+
# Wiring
|
| 1065 |
csv_file.upload(fn=on_csv_upload,inputs=csv_file,outputs=[patient_dd,csv_status])
|
| 1066 |
dicom_files.upload(fn=on_dicom_upload,inputs=dicom_files,outputs=[patient_dd,dicom_status])
|
| 1067 |
patient_dd.change(fn=on_patient_select,inputs=patient_dd,outputs=patient_info)
|
|
|
|
| 1070 |
pdf_btn.click(fn=on_download_pdf,inputs=[],outputs=pdf_output)
|
| 1071 |
pdf_btn.click(fn=lambda:gr.update(visible=True),inputs=[],outputs=pdf_output)
|
| 1072 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1073 |
demo.launch(server_name="0.0.0.0",server_port=7860)
|