Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
"""
|
| 2 |
-
FibrosisNet-V4 β
|
| 3 |
-
Precision-medical aesthetic: deep navy + cyan, Syne + IBM Plex Mono
|
| 4 |
"""
|
| 5 |
|
| 6 |
import os, json, warnings, math, io, datetime
|
|
@@ -14,7 +13,6 @@ import matplotlib
|
|
| 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,11 +24,8 @@ try:
|
|
| 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 |
-
|
| 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
|
|
@@ -41,47 +36,10 @@ NUM_SLICES = 16
|
|
| 41 |
HU_MIN, HU_MAX = -1000, 400
|
| 42 |
TAB_FEATURES = ["BaselineFVC","Percent","Age","Sex_enc","Smoking_enc",
|
| 43 |
"FVC_height_ratio","percent_age_interaction"]
|
| 44 |
-
SIN_PERIODS
|
| 45 |
-
SIN_DIM
|
| 46 |
-
TAB_DIM
|
| 47 |
-
FUSION_DIM
|
| 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):
|
|
@@ -195,7 +153,7 @@ def detect_pid(files):
|
|
| 195 |
except: continue
|
| 196 |
return None
|
| 197 |
|
| 198 |
-
# ββ CT
|
| 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
|
|
@@ -244,11 +202,30 @@ def run_inference(bl,volume,bw=0.):
|
|
| 244 |
mu,sigma=MODEL(vol_t,tab_t,bfvc_t,weeks_t)
|
| 245 |
return mu.squeeze().numpy(),sigma.squeeze().numpy()
|
| 246 |
|
| 247 |
-
# ββ
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 248 |
def _empty(msg=""):
|
| 249 |
-
fig
|
|
|
|
| 250 |
ax.text(0.5,0.5,msg,ha="center",va="center",transform=ax.transAxes,
|
| 251 |
-
color=
|
| 252 |
ax.axis("off"); return fig
|
| 253 |
|
| 254 |
def make_fvc_plot(bl,visits,mu,sigma):
|
|
@@ -258,177 +235,128 @@ def make_fvc_plot(bl,visits,mu,sigma):
|
|
| 258 |
vis_fvc=visits["FVC"].values.astype(float)
|
| 259 |
dec_1yr=(fvc_bl-mu[52])/fvc_bl*100
|
| 260 |
|
| 261 |
-
fig=
|
| 262 |
-
fig.
|
| 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 |
-
|
| 269 |
-
|
| 270 |
-
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
|
| 278 |
-
|
| 279 |
-
|
| 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=
|
| 293 |
-
ax_main.scatter(vis_wk,vis_fvc,color=
|
| 294 |
-
edgecolors=
|
| 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=
|
| 298 |
|
| 299 |
-
ax_main.scatter([0],[fvc_bl],color=
|
| 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 Β·
|
| 303 |
-
|
| 304 |
-
leg
|
| 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=[
|
| 312 |
-
bars=ax_bar.bar(clabs,fvc_ck,color=bcols,edgecolor=
|
| 313 |
-
ax_bar.axhline(fvc_bl,color=
|
| 314 |
-
ax_bar.axhline(fvc_bl*0.9,color=
|
| 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=
|
| 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=
|
| 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=
|
| 331 |
-
|
| 332 |
-
|
| 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=
|
| 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=
|
| 348 |
plt.tight_layout(); return fig
|
| 349 |
|
| 350 |
def make_multiview(volume):
|
| 351 |
D,H,W=volume.shape
|
| 352 |
-
fig
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 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=
|
| 361 |
-
|
| 362 |
-
cb
|
| 363 |
-
cb.
|
| 364 |
-
|
| 365 |
-
|
| 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
|
| 373 |
idx=int(np.clip(idx,0,vol.shape[0]-1)); D,H,W=vol.shape
|
| 374 |
-
fig
|
| 375 |
-
|
| 376 |
-
|
| 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=
|
| 381 |
plt.tight_layout(); return fig
|
| 382 |
|
| 383 |
-
# ββ PDF
|
| 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 |
-
#
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 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 |
-
|
| 408 |
-
|
| 409 |
-
|
| 410 |
-
|
| 411 |
-
|
| 412 |
-
|
| 413 |
-
|
| 414 |
-
|
| 415 |
-
|
| 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")
|
|
@@ -446,37 +374,28 @@ def generate_pdf(bl,visits,mu,sigma,fvc_fig):
|
|
| 446 |
vis_wk=visits["WeekDelta"].values.astype(float); vis_fvc=visits["FVC"].values.astype(float)
|
| 447 |
|
| 448 |
story=[]
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
story.append(Paragraph("FibrosisNet-V4", sDisplay))
|
| 452 |
-
story.append(Paragraph("Pulmonary Fibrosis Progression Report", sSubtitle))
|
| 453 |
story.append(Paragraph(
|
| 454 |
-
f"Generated
|
| 455 |
-
f"Swin-Tiny 2.5D
|
| 456 |
-
|
| 457 |
-
|
| 458 |
-
|
| 459 |
-
story.append(
|
| 460 |
-
|
| 461 |
-
|
| 462 |
-
|
| 463 |
-
|
| 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",
|
| 470 |
-
[cell("SMOKING
|
| 471 |
-
|
| 472 |
-
|
| 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 |
-
("
|
| 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),
|
|
@@ -485,42 +404,35 @@ def generate_pdf(bl,visits,mu,sigma,fvc_fig):
|
|
| 485 |
]))
|
| 486 |
story.append(pt); story.append(Spacer(1,10))
|
| 487 |
|
| 488 |
-
|
| 489 |
-
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
|
| 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(
|
| 503 |
-
story.append(Paragraph(f"<b>Trajectory Classification:</b> {traj}", sBody))
|
| 504 |
|
| 505 |
-
|
| 506 |
-
|
| 507 |
-
ph=["Timepoint","Predicted FVC","Change from Baseline","Β± 1Ο Uncertainty Range"]
|
| 508 |
pd_rows=[
|
| 509 |
-
["6 months
|
| 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
|
| 513 |
-
f"β{fvc_bl-fvc_1yr:.0f} ml ({dec_pct:.1f}%
|
| 514 |
f"{fvc_1yr-sig_1yr:.0f} β {fvc_1yr+sig_1yr:.0f} ml"],
|
| 515 |
-
["2 years
|
| 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.
|
| 520 |
prt.setStyle(TableStyle([
|
| 521 |
-
("BACKGROUND",(0,0),(-1,0),cNavy),("TEXTCOLOR",(0,0),(-1,0),
|
| 522 |
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,0),9),
|
| 523 |
-
("ROWBACKGROUNDS",(0,1),(-1,-1),[cLight,
|
| 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")),
|
|
@@ -528,78 +440,54 @@ def generate_pdf(bl,visits,mu,sigma,fvc_fig):
|
|
| 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
|
| 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 |
-
|
| 547 |
-
|
| 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),
|
| 551 |
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,0),9),
|
| 552 |
-
("ROWBACKGROUNDS",(0,1),(-1,-2),[cLight,
|
| 553 |
-
("BACKGROUND",(0,-1),(-1,-1),
|
| 554 |
-
("
|
| 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,
|
| 560 |
|
| 561 |
-
|
| 562 |
-
|
| 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/
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
"
|
| 575 |
-
|
| 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 |
-
"
|
| 595 |
-
"It must not substitute for clinical
|
| 596 |
-
"by a qualified pulmonologist.", sWarn))
|
| 597 |
story.append(Spacer(1,4))
|
| 598 |
story.append(Paragraph(
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
f"Balaji R Β· NIT Calicut Β· May 2026", sFooter))
|
| 602 |
-
|
| 603 |
doc.build(story); buf.seek(0); return buf.getvalue()
|
| 604 |
|
| 605 |
# ββ CACHE & CALLBACKS βββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -615,8 +503,7 @@ def on_csv_upload(csv_file):
|
|
| 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=
|
| 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 |
|
|
@@ -624,9 +511,9 @@ 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 Β·
|
| 628 |
-
elif pid: return gr.update(),f"β {n} files Β·
|
| 629 |
-
return gr.update(),f"βΉ {n} files
|
| 630 |
|
| 631 |
def on_patient_select(pid):
|
| 632 |
df=_CACHE.get("df")
|
|
@@ -635,29 +522,27 @@ def on_patient_select(pid):
|
|
| 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
|
| 642 |
f"Smoking βΊ {smoking}\n"
|
| 643 |
f"Baseline βΊ {bl['BaselineFVC']:.0f} ml ({bl['Percent']:.1f}% predicted)\n"
|
| 644 |
-
f"Normal βΊ {bl['PredictedFVC']:.0f} ml
|
| 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:
|
| 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=
|
| 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"])
|
|
@@ -672,45 +557,45 @@ def run_all(pid,dicom_files):
|
|
| 672 |
|
| 673 |
obs=""
|
| 674 |
if len(vis_wk)>0:
|
| 675 |
-
rows=[f" {'Week':>6} {'Actual':>8} {'Predicted':>10} {'Error':>8}"," "+"β"*
|
| 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\
|
| 682 |
|
| 683 |
report=(
|
| 684 |
f" FIBROSISNET-V4 Β· CLINICAL SUMMARY\n"
|
| 685 |
-
f"{'β'*
|
| 686 |
f" PATIENT\n"
|
| 687 |
-
f" ID βΊ {pid}\n"
|
| 688 |
-
f" Age
|
| 689 |
-
f" Smoking βΊ {smoking}\n"
|
| 690 |
-
f" Baseline βΊ {fvc_bl:.0f} ml ({pct:.1f}% predicted)\n"
|
| 691 |
-
f" Normal βΊ {float(bl['PredictedFVC']):.0f} ml
|
| 692 |
-
f"{'β'*
|
| 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"{'β'*
|
| 697 |
-
f" TRAJECTORY\n"
|
| 698 |
-
f"
|
| 699 |
-
f"
|
| 700 |
-
f"
|
| 701 |
-
f"
|
| 702 |
-
f"
|
| 703 |
-
f"
|
| 704 |
-
f"
|
| 705 |
-
f"
|
| 706 |
-
f"{
|
| 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"{'β'*
|
| 712 |
-
f" β AI research model
|
| 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 |
|
|
@@ -724,350 +609,545 @@ def on_download_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 |
-
|
| 732 |
-
|
| 733 |
-
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
|
| 737 |
-
--radius:12px; --radius-sm:8px;
|
| 738 |
}
|
| 739 |
|
| 740 |
-
/*
|
| 741 |
-
|
| 742 |
-
|
| 743 |
-
|
| 744 |
-
|
| 745 |
-
|
|
|
|
| 746 |
}
|
| 747 |
-
.gradio-container
|
| 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 |
-
|
| 763 |
-
|
| 764 |
-
|
| 765 |
-
|
| 766 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 767 |
}
|
| 768 |
-
|
| 769 |
-
|
| 770 |
-
|
| 771 |
-
|
| 772 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 773 |
}
|
| 774 |
-
.fn-
|
| 775 |
-
|
| 776 |
-
|
| 777 |
-
|
| 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-
|
| 782 |
-
.fn-
|
| 783 |
-
.
|
| 784 |
-
|
| 785 |
-
|
| 786 |
-
|
| 787 |
-
|
|
|
|
|
|
|
| 788 |
}
|
| 789 |
|
| 790 |
-
/* ββ
|
| 791 |
-
.
|
| 792 |
-
|
| 793 |
-
|
| 794 |
-
|
|
|
|
|
|
|
| 795 |
}
|
| 796 |
-
.
|
| 797 |
-
|
| 798 |
-
|
| 799 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 800 |
}
|
| 801 |
-
.step-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 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-
|
| 809 |
-
|
| 810 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 811 |
}
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 820 |
}
|
| 821 |
-
|
| 822 |
-
|
| 823 |
-
|
| 824 |
-
|
| 825 |
-
|
| 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:
|
| 831 |
-
|
| 832 |
-
|
|
|
|
| 833 |
}
|
| 834 |
|
| 835 |
/* Status boxes */
|
| 836 |
-
.status-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
|
|
|
|
| 842 |
}
|
| 843 |
|
| 844 |
/* Patient preview */
|
| 845 |
-
.pat-
|
| 846 |
-
|
| 847 |
-
|
| 848 |
-
|
| 849 |
-
|
| 850 |
-
|
| 851 |
-
border-radius:var(--radius-sm) !important;
|
| 852 |
}
|
| 853 |
|
| 854 |
-
/*
|
| 855 |
-
.report-
|
| 856 |
-
|
| 857 |
-
|
| 858 |
-
|
| 859 |
-
|
| 860 |
-
|
| 861 |
-
|
| 862 |
-
padding:16px !important;
|
| 863 |
}
|
| 864 |
|
| 865 |
-
/*
|
| 866 |
-
.
|
| 867 |
-
|
| 868 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 869 |
}
|
| 870 |
|
| 871 |
-
/* ββ
|
| 872 |
-
.run-btn button{
|
| 873 |
-
|
| 874 |
-
|
| 875 |
-
|
| 876 |
-
|
| 877 |
-
|
| 878 |
-
|
| 879 |
-
|
| 880 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 881 |
}
|
| 882 |
-
.
|
| 883 |
-
|
| 884 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 885 |
}
|
| 886 |
-
.
|
| 887 |
-
|
| 888 |
-
|
| 889 |
-
|
| 890 |
-
|
| 891 |
-
|
| 892 |
-
|
| 893 |
-
|
| 894 |
-
|
| 895 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 896 |
}
|
| 897 |
-
.pdf-btn button:hover{box-shadow:0 5px 20px rgba(0,184,124,0.45) !important;transform:translateY(-1px) !important;}
|
| 898 |
|
| 899 |
-
/* ββ
|
| 900 |
-
.tab-nav
|
| 901 |
-
|
| 902 |
-
|
| 903 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 904 |
}
|
| 905 |
-
.
|
| 906 |
-
|
| 907 |
-
|
| 908 |
-
color:var(--muted) !important;
|
| 909 |
-
border-bottom:2px solid transparent !important;
|
| 910 |
-
padding:12px 18px !important;
|
| 911 |
-
transition:all .2s !important;
|
| 912 |
}
|
| 913 |
-
.
|
| 914 |
-
|
| 915 |
-
border-bottom:2px solid var(--cyan) !important;
|
| 916 |
-
background:transparent !important;
|
| 917 |
}
|
| 918 |
-
.
|
| 919 |
-
|
| 920 |
-
|
| 921 |
-
|
| 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 |
-
/* ββ
|
| 930 |
-
.
|
| 931 |
-
|
| 932 |
-
|
| 933 |
-
|
|
|
|
|
|
|
| 934 |
}
|
| 935 |
|
| 936 |
-
/* ββ
|
| 937 |
-
|
| 938 |
-
|
| 939 |
-
|
| 940 |
-
|
| 941 |
}
|
| 942 |
-
|
| 943 |
-
|
| 944 |
-
|
| 945 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 946 |
}
|
| 947 |
-
|
| 948 |
-
|
| 949 |
-
|
| 950 |
-
|
| 951 |
-
|
| 952 |
-
|
| 953 |
-
|
| 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 |
-
/*
|
| 962 |
-
|
| 963 |
|
| 964 |
-
/*
|
| 965 |
-
.
|
| 966 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 967 |
"""
|
| 968 |
|
| 969 |
-
# ββ
|
| 970 |
-
with gr.Blocks(title="FibrosisNet-V4",
|
| 971 |
|
| 972 |
-
# Header
|
| 973 |
gr.HTML("""
|
| 974 |
<div class="fn-header">
|
| 975 |
-
<
|
| 976 |
-
<p class="fn-
|
| 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
|
| 988 |
|
| 989 |
# ββ LEFT PANEL ββ
|
| 990 |
-
with gr.Column(scale=1, min_width=360):
|
| 991 |
|
| 992 |
-
|
| 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-
|
| 1000 |
|
| 1001 |
-
|
| 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-
|
| 1009 |
|
| 1010 |
-
|
| 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 |
-
|
| 1018 |
-
|
| 1019 |
-
|
| 1020 |
-
|
| 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 |
-
'
|
| 1026 |
-
dicom_files = gr.File(label="DICOM slices
|
| 1027 |
file_count="multiple",
|
| 1028 |
file_types=[".dcm",".DCM"],
|
| 1029 |
-
elem_classes="dicom-
|
| 1030 |
dicom_status = gr.Textbox(label="DICOM Status", lines=2,
|
| 1031 |
-
interactive=False, elem_classes="status-
|
| 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(
|
| 1038 |
|
| 1039 |
with gr.Tab("π« CT Lung Viewer"):
|
| 1040 |
-
ct_view = gr.Plot(
|
| 1041 |
-
gr.HTML('<p style="color:
|
| 1042 |
-
'
|
| 1043 |
-
|
| 1044 |
-
|
| 1045 |
-
|
|
|
|
| 1046 |
|
| 1047 |
with gr.Tab("π Clinical Report"):
|
| 1048 |
with gr.Row():
|
| 1049 |
-
gr.HTML('<div class="report-
|
| 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-
|
| 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)
|
| 1068 |
-
predict_btn.click(fn=run_all,inputs=[patient_dd,dicom_files],
|
| 1069 |
-
outputs=[fvc_plot,ct_view,report_box,pdf_btn,pdf_output])
|
| 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)
|
|
|
|
| 1 |
"""
|
| 2 |
+
FibrosisNet-V4 β Fixed Dark Theme Gradio App
|
|
|
|
| 3 |
"""
|
| 4 |
|
| 5 |
import os, json, warnings, math, io, datetime
|
|
|
|
| 13 |
matplotlib.use("Agg")
|
| 14 |
import matplotlib.pyplot as plt
|
| 15 |
import matplotlib.gridspec as gridspec
|
|
|
|
| 16 |
import pydicom
|
| 17 |
import timm
|
| 18 |
|
|
|
|
| 24 |
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
|
| 25 |
from reportlab.lib.units import cm
|
| 26 |
from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer,
|
| 27 |
+
Table, TableStyle, HRFlowable, Image as RLImage)
|
| 28 |
+
from reportlab.lib.enums import TA_CENTER, TA_LEFT
|
|
|
|
|
|
|
|
|
|
| 29 |
PDF_OK = True
|
| 30 |
except ImportError:
|
| 31 |
PDF_OK = False
|
|
|
|
| 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; FUSION_HEADS = 8; FUSION_DEPTH = 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
# ββ MODEL βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 45 |
class SEAttentionPool(nn.Module):
|
|
|
|
| 153 |
except: continue
|
| 154 |
return None
|
| 155 |
|
| 156 |
+
# ββ CT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 157 |
def _extent(vol,thr=0.06):
|
| 158 |
m=vol.mean(axis=(1,2)); mask=m>thr
|
| 159 |
if mask.sum()<5: return 0,vol.shape[0]-1
|
|
|
|
| 202 |
mu,sigma=MODEL(vol_t,tab_t,bfvc_t,weeks_t)
|
| 203 |
return mu.squeeze().numpy(),sigma.squeeze().numpy()
|
| 204 |
|
| 205 |
+
# ββ MATPLOTLIB DARK THEME βββββββββββββββββββββββββββββββββββββ
|
| 206 |
+
BG = "#0D1B2E"
|
| 207 |
+
BG2 = "#0A1628"
|
| 208 |
+
COL = {"text":"#C8D8F0","muted":"#5A7A9A","border":"#1A2E48",
|
| 209 |
+
"cyan":"#00C4D4","green":"#00B87C","amber":"#E8971A",
|
| 210 |
+
"red":"#E03C3C","blue":"#1A6FBF","teal":"#0B8C7A"}
|
| 211 |
+
|
| 212 |
+
def _mpl_fig(w=15,h=7.5):
|
| 213 |
+
fig=plt.figure(figsize=(w,h),facecolor=BG)
|
| 214 |
+
return fig
|
| 215 |
+
|
| 216 |
+
def _style_ax(ax):
|
| 217 |
+
ax.set_facecolor(BG2)
|
| 218 |
+
for sp in ax.spines.values(): sp.set_edgecolor(COL["border"])
|
| 219 |
+
ax.tick_params(colors=COL["muted"],labelsize=9)
|
| 220 |
+
ax.xaxis.label.set_color(COL["text"]); ax.yaxis.label.set_color(COL["text"])
|
| 221 |
+
ax.title.set_color(COL["text"])
|
| 222 |
+
ax.grid(True,color=COL["border"],alpha=0.6,linewidth=0.5)
|
| 223 |
+
|
| 224 |
def _empty(msg=""):
|
| 225 |
+
fig=_mpl_fig(8,3.5)
|
| 226 |
+
ax=fig.add_subplot(111); _style_ax(ax)
|
| 227 |
ax.text(0.5,0.5,msg,ha="center",va="center",transform=ax.transAxes,
|
| 228 |
+
color=COL["muted"],fontsize=12,style="italic")
|
| 229 |
ax.axis("off"); return fig
|
| 230 |
|
| 231 |
def make_fvc_plot(bl,visits,mu,sigma):
|
|
|
|
| 235 |
vis_fvc=visits["FVC"].values.astype(float)
|
| 236 |
dec_1yr=(fvc_bl-mu[52])/fvc_bl*100
|
| 237 |
|
| 238 |
+
fig=_mpl_fig(15,7.5)
|
| 239 |
+
gs=gridspec.GridSpec(2,3,figure=fig,hspace=0.52,wspace=0.40)
|
|
|
|
| 240 |
ax_main=fig.add_subplot(gs[:,0:2])
|
| 241 |
+
ax_bar =fig.add_subplot(gs[0,2])
|
| 242 |
+
ax_sev =fig.add_subplot(gs[1,2])
|
| 243 |
+
for ax in [ax_main,ax_bar,ax_sev]: _style_ax(ax)
|
| 244 |
+
|
| 245 |
+
ax_main.fill_between(weeks,mu-2*sigma,mu+2*sigma,alpha=0.07,color=COL["cyan"])
|
| 246 |
+
ax_main.fill_between(weeks,mu-sigma, mu+sigma, alpha=0.18,color=COL["cyan"],label="Β±1Ο confidence")
|
| 247 |
+
ax_main.plot(weeks,mu,color=COL["cyan"],lw=2.5,zorder=5,label="FibrosisNet-V4")
|
| 248 |
+
ax_main.axhline(fvc_bl, color=COL["muted"],ls="--",lw=1.4,alpha=0.8,label=f"Baseline {fvc_bl:.0f} ml")
|
| 249 |
+
ax_main.axhline(fvc_bl*0.90, color=COL["amber"],ls=":" ,lw=2.0,label="β10% threshold")
|
| 250 |
+
ax_main.axhline(fvc_bl*0.80, color=COL["red"], ls=":" ,lw=1.3,alpha=0.65,label="β20% threshold")
|
| 251 |
+
ax_main.axhline(norm_fvc, color=COL["teal"], ls="-.",lw=1.2,alpha=0.65,label=f"Est. normal {norm_fvc:.0f} ml")
|
| 252 |
+
|
| 253 |
+
for wk,lbl in [(26,"6mo"),(52,"1yr"),(78,"18mo"),(104,"2yr")]:
|
| 254 |
+
ax_main.axvline(wk,color=COL["border"],lw=1,alpha=0.8)
|
| 255 |
+
ax_main.text(wk+1,mu.min()*0.974,lbl,fontsize=7.5,color=COL["muted"])
|
|
|
|
|
|
|
|
|
|
| 256 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 257 |
if len(vis_wk)>0:
|
| 258 |
+
ax_main.plot(vis_wk,vis_fvc,color=COL["red"],lw=1.6,ls="--",alpha=0.75,zorder=6)
|
| 259 |
+
ax_main.scatter(vis_wk,vis_fvc,color=COL["red"],s=90,zorder=7,
|
| 260 |
+
edgecolors=BG,linewidths=1.8,label="Actual FVC (CSV)")
|
| 261 |
for wk,fv in zip(vis_wk,vis_fvc):
|
| 262 |
ax_main.annotate(f"{fv:.0f}",xy=(wk,fv),xytext=(5,9),textcoords="offset points",
|
| 263 |
+
fontsize=7.5,color=COL["red"],fontweight="bold")
|
| 264 |
|
| 265 |
+
ax_main.scatter([0],[fvc_bl],color=COL["cyan"],s=120,zorder=8,edgecolors=BG,lw=2)
|
| 266 |
ax_main.set_xlabel("Weeks from Baseline",fontsize=11,labelpad=8)
|
| 267 |
ax_main.set_ylabel("Forced Vital Capacity (ml)",fontsize=11,labelpad=8)
|
| 268 |
+
ax_main.set_title(f"FVC Decline Trajectory Β· {pid}",fontsize=13,fontweight="bold",pad=12)
|
| 269 |
+
leg=ax_main.legend(fontsize=8,loc="lower left",facecolor=BG2,edgecolor=COL["border"],framealpha=0.92)
|
| 270 |
+
for t in leg.get_texts(): t.set_color(COL["text"])
|
|
|
|
|
|
|
| 271 |
|
|
|
|
| 272 |
cps=[0,13,26,52,78,104,144]; clabs=["0w","3m","6m","1yr","18m","2yr","End"]
|
| 273 |
fvc_ck=[mu[min(w,144)] for w in cps]
|
| 274 |
+
bcols=[COL["green"] if v>=fvc_bl*0.9 else COL["amber"] if v>=fvc_bl*0.8 else COL["red"] for v in fvc_ck]
|
| 275 |
+
bars=ax_bar.bar(clabs,fvc_ck,color=bcols,edgecolor=BG,lw=1.2,width=0.68,zorder=3)
|
| 276 |
+
ax_bar.axhline(fvc_bl, color=COL["muted"],ls="--",lw=1.1,alpha=0.7,zorder=4)
|
| 277 |
+
ax_bar.axhline(fvc_bl*0.9,color=COL["amber"],ls=":",lw=1.1,alpha=0.7,zorder=4)
|
| 278 |
ax_bar.set_title("FVC at Key Timepoints",fontweight="bold",fontsize=10,pad=8)
|
|
|
|
| 279 |
ax_bar.tick_params(axis="x",labelsize=8)
|
| 280 |
for bar,val in zip(bars,fvc_ck):
|
| 281 |
ax_bar.text(bar.get_x()+bar.get_width()/2,bar.get_height()+18,
|
| 282 |
+
f"{val:.0f}",ha="center",fontsize=6.5,fontweight="bold",color=COL["text"])
|
| 283 |
if len(vis_wk)>0:
|
| 284 |
bx,by=[],[]
|
| 285 |
for wk,fv in zip(vis_wk,vis_fvc):
|
| 286 |
ni=int(np.argmin(np.abs(np.array(cps)-int(wk)))); bx.append(clabs[ni]); by.append(fv)
|
| 287 |
+
ax_bar.scatter(bx,by,color=COL["red"],zorder=6,s=55,edgecolors=BG,lw=1.5,label="Actual")
|
| 288 |
+
leg2=ax_bar.legend(fontsize=7,facecolor=BG2,edgecolor=COL["border"])
|
| 289 |
+
for t in leg2.get_texts(): t.set_color(COL["text"])
|
| 290 |
|
|
|
|
| 291 |
sev_label=("Stable / Mild" if dec_1yr<5 else "Moderate" if dec_1yr<10 else "Severe / Rapid")
|
| 292 |
+
sev_col=COL["green"] if dec_1yr<5 else COL["amber"] if dec_1yr<10 else COL["red"]
|
| 293 |
+
for (lo,hi),col in [((0,5),COL["green"]),((5,10),COL["amber"]),((10,20),"#D06020"),((20,30),COL["red"])]:
|
| 294 |
+
ax_sev.barh(0,hi-lo,left=lo,color=col,height=0.5,alpha=0.55)
|
|
|
|
| 295 |
mx=float(np.clip(dec_1yr,0,29))
|
| 296 |
ax_sev.axvline(mx,color="white",lw=3.5,zorder=5)
|
| 297 |
ax_sev.scatter([mx],[0],color=sev_col,s=100,zorder=6,edgecolors="white",lw=2)
|
| 298 |
ax_sev.set_xlim(0,30); ax_sev.set_ylim(-0.8,0.8); ax_sev.set_yticks([])
|
| 299 |
ax_sev.set_xlabel("Annual FVC Decline (%)",fontsize=9,labelpad=6)
|
| 300 |
+
ax_sev.set_title(f"{sev_label}\n{dec_1yr:.1f}% / year",fontweight="bold",fontsize=10,color=sev_col,pad=8)
|
|
|
|
| 301 |
for xt,xtl in zip([0,5,10,20,30],["0%","5%","10%","20%","30%"]):
|
| 302 |
+
ax_sev.text(xt,-0.65,xtl,fontsize=7,ha="center",color=COL["muted"])
|
|
|
|
| 303 |
|
| 304 |
age=int(bl["Age"]); sex="Male" if bl["Sex_enc"]==1. else "Female"
|
| 305 |
fig.suptitle(f"Age {age} Β· {sex} Β· Baseline FVC {fvc_bl:.0f} ml Β· {float(bl['Percent']):.0f}% predicted",
|
| 306 |
+
fontsize=10,color=COL["muted"],y=1.01)
|
| 307 |
plt.tight_layout(); return fig
|
| 308 |
|
| 309 |
def make_multiview(volume):
|
| 310 |
D,H,W=volume.shape
|
| 311 |
+
fig=_mpl_fig(15,5.2)
|
| 312 |
+
views=[(volume[D//2],f"Axial Β· {D//2+1}/{D}"),(volume[:,H//2,:],"Coronal Β· mid"),(volume[:,:,W//2],"Sagittal Β· mid")]
|
| 313 |
+
for i,(img,ttl) in enumerate(views,1):
|
| 314 |
+
ax=fig.add_subplot(1,3,i); ax.set_facecolor("#040C1A")
|
|
|
|
|
|
|
|
|
|
| 315 |
im=ax.imshow(img,cmap="bone",vmin=0,vmax=1,aspect="auto",interpolation="bicubic")
|
| 316 |
+
ax.set_title(ttl,color=COL["cyan"],fontsize=10,pad=8,fontweight="bold"); ax.axis("off")
|
| 317 |
+
cb=fig.colorbar(im,ax=fig.axes[-1],fraction=0.026,pad=0.02)
|
| 318 |
+
cb.set_label("HU [0β1]",color=COL["muted"],fontsize=8)
|
| 319 |
+
plt.setp(cb.ax.yaxis.get_ticklabels(),color=COL["muted"])
|
| 320 |
+
cb.outline.set_edgecolor(COL["border"])
|
| 321 |
+
fig.suptitle("CT Lung Volume β Multi-Plane Reconstruction",color=COL["text"],fontsize=12,fontweight="bold",y=1.02)
|
|
|
|
|
|
|
| 322 |
plt.tight_layout(); return fig
|
| 323 |
|
| 324 |
def update_slice(idx):
|
| 325 |
vol=_CACHE.get("vol")
|
| 326 |
+
if vol is None: return _empty("Upload DICOM and run prediction first")
|
| 327 |
idx=int(np.clip(idx,0,vol.shape[0]-1)); D,H,W=vol.shape
|
| 328 |
+
fig=_mpl_fig(15,5.2)
|
| 329 |
+
for i,(img,ttl) in enumerate([(vol[idx],f"Axial Β· {idx+1}/{D}"),(vol[:,H//2,:],"Coronal"),(vol[:,:,W//2],"Sagittal")],1):
|
| 330 |
+
ax=fig.add_subplot(1,3,i); ax.set_facecolor("#040C1A")
|
|
|
|
|
|
|
| 331 |
ax.imshow(img,cmap="bone",vmin=0,vmax=1,aspect="auto",interpolation="bicubic")
|
| 332 |
+
ax.set_title(ttl,color=COL["cyan"],fontsize=10,pad=8,fontweight="bold"); ax.axis("off")
|
| 333 |
plt.tight_layout(); return fig
|
| 334 |
|
| 335 |
+
# ββ PDF ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 336 |
def generate_pdf(bl,visits,mu,sigma,fvc_fig):
|
| 337 |
if not PDF_OK: return None
|
| 338 |
buf=io.BytesIO()
|
| 339 |
+
doc=SimpleDocTemplate(buf,pagesize=A4,leftMargin=2*cm,rightMargin=2*cm,topMargin=2.2*cm,bottomMargin=2*cm)
|
|
|
|
| 340 |
W=A4[0]-4*cm; styles=getSampleStyleSheet()
|
| 341 |
|
| 342 |
+
cNavy=colors.HexColor("#0F2142"); cBlue=colors.HexColor("#0D5EAF")
|
| 343 |
+
cCyan=colors.HexColor("#00A8BC"); cGreen=colors.HexColor("#00B87C")
|
| 344 |
+
cAmber=colors.HexColor("#E8971A"); cRed=colors.HexColor("#E03C3C")
|
| 345 |
+
cText=colors.HexColor("#1E293B"); cMuted=colors.HexColor("#64748B")
|
| 346 |
+
cLight=colors.HexColor("#F0F4FA"); cLighter=colors.HexColor("#E8EEF8")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 347 |
|
| 348 |
def PS(name,**kw):
|
| 349 |
return ParagraphStyle(name,parent=styles.get(kw.pop("parent","Normal"),styles["Normal"]),**kw)
|
| 350 |
|
| 351 |
+
sTitle=PS("T",fontSize=26,fontName="Helvetica-Bold",textColor=cNavy,alignment=TA_CENTER,spaceAfter=3)
|
| 352 |
+
sSub =PS("S",fontSize=10,fontName="Helvetica",textColor=cBlue,alignment=TA_CENTER,spaceAfter=5)
|
| 353 |
+
sMeta =PS("M",fontSize=8.5,fontName="Helvetica",textColor=cMuted,alignment=TA_CENTER,spaceAfter=14)
|
| 354 |
+
sH =PS("H",fontSize=12,fontName="Helvetica-Bold",textColor=cNavy,spaceBefore=16,spaceAfter=5)
|
| 355 |
+
sBody =PS("B",fontSize=9.5,fontName="Helvetica",textColor=cText,leading=15,spaceAfter=4)
|
| 356 |
+
sBullet=PS("Bu",fontSize=9.5,fontName="Helvetica",textColor=cText,leading=15,leftIndent=12,spaceAfter=4)
|
| 357 |
+
sWarn =PS("W",fontSize=8,fontName="Helvetica-Oblique",textColor=colors.HexColor("#92400E"),alignment=TA_CENTER)
|
| 358 |
+
sFooter=PS("F",fontSize=7.5,fontName="Helvetica",textColor=cMuted,alignment=TA_CENTER)
|
| 359 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 360 |
pid=str(bl["Patient"]); age=int(bl["Age"])
|
| 361 |
sex="Male" if bl["Sex_enc"]==1. else "Female"
|
| 362 |
smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
|
|
|
|
| 374 |
vis_wk=visits["WeekDelta"].values.astype(float); vis_fvc=visits["FVC"].values.astype(float)
|
| 375 |
|
| 376 |
story=[]
|
| 377 |
+
story.append(Paragraph("FibrosisNet-V4",sTitle))
|
| 378 |
+
story.append(Paragraph("Pulmonary Fibrosis Progression Report",sSub))
|
|
|
|
|
|
|
| 379 |
story.append(Paragraph(
|
| 380 |
+
f"Generated {datetime.datetime.now().strftime('%d %B %Y at %H:%M')} Β· "
|
| 381 |
+
f"Swin-Tiny 2.5D Β· OOF β6.6629 Β· Beats Kaggle Baseline",sMeta))
|
| 382 |
+
story.append(HRFlowable(width="100%",thickness=3,color=cNavy,spaceAfter=1))
|
| 383 |
+
story.append(HRFlowable(width="100%",thickness=1,color=cCyan,spaceBefore=2,spaceAfter=14))
|
| 384 |
+
|
| 385 |
+
story.append(Paragraph("Patient Profile",sH))
|
| 386 |
+
def cell(lbl,val):
|
| 387 |
+
return Paragraph(f"<font size='7.5' color='#64748B'>{lbl}</font><br/>"
|
| 388 |
+
f"<font name='Helvetica-Bold' size='10'>{val}</font>",
|
| 389 |
+
PS(f"c{lbl}",fontSize=10,leading=15))
|
|
|
|
|
|
|
|
|
|
|
|
|
| 390 |
profile_data=[
|
| 391 |
+
[cell("PATIENT ID",pid), cell("AGE",f"{age} years"), cell("SEX",sex)],
|
| 392 |
+
[cell("SMOKING",smoking), cell("BASELINE FVC",f"{fvc_bl:.0f} ml"), cell("% PREDICTED",f"{pct:.1f}%")],
|
| 393 |
+
[cell("ESTIMATED NORMAL",f"{norm:.0f} ml"), cell("MODEL INPUTS","Baseline visit + CT"),
|
| 394 |
+
cell("CSV VISITS",f"{len(vis_wk)} recorded")],
|
|
|
|
|
|
|
| 395 |
]
|
| 396 |
pt=Table(profile_data,colWidths=[W/3]*3)
|
| 397 |
pt.setStyle(TableStyle([
|
| 398 |
+
("ROWBACKGROUNDS",(0,0),(-1,-1),[cLight,cLighter]),
|
|
|
|
| 399 |
("BOX",(0,0),(-1,-1),1,colors.HexColor("#CBD5E1")),
|
| 400 |
("INNERGRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
|
| 401 |
("TOPPADDING",(0,0),(-1,-1),8),("BOTTOMPADDING",(0,0),(-1,-1),8),
|
|
|
|
| 404 |
]))
|
| 405 |
story.append(pt); story.append(Spacer(1,10))
|
| 406 |
|
| 407 |
+
story.append(Paragraph("Severity Assessment",sH))
|
| 408 |
+
sb_sty=PS("SBadge",fontSize=15,fontName="Helvetica-Bold",textColor=sev_col,alignment=TA_CENTER)
|
| 409 |
+
sb_sub=PS("SSub",fontSize=9,fontName="Helvetica",textColor=cMuted,alignment=TA_CENTER)
|
| 410 |
+
sev_tbl=Table([[Paragraph(f"{sev.upper()}",sb_sty)],
|
| 411 |
+
[Paragraph(f"{pct:.1f}% predicted Β· Mild β₯70% | Moderate 50β69% | Severe <50%",sb_sub)]],colWidths=[W])
|
| 412 |
+
sev_tbl.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),sev_bg),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 413 |
("BOX",(0,0),(-1,-1),1.5,sev_col),
|
| 414 |
+
("TOPPADDING",(0,0),(-1,-1),10),("BOTTOMPADDING",(0,0),(-1,-1),8)]))
|
| 415 |
+
story.append(sev_tbl); story.append(Spacer(1,6))
|
| 416 |
+
story.append(Paragraph(f"<b>Trajectory:</b> {traj}",sBody))
|
|
|
|
| 417 |
|
| 418 |
+
story.append(Paragraph("Predicted FVC Trajectory",sH))
|
| 419 |
+
ph=["Timepoint","Predicted FVC","Change from Baseline","Β±1Ο Uncertainty"]
|
|
|
|
| 420 |
pd_rows=[
|
| 421 |
+
["6 months (Week 26)",f"{fvc_6m:.0f} ml",
|
| 422 |
f"β{fvc_bl-fvc_6m:.0f} ml ({(fvc_bl-fvc_6m)/fvc_bl*100:.1f}%)",
|
| 423 |
f"{fvc_6m-sigma[26]:.0f} β {fvc_6m+sigma[26]:.0f} ml"],
|
| 424 |
+
["1 year (Week 52)",f"{fvc_1yr:.0f} ml",
|
| 425 |
+
f"β{fvc_bl-fvc_1yr:.0f} ml ({dec_pct:.1f}%/yr)",
|
| 426 |
f"{fvc_1yr-sig_1yr:.0f} β {fvc_1yr+sig_1yr:.0f} ml"],
|
| 427 |
+
["2 years (Week 104)",f"{fvc_2yr:.0f} ml",
|
| 428 |
f"β{fvc_bl-fvc_2yr:.0f} ml ({(fvc_bl-fvc_2yr)/fvc_bl*100:.1f}%)",
|
| 429 |
f"{fvc_2yr-sigma[104]:.0f} β {fvc_2yr+sigma[104]:.0f} ml"],
|
| 430 |
]
|
| 431 |
+
prt=Table([ph]+pd_rows,colWidths=[W*0.28,W*0.17,W*0.31,W*0.24])
|
| 432 |
prt.setStyle(TableStyle([
|
| 433 |
+
("BACKGROUND",(0,0),(-1,0),cNavy),("TEXTCOLOR",(0,0),(-1,0),colors.white),
|
| 434 |
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,0),9),
|
| 435 |
+
("ROWBACKGROUNDS",(0,1),(-1,-1),[cLight,cLighter]),
|
| 436 |
("FONTSIZE",(0,1),(-1,-1),9),("FONTNAME",(0,1),(0,-1),"Helvetica-Bold"),
|
| 437 |
("TEXTCOLOR",(0,1),(0,-1),cNavy),
|
| 438 |
("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
|
|
|
|
| 440 |
("LEFTPADDING",(0,0),(-1,-1),9),("ALIGN",(1,1),(-1,-1),"CENTER"),
|
| 441 |
]))
|
| 442 |
story.append(prt); story.append(Spacer(1,6))
|
| 443 |
+
thr_txt=(f"Week {wks10} (~{wks10//4} months)" if wks10 else "Not reached within 2.5-year horizon")
|
| 444 |
+
story.append(Paragraph(f"<b>Time to 10% FVC decline:</b> {thr_txt}",sBody))
|
| 445 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 446 |
if len(vis_wk)>0:
|
| 447 |
+
story.append(Paragraph("Observed vs Predicted",sH))
|
| 448 |
+
obs_h=["Visit Week","Actual FVC","Predicted FVC","Error","Within Β±1Ο"]
|
| 449 |
obs_rows=[]; errs=[]
|
| 450 |
for wk,afvc in zip(vis_wk,vis_fvc):
|
| 451 |
wi=int(np.clip(int(wk),0,144)); pred=mu[wi]; err=afvc-pred; errs.append(abs(err))
|
| 452 |
within="β" if abs(err)<=sigma[wi] else "β"
|
| 453 |
obs_rows.append([f"Week {int(wk)}",f"{afvc:.0f} ml",f"{pred:.0f} ml",
|
| 454 |
f"{'+' if err>=0 else ''}{err:.0f} ml",within])
|
| 455 |
+
obs_rows.append(["","","Mean Abs. Error",f"{np.mean(errs):.1f} ml",""])
|
| 456 |
+
ot=Table([obs_h]+obs_rows,colWidths=[W*0.18,W*0.18,W*0.20,W*0.17,W*0.13])
|
|
|
|
| 457 |
ot.setStyle(TableStyle([
|
| 458 |
+
("BACKGROUND",(0,0),(-1,0),cBlue),("TEXTCOLOR",(0,0),(-1,0),colors.white),
|
| 459 |
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,0),9),
|
| 460 |
+
("ROWBACKGROUNDS",(0,1),(-1,-2),[cLight,cLighter]),
|
| 461 |
+
("BACKGROUND",(0,-1),(-1,-1),cLighter),("FONTNAME",(0,-1),(-1,-1),"Helvetica-Bold"),
|
| 462 |
+
("FONTSIZE",(0,1),(-1,-1),9),
|
| 463 |
("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
|
| 464 |
("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),
|
| 465 |
("LEFTPADDING",(0,0),(-1,-1),9),("ALIGN",(1,1),(-1,-1),"CENTER"),
|
| 466 |
]))
|
| 467 |
+
story.append(ot); story.append(Spacer(1,6))
|
| 468 |
|
| 469 |
+
story.append(Paragraph("FVC Decline Trajectory Chart",sH))
|
| 470 |
+
fig_buf=io.BytesIO(); fvc_fig.savefig(fig_buf,format="png",dpi=140,bbox_inches="tight")
|
|
|
|
|
|
|
| 471 |
fig_buf.seek(0)
|
| 472 |
+
story.append(RLImage(fig_buf,width=W,height=W*7.5/15)); story.append(Spacer(1,10))
|
| 473 |
+
|
| 474 |
+
story.append(Paragraph("Clinical Recommendations",sH))
|
| 475 |
+
for r in [f"<b>Spirometry:</b> {monitor}",
|
| 476 |
+
"<b>Physical:</b> 6-minute walk test at each visit",
|
| 477 |
+
"<b>Treatment:</b> "+("Discuss antifibrotic therapy (nintedanib / pirfenidone)"
|
| 478 |
+
if sev!="Mild" or dec_pct>=10 else "Continue current management plan"),
|
| 479 |
+
"<b>Rehabilitation:</b> Pulmonary rehabilitation referral recommended"]:
|
| 480 |
+
story.append(Paragraph(f" β’ {r}",sBullet))
|
| 481 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 482 |
story.append(Spacer(1,16))
|
| 483 |
story.append(HRFlowable(width="100%",thickness=1,color=colors.HexColor("#CBD5E1"),spaceAfter=8))
|
| 484 |
story.append(Paragraph(
|
| 485 |
+
"This report is produced by an AI research model for academic purposes only. "
|
| 486 |
+
"It must not substitute for clinical decisions without review by a qualified pulmonologist.",sWarn))
|
|
|
|
| 487 |
story.append(Spacer(1,4))
|
| 488 |
story.append(Paragraph(
|
| 489 |
+
"FibrosisNet-V4 Β· Swin-Tiny 2.5D Β· OOF β6.6629 vs Kaggle β6.6743 Β· "
|
| 490 |
+
"Balaji R Β· NIT Calicut Β· May 2026",sFooter))
|
|
|
|
|
|
|
| 491 |
doc.build(story); buf.seek(0); return buf.getvalue()
|
| 492 |
|
| 493 |
# ββ CACHE & CALLBACKS βββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 503 |
return gr.update(choices=[],value=None),"'Patient' column not found."
|
| 504 |
df_prep=prepare_features(df_raw); _CACHE["df"]=df_prep
|
| 505 |
pids=sorted(df_prep["Patient"].unique().tolist())
|
| 506 |
+
msg=f"β
{len(pids)} patients Β· {len(df_raw)} rows\n{', '.join(df_raw.columns[:6].tolist())}"
|
|
|
|
| 507 |
return gr.update(choices=pids,value=pids[0] if pids else None),msg
|
| 508 |
except Exception as e: return gr.update(choices=[],value=None),f"β {e}"
|
| 509 |
|
|
|
|
| 511 |
if not dicom_files: return gr.update(),"No DICOM files."
|
| 512 |
n=len(dicom_files); pid=detect_pid(dicom_files); df=_CACHE.get("df")
|
| 513 |
if pid and df is not None and pid in df["Patient"].values:
|
| 514 |
+
return gr.update(value=pid),f"β
{n} files Β· Auto-matched:\n{pid}"
|
| 515 |
+
elif pid: return gr.update(),f"β {n} files Β· '{pid}' not in CSV"
|
| 516 |
+
return gr.update(),f"βΉ {n} files Β· No ID in DICOM tags"
|
| 517 |
|
| 518 |
def on_patient_select(pid):
|
| 519 |
df=_CACHE.get("df")
|
|
|
|
| 522 |
if bl is None: return f"Patient '{pid}' not found."
|
| 523 |
sex="Male" if bl["Sex_enc"]==1. else "Female"
|
| 524 |
smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
|
|
|
|
| 525 |
sev="Mild" if float(bl['Percent'])>=70 else "Moderate" if float(bl['Percent'])>=50 else "Severe"
|
| 526 |
+
lines="\n".join(f" Week {int(r['WeekDelta']):>4} βΊ {r['FVC']:.0f} ml" for _,r in visits.iterrows())
|
| 527 |
return (f"ID βΊ {pid}\n"
|
| 528 |
+
f"Age/Sex βΊ {int(bl['Age'])} yrs / {sex}\n"
|
| 529 |
f"Smoking βΊ {smoking}\n"
|
| 530 |
f"Baseline βΊ {bl['BaselineFVC']:.0f} ml ({bl['Percent']:.1f}% predicted)\n"
|
| 531 |
+
f"Normal βΊ {bl['PredictedFVC']:.0f} ml\n"
|
| 532 |
+
f"Severity βΊ {sev}\n\nVisits\n{'β'*22}\n{lines}")
|
|
|
|
| 533 |
|
| 534 |
def run_all(pid,dicom_files):
|
| 535 |
NO=(gr.update(visible=False),gr.update(visible=False))
|
| 536 |
df=_CACHE.get("df")
|
| 537 |
if df is None: return _empty("Upload CSV first"),_empty(""),"Upload CSV first.",*NO
|
| 538 |
+
if not pid: return _empty("Select a patient"),_empty(""),"Select a Patient ID.",*NO
|
| 539 |
bl,visits=extract_patient(df,pid)
|
| 540 |
if bl is None: return _empty(f"Patient {pid} not found"),_empty(""),"Not found.",*NO
|
| 541 |
volume=load_dicoms(dicom_files) if dicom_files else None
|
| 542 |
_CACHE["vol"]=volume
|
| 543 |
mu,sigma=run_inference(bl,volume,float(bl.get("BaselineWeek",0.)))
|
| 544 |
fvc_fig=make_fvc_plot(bl,visits,mu,sigma)
|
| 545 |
+
ct_view=make_multiview(volume) if volume is not None else _empty("No DICOM β CT view unavailable")
|
|
|
|
| 546 |
_CACHE.update({"last_fig":fvc_fig,"last_bl":bl,"last_visits":visits,"last_mu":mu,"last_sigma":sigma})
|
| 547 |
|
| 548 |
fvc_bl=float(bl["BaselineFVC"]); pct=float(bl["Percent"])
|
|
|
|
| 557 |
|
| 558 |
obs=""
|
| 559 |
if len(vis_wk)>0:
|
| 560 |
+
rows=[f" {'Week':>6} {'Actual':>8} {'Predicted':>10} {'Error':>8}"," "+"β"*40]
|
| 561 |
errs=[]
|
| 562 |
for wk,afvc in zip(vis_wk,vis_fvc):
|
| 563 |
wi=int(np.clip(int(wk),0,144)); pred=mu[wi]; err=afvc-pred; errs.append(abs(err))
|
| 564 |
rows.append(f" {int(wk):>6} {afvc:>8.0f} {pred:>10.0f} {err:>+8.0f} ml")
|
| 565 |
rows.append(f"\n Mean Absolute Error βΊ {np.mean(errs):.1f} ml")
|
| 566 |
+
obs="\n\n OBSERVED vs PREDICTED\n"+"".join(f" {r}\n" for r in rows)
|
| 567 |
|
| 568 |
report=(
|
| 569 |
f" FIBROSISNET-V4 Β· CLINICAL SUMMARY\n"
|
| 570 |
+
f" {'β'*46}\n\n"
|
| 571 |
f" PATIENT\n"
|
| 572 |
+
f" β ID βΊ {pid}\n"
|
| 573 |
+
f" β Age/Sex βΊ {int(bl['Age'])} yrs / {sex}\n"
|
| 574 |
+
f" β Smoking βΊ {smoking}\n"
|
| 575 |
+
f" β Baseline βΊ {fvc_bl:.0f} ml ({pct:.1f}% predicted)\n"
|
| 576 |
+
f" β Normal βΊ {float(bl['PredictedFVC']):.0f} ml (estimated)\n\n"
|
| 577 |
+
f" {'β'*46}\n"
|
| 578 |
f" SEVERITY (ATS/ERS)\n"
|
| 579 |
f" βΊ {sev.upper()} β {pct:.1f}% predicted FVC\n"
|
| 580 |
f" Mild β₯70% β Moderate 50β69% β Severe <50%\n\n"
|
| 581 |
+
f" {'β'*46}\n"
|
| 582 |
+
f" TRAJECTORY βΊ {traj}\n\n"
|
| 583 |
+
f" β 6 months βΊ {mu[26]:.0f} ml (β{fvc_bl-mu[26]:.0f} ml)\n"
|
| 584 |
+
f" β 1 year βΊ {mu[52]:.0f} ml (β{fvc_bl-mu[52]:.0f} ml Β· {dec_pct:.1f}%/yr)\n"
|
| 585 |
+
f" β 2 years βΊ {mu[104]:.0f} ml (β{fvc_bl-mu[104]:.0f} ml cumulative)\n"
|
| 586 |
+
f" β Β±1Ο@1yr βΊ {mu[52]-sigma[52]:.0f} β {mu[52]+sigma[52]:.0f} ml\n\n"
|
| 587 |
+
f" {'β'*46}\n"
|
| 588 |
+
f" 10% THRESHOLD\n"
|
| 589 |
+
f" βΊ {'Week '+str(wks10)+f' (~{wks10//4} months)' if wks10 else 'Not reached in 2.5-yr horizon'}\n"
|
| 590 |
+
f"{obs}\n"
|
| 591 |
+
f" {'β'*46}\n"
|
|
|
|
| 592 |
f" MONITORING\n"
|
| 593 |
f" βΊ Spirometry {monitor}\n"
|
| 594 |
f" βΊ {'Discuss antifibrotic therapy with specialist' if sev!='Mild' or dec_pct>=10 else 'Continue current management plan'}\n\n"
|
| 595 |
+
f" {'β'*46}\n"
|
| 596 |
+
f" β AI research model\n"
|
| 597 |
+
f" OOF β6.6629 β Kaggle baseline β6.6743 β\n"
|
| 598 |
+
f" Not for clinical use without physician oversight"
|
| 599 |
)
|
| 600 |
return fvc_fig,ct_view,report,gr.update(visible=True),gr.update(visible=False)
|
| 601 |
|
|
|
|
| 609 |
with open(path,"wb") as f: f.write(pdf_bytes)
|
| 610 |
return path
|
| 611 |
|
| 612 |
+
# ββ THEME βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 613 |
+
theme = gr.themes.Base(
|
| 614 |
+
primary_hue=gr.themes.Color(
|
| 615 |
+
c50="#e0f7fa", c100="#b2ebf2", c200="#80deea", c300="#4dd0e1",
|
| 616 |
+
c400="#26c6da", c500="#00BCD4", c600="#00ACC1", c700="#0097A7",
|
| 617 |
+
c800="#00838F", c900="#006064", c950="#004D40"),
|
| 618 |
+
secondary_hue=gr.themes.Color(
|
| 619 |
+
c50="#e8eaf6", c100="#c5cae9", c200="#9fa8da", c300="#7986cb",
|
| 620 |
+
c400="#5c6bc0", c500="#3f51b5", c600="#3949ab", c700="#303f9f",
|
| 621 |
+
c800="#283593", c900="#1a237e", c950="#0d1b69"),
|
| 622 |
+
neutral_hue=gr.themes.Color(
|
| 623 |
+
c50="#f0f4fa", c100="#d0dcea", c200="#a8bdd4", c300="#7a9ab8",
|
| 624 |
+
c400="#5a7a9a", c500="#3d5e80", c600="#2a4560", c700="#1a2e48",
|
| 625 |
+
c800="#0f1e34", c900="#080f1c", c950="#040810"),
|
| 626 |
+
font=[gr.themes.GoogleFont("Syne"), gr.themes.GoogleFont("IBM Plex Mono"), "sans-serif"],
|
| 627 |
+
font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "monospace"],
|
| 628 |
+
).set(
|
| 629 |
+
body_background_fill="#070E1D",
|
| 630 |
+
body_background_fill_dark="#070E1D",
|
| 631 |
+
body_text_color="#C8D8F0",
|
| 632 |
+
body_text_color_dark="#C8D8F0",
|
| 633 |
+
block_background_fill="#0D1B2E",
|
| 634 |
+
block_background_fill_dark="#0D1B2E",
|
| 635 |
+
block_border_color="#1A2E48",
|
| 636 |
+
block_border_color_dark="#1A2E48",
|
| 637 |
+
block_label_background_fill="#0D1B2E",
|
| 638 |
+
block_label_background_fill_dark="#0D1B2E",
|
| 639 |
+
block_label_text_color="#5A7A9A",
|
| 640 |
+
block_label_text_color_dark="#5A7A9A",
|
| 641 |
+
block_title_text_color="#C8D8F0",
|
| 642 |
+
block_title_text_color_dark="#C8D8F0",
|
| 643 |
+
input_background_fill="#111E33",
|
| 644 |
+
input_background_fill_dark="#111E33",
|
| 645 |
+
input_border_color="#1A2E48",
|
| 646 |
+
input_border_color_dark="#1A2E48",
|
| 647 |
+
input_placeholder_color="#3d5e80",
|
| 648 |
+
input_placeholder_color_dark="#3d5e80",
|
| 649 |
+
# CRITICAL: force input text color via theme vars
|
| 650 |
+
input_background_fill_focus="#111E33",
|
| 651 |
+
input_background_fill_focus_dark="#111E33",
|
| 652 |
+
panel_background_fill="#0A1628",
|
| 653 |
+
panel_background_fill_dark="#0A1628",
|
| 654 |
+
panel_border_color="#1A2E48",
|
| 655 |
+
panel_border_color_dark="#1A2E48",
|
| 656 |
+
button_primary_background_fill="linear-gradient(135deg, #0D5EAF, #00A8BC)",
|
| 657 |
+
button_primary_background_fill_dark="linear-gradient(135deg, #0D5EAF, #00A8BC)",
|
| 658 |
+
button_primary_text_color="#ffffff",
|
| 659 |
+
button_primary_text_color_dark="#ffffff",
|
| 660 |
+
button_secondary_background_fill="#111E33",
|
| 661 |
+
button_secondary_background_fill_dark="#111E33",
|
| 662 |
+
button_secondary_text_color="#C8D8F0",
|
| 663 |
+
button_secondary_text_color_dark="#C8D8F0",
|
| 664 |
+
checkbox_background_color="#111E33",
|
| 665 |
+
checkbox_background_color_dark="#111E33",
|
| 666 |
+
slider_color="#00C4D4",
|
| 667 |
+
slider_color_dark="#00C4D4",
|
| 668 |
+
table_even_background_fill="#0D1B2E",
|
| 669 |
+
table_even_background_fill_dark="#0D1B2E",
|
| 670 |
+
table_odd_background_fill="#0A1628",
|
| 671 |
+
table_odd_background_fill_dark="#0A1628",
|
| 672 |
+
border_color_primary="#1A2E48",
|
| 673 |
+
border_color_primary_dark="#1A2E48",
|
| 674 |
+
color_accent="#00C4D4",
|
| 675 |
+
color_accent_soft="#00A8BC22",
|
| 676 |
+
)
|
| 677 |
+
|
| 678 |
# ββ CSS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 679 |
+
CSS = """
|
| 680 |
+
@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:ital,wght@0,300;0,400;0,500;0,600;1,400&display=swap');
|
| 681 |
+
|
| 682 |
+
/* βββ NUCLEAR DARK OVERRIDE βββββββββββββββββββββββββββββββββββ */
|
| 683 |
+
*, *::before, *::after { box-sizing: border-box; }
|
| 684 |
+
|
| 685 |
+
html, body {
|
| 686 |
+
background: #070E1D !important;
|
| 687 |
+
color: #C8D8F0 !important;
|
|
|
|
| 688 |
}
|
| 689 |
|
| 690 |
+
/* Root & layout */
|
| 691 |
+
.gradio-container {
|
| 692 |
+
background: #070E1D !important;
|
| 693 |
+
max-width: 1440px !important;
|
| 694 |
+
margin: 0 auto !important;
|
| 695 |
+
padding: 16px 20px !important;
|
| 696 |
+
color: #C8D8F0 !important;
|
| 697 |
}
|
| 698 |
+
.gradio-container * {
|
| 699 |
+
font-family: 'IBM Plex Sans', sans-serif !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 700 |
}
|
| 701 |
+
|
| 702 |
+
/* Kill ALL white panel backgrounds */
|
| 703 |
+
.gradio-container .block,
|
| 704 |
+
.gradio-container .wrap,
|
| 705 |
+
.gradio-container .gap,
|
| 706 |
+
.gradio-container .form,
|
| 707 |
+
.gradio-container .prose,
|
| 708 |
+
.gradio-container section,
|
| 709 |
+
.gradio-container .contain,
|
| 710 |
+
footer {
|
| 711 |
+
background: transparent !important;
|
| 712 |
+
background-color: transparent !important;
|
| 713 |
}
|
| 714 |
+
|
| 715 |
+
/* Visible block backgrounds */
|
| 716 |
+
.gradio-container .block.padded,
|
| 717 |
+
.gradio-container .gr-padded {
|
| 718 |
+
background: #0D1B2E !important;
|
| 719 |
+
background-color: #0D1B2E !important;
|
| 720 |
+
border: 1px solid #1A2E48 !important;
|
| 721 |
+
border-radius: 10px !important;
|
| 722 |
+
}
|
| 723 |
+
|
| 724 |
+
/* Force ALL text to be visible */
|
| 725 |
+
.gradio-container label,
|
| 726 |
+
.gradio-container span,
|
| 727 |
+
.gradio-container p,
|
| 728 |
+
.gradio-container div,
|
| 729 |
+
.gradio-container h1, .gradio-container h2,
|
| 730 |
+
.gradio-container h3, .gradio-container h4 {
|
| 731 |
+
color: #C8D8F0;
|
| 732 |
+
}
|
| 733 |
+
|
| 734 |
+
/* ββ HEADER βββββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 735 |
+
.fn-header {
|
| 736 |
+
background: linear-gradient(135deg, #050E1F 0%, #0C1D38 50%, #0D3060 100%) !important;
|
| 737 |
+
border: 1px solid #1A2E48;
|
| 738 |
+
border-radius: 16px;
|
| 739 |
+
padding: 28px 40px;
|
| 740 |
+
margin-bottom: 20px;
|
| 741 |
+
box-shadow: 0 8px 48px rgba(0,0,0,0.65), 0 0 0 1px rgba(0,196,212,0.07);
|
| 742 |
+
position: relative; overflow: hidden;
|
| 743 |
+
}
|
| 744 |
+
.fn-header::after {
|
| 745 |
+
content: '';
|
| 746 |
+
position: absolute; top: -80px; right: -80px;
|
| 747 |
+
width: 320px; height: 320px; border-radius: 50%;
|
| 748 |
+
background: radial-gradient(circle, rgba(0,196,212,0.07) 0%, transparent 70%);
|
| 749 |
+
pointer-events: none;
|
| 750 |
+
}
|
| 751 |
+
.fn-logo {
|
| 752 |
+
font-family: 'Syne', sans-serif !important;
|
| 753 |
+
font-size: 32px; font-weight: 800; letter-spacing: -1.5px;
|
| 754 |
+
background: linear-gradient(135deg, #ffffff 0%, #00C4D4 100%);
|
| 755 |
+
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
|
| 756 |
+
background-clip: text; margin: 0 0 6px; display: block;
|
| 757 |
}
|
| 758 |
+
.fn-sub {
|
| 759 |
+
color: #5A7A9A !important;
|
| 760 |
+
-webkit-text-fill-color: #5A7A9A !important;
|
| 761 |
+
font-size: 13px; margin: 0 0 14px;
|
|
|
|
|
|
|
| 762 |
}
|
| 763 |
+
.fn-badges { display: flex; gap: 8px; flex-wrap: wrap; }
|
| 764 |
+
.fn-badge {
|
| 765 |
+
background: rgba(0,196,212,0.08);
|
| 766 |
+
border: 1px solid rgba(0,196,212,0.22);
|
| 767 |
+
color: #00C4D4 !important;
|
| 768 |
+
-webkit-text-fill-color: #00C4D4 !important;
|
| 769 |
+
font-family: 'IBM Plex Mono', monospace !important;
|
| 770 |
+
font-size: 11px; font-weight: 500; letter-spacing: 0.4px;
|
| 771 |
+
padding: 3px 12px; border-radius: 20px;
|
| 772 |
}
|
| 773 |
|
| 774 |
+
/* ββ LEFT COLUMN ββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 775 |
+
.left-col {
|
| 776 |
+
background: #0D1B2E !important;
|
| 777 |
+
background-color: #0D1B2E !important;
|
| 778 |
+
border: 1px solid #1A2E48 !important;
|
| 779 |
+
border-radius: 14px !important;
|
| 780 |
+
padding: 20px !important;
|
| 781 |
}
|
| 782 |
+
.left-col > * { background: transparent !important; background-color: transparent !important; }
|
| 783 |
+
|
| 784 |
+
/* ββ STEP HEADERS βββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββββ */
|
| 785 |
+
.step-hdr { display: flex; align-items: center; gap: 10px; margin: 20px 0 10px; }
|
| 786 |
+
.step-num {
|
| 787 |
+
width: 26px; height: 26px; border-radius: 50%;
|
| 788 |
+
background: linear-gradient(135deg, #0D5EAF, #00A8BC) !important;
|
| 789 |
+
display: flex; align-items: center; justify-content: center;
|
| 790 |
+
font-family: 'Syne', sans-serif !important; font-size: 12px; font-weight: 700;
|
| 791 |
+
color: white !important; -webkit-text-fill-color: white !important;
|
| 792 |
+
flex-shrink: 0; box-shadow: 0 0 16px rgba(0,196,212,0.3);
|
| 793 |
+
min-width: 26px;
|
| 794 |
}
|
| 795 |
+
.step-lbl {
|
| 796 |
+
font-family: 'Syne', sans-serif !important;
|
| 797 |
+
font-size: 13px; font-weight: 600;
|
| 798 |
+
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
|
|
|
|
|
|
|
| 799 |
}
|
| 800 |
+
.step-opt { color: #3d5e80 !important; -webkit-text-fill-color: #3d5e80 !important; font-size: 11px; }
|
| 801 |
+
|
| 802 |
+
/* ββ LABEL TEXT (above inputs) ββββββββββββββββββββββββββββββββ */
|
| 803 |
+
.gradio-container label > span,
|
| 804 |
+
.gradio-container .block > label > span,
|
| 805 |
+
.gradio-container .block-label span,
|
| 806 |
+
.gradio-container .label-wrap span,
|
| 807 |
+
.svelte-1b6s6s {
|
| 808 |
+
font-size: 11px !important;
|
| 809 |
+
font-weight: 600 !important;
|
| 810 |
+
letter-spacing: 0.6px !important;
|
| 811 |
+
text-transform: uppercase !important;
|
| 812 |
+
color: #5A7A9A !important;
|
| 813 |
+
-webkit-text-fill-color: #5A7A9A !important;
|
| 814 |
}
|
| 815 |
+
|
| 816 |
+
/* ββ TEXTBOXES / INPUTS βββββββββββββββββββββββββββββββββββββββ */
|
| 817 |
+
.gradio-container input,
|
| 818 |
+
.gradio-container textarea,
|
| 819 |
+
.gradio-container select,
|
| 820 |
+
.gradio-container [data-testid="textbox"] textarea,
|
| 821 |
+
.gradio-container [data-testid="textbox"] input {
|
| 822 |
+
background: #111E33 !important;
|
| 823 |
+
background-color: #111E33 !important;
|
| 824 |
+
border: 1px solid #1A2E48 !important;
|
| 825 |
+
color: #C8D8F0 !important;
|
| 826 |
+
-webkit-text-fill-color: #C8D8F0 !important;
|
| 827 |
+
border-radius: 8px !important;
|
| 828 |
+
font-size: 13px !important;
|
| 829 |
+
transition: border-color 0.2s, box-shadow 0.2s !important;
|
| 830 |
}
|
| 831 |
+
.gradio-container input:focus,
|
| 832 |
+
.gradio-container textarea:focus {
|
| 833 |
+
border-color: #00A8BC !important;
|
| 834 |
+
box-shadow: 0 0 0 3px rgba(0,196,212,0.12) !important;
|
| 835 |
+
outline: none !important;
|
|
|
|
|
|
|
|
|
|
| 836 |
}
|
| 837 |
+
.gradio-container input::placeholder,
|
| 838 |
+
.gradio-container textarea::placeholder {
|
| 839 |
+
color: #2a4560 !important;
|
| 840 |
+
-webkit-text-fill-color: #2a4560 !important;
|
| 841 |
}
|
| 842 |
|
| 843 |
/* Status boxes */
|
| 844 |
+
.status-box textarea {
|
| 845 |
+
background: rgba(0,196,212,0.04) !important;
|
| 846 |
+
background-color: rgba(0,196,212,0.04) !important;
|
| 847 |
+
border: 1px solid rgba(0,196,212,0.15) !important;
|
| 848 |
+
color: #00C4D4 !important; -webkit-text-fill-color: #00C4D4 !important;
|
| 849 |
+
font-family: 'IBM Plex Mono', monospace !important;
|
| 850 |
+
font-size: 11.5px !important; line-height: 1.6 !important;
|
| 851 |
}
|
| 852 |
|
| 853 |
/* Patient preview */
|
| 854 |
+
.pat-box textarea {
|
| 855 |
+
background: #080F1C !important; background-color: #080F1C !important;
|
| 856 |
+
border: 1px solid #1A2E48 !important;
|
| 857 |
+
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
|
| 858 |
+
font-family: 'IBM Plex Mono', monospace !important;
|
| 859 |
+
font-size: 12px !important; line-height: 1.8 !important;
|
|
|
|
| 860 |
}
|
| 861 |
|
| 862 |
+
/* Clinical report */
|
| 863 |
+
.report-box textarea {
|
| 864 |
+
background: #080F1C !important; background-color: #080F1C !important;
|
| 865 |
+
border: 1px solid #1A2E48 !important;
|
| 866 |
+
color: #9BB5D0 !important; -webkit-text-fill-color: #9BB5D0 !important;
|
| 867 |
+
font-family: 'IBM Plex Mono', monospace !important;
|
| 868 |
+
font-size: 12px !important; line-height: 1.85 !important;
|
| 869 |
+
padding: 16px !important;
|
|
|
|
| 870 |
}
|
| 871 |
|
| 872 |
+
/* ββ DROPDOWN βββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 873 |
+
.gradio-container [data-testid="dropdown"],
|
| 874 |
+
.gradio-container .gr-dropdown {
|
| 875 |
+
background: #111E33 !important; background-color: #111E33 !important;
|
| 876 |
+
border: 1px solid #1A2E48 !important;
|
| 877 |
+
border-radius: 8px !important;
|
| 878 |
+
}
|
| 879 |
+
.gradio-container [data-testid="dropdown"] input,
|
| 880 |
+
.gradio-container [data-testid="dropdown"] span,
|
| 881 |
+
.gradio-container [data-testid="dropdown"] div {
|
| 882 |
+
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
|
| 883 |
+
background: transparent !important;
|
| 884 |
+
}
|
| 885 |
+
ul[role="listbox"] {
|
| 886 |
+
background: #111E33 !important; background-color: #111E33 !important;
|
| 887 |
+
border: 1px solid #1A2E48 !important;
|
| 888 |
+
border-radius: 8px !important;
|
| 889 |
+
box-shadow: 0 8px 32px rgba(0,0,0,0.55) !important;
|
| 890 |
+
}
|
| 891 |
+
li[role="option"] {
|
| 892 |
+
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
|
| 893 |
+
background: transparent !important;
|
| 894 |
+
}
|
| 895 |
+
li[role="option"]:hover { background: #1A2E48 !important; }
|
| 896 |
+
li[role="option"][aria-selected="true"] {
|
| 897 |
+
background: rgba(0,168,188,0.15) !important;
|
| 898 |
+
color: #00C4D4 !important; -webkit-text-fill-color: #00C4D4 !important;
|
| 899 |
}
|
| 900 |
|
| 901 |
+
/* ββ BUTTONS ββββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 902 |
+
.run-btn button {
|
| 903 |
+
background: linear-gradient(135deg, #0D5EAF 0%, #00A8BC 100%) !important;
|
| 904 |
+
border: none !important; border-radius: 10px !important;
|
| 905 |
+
font-family: 'Syne', sans-serif !important;
|
| 906 |
+
font-size: 15px !important; font-weight: 700 !important;
|
| 907 |
+
color: white !important; -webkit-text-fill-color: white !important;
|
| 908 |
+
padding: 16px !important;
|
| 909 |
+
box-shadow: 0 4px 24px rgba(0,168,188,0.35) !important;
|
| 910 |
+
transition: all 0.25s !important; width: 100% !important;
|
| 911 |
+
}
|
| 912 |
+
.run-btn button:hover {
|
| 913 |
+
box-shadow: 0 6px 32px rgba(0,168,188,0.55) !important;
|
| 914 |
+
transform: translateY(-2px) !important;
|
| 915 |
}
|
| 916 |
+
.pdf-btn button {
|
| 917 |
+
background: linear-gradient(135deg, #00B87C 0%, #0B8C7A 100%) !important;
|
| 918 |
+
border: none !important; border-radius: 8px !important;
|
| 919 |
+
font-family: 'Syne', sans-serif !important;
|
| 920 |
+
font-size: 13px !important; font-weight: 600 !important;
|
| 921 |
+
color: white !important; -webkit-text-fill-color: white !important;
|
| 922 |
+
box-shadow: 0 3px 16px rgba(0,184,124,0.3) !important;
|
| 923 |
+
transition: all 0.2s !important;
|
| 924 |
}
|
| 925 |
+
.pdf-btn button:hover { transform: translateY(-1px) !important; }
|
| 926 |
+
|
| 927 |
+
/* ββ ACCORDION ββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 928 |
+
.gradio-container details,
|
| 929 |
+
.gradio-container details > summary {
|
| 930 |
+
background: #0D1B2E !important;
|
| 931 |
+
background-color: #0D1B2E !important;
|
| 932 |
+
border: 1px solid #1A2E48 !important;
|
| 933 |
+
border-radius: 10px !important;
|
| 934 |
+
color: #C8D8F0 !important;
|
| 935 |
+
}
|
| 936 |
+
.gradio-container details > summary {
|
| 937 |
+
font-family: 'Syne', sans-serif !important;
|
| 938 |
+
font-size: 13px !important; font-weight: 600 !important;
|
| 939 |
+
padding: 12px 16px !important; cursor: pointer !important;
|
| 940 |
+
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
|
| 941 |
+
list-style: none;
|
| 942 |
+
}
|
| 943 |
+
.gradio-container details[open] > summary { border-radius: 10px 10px 0 0 !important; }
|
| 944 |
+
|
| 945 |
+
/* ββ FILE UPLOAD ββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 946 |
+
.gradio-container [data-testid="upload-btn"],
|
| 947 |
+
.gradio-container .upload-container,
|
| 948 |
+
.gradio-container [class*="upload-zone"],
|
| 949 |
+
.gradio-container .gr-file {
|
| 950 |
+
background: #111E33 !important; background-color: #111E33 !important;
|
| 951 |
+
border: 1.5px dashed #1A2E48 !important;
|
| 952 |
+
border-radius: 10px !important; transition: all 0.2s !important;
|
| 953 |
+
}
|
| 954 |
+
.gradio-container [data-testid="upload-btn"]:hover,
|
| 955 |
+
.gradio-container .upload-container:hover {
|
| 956 |
+
border-color: #00A8BC !important;
|
| 957 |
+
background-color: rgba(0,168,188,0.04) !important;
|
| 958 |
+
}
|
| 959 |
+
.gradio-container [data-testid="upload-btn"] *,
|
| 960 |
+
.gradio-container .upload-container * {
|
| 961 |
+
color: #5A7A9A !important; -webkit-text-fill-color: #5A7A9A !important;
|
| 962 |
+
}
|
| 963 |
+
|
| 964 |
+
/* File list inside upload */
|
| 965 |
+
.gradio-container [class*="file-preview"],
|
| 966 |
+
.gradio-container [data-testid="file"] {
|
| 967 |
+
background: #080F1C !important; background-color: #080F1C !important;
|
| 968 |
+
border: 1px solid #1A2E48 !important; border-radius: 6px !important;
|
| 969 |
+
max-height: 150px !important; overflow-y: auto !important;
|
| 970 |
+
}
|
| 971 |
+
.gradio-container [class*="file-name"],
|
| 972 |
+
.gradio-container [class*="file"] span {
|
| 973 |
+
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
|
| 974 |
+
font-size: 11.5px !important;
|
| 975 |
}
|
|
|
|
| 976 |
|
| 977 |
+
/* ββ TABS βββββββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 978 |
+
.gradio-container .tab-nav,
|
| 979 |
+
.gradio-container [role="tablist"] {
|
| 980 |
+
background: #0A1628 !important; background-color: #0A1628 !important;
|
| 981 |
+
border-bottom: 1px solid #1A2E48 !important;
|
| 982 |
+
border-radius: 12px 12px 0 0 !important;
|
| 983 |
+
padding: 0 4px !important;
|
| 984 |
+
}
|
| 985 |
+
.gradio-container button[role="tab"] {
|
| 986 |
+
font-family: 'Syne', sans-serif !important;
|
| 987 |
+
font-size: 13px !important; font-weight: 600 !important;
|
| 988 |
+
color: #5A7A9A !important; -webkit-text-fill-color: #5A7A9A !important;
|
| 989 |
+
padding: 12px 20px !important;
|
| 990 |
+
border-bottom: 2px solid transparent !important;
|
| 991 |
+
background: transparent !important; transition: all 0.2s !important;
|
| 992 |
}
|
| 993 |
+
.gradio-container button[role="tab"][aria-selected="true"] {
|
| 994 |
+
color: #00C4D4 !important; -webkit-text-fill-color: #00C4D4 !important;
|
| 995 |
+
border-bottom: 2px solid #00C4D4 !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
| 996 |
}
|
| 997 |
+
.gradio-container button[role="tab"]:hover {
|
| 998 |
+
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
|
|
|
|
|
|
|
| 999 |
}
|
| 1000 |
+
.gradio-container [role="tabpanel"] {
|
| 1001 |
+
background: #0A1628 !important; background-color: #0A1628 !important;
|
| 1002 |
+
border: 1px solid #1A2E48 !important; border-top: none !important;
|
| 1003 |
+
border-radius: 0 0 12px 12px !important; padding: 16px !important;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1004 |
}
|
| 1005 |
|
| 1006 |
+
/* ββ PLOT CONTAINERS ββββββββββββββββββββββββββββββββββββββββββ */
|
| 1007 |
+
.gradio-container .gr-plot,
|
| 1008 |
+
.gradio-container [data-testid="plot"],
|
| 1009 |
+
.gradio-container [class*="plot"] {
|
| 1010 |
+
background: #0D1B2E !important; background-color: #0D1B2E !important;
|
| 1011 |
+
border: 1px solid #1A2E48 !important;
|
| 1012 |
+
border-radius: 10px !important; overflow: hidden !important;
|
| 1013 |
}
|
| 1014 |
|
| 1015 |
+
/* ββ SLIDER βββββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 1016 |
+
input[type="range"] { accent-color: #00C4D4 !important; }
|
| 1017 |
+
.gradio-container [data-testid="slider"],
|
| 1018 |
+
.gradio-container .gr-slider {
|
| 1019 |
+
background: transparent !important;
|
| 1020 |
}
|
| 1021 |
+
|
| 1022 |
+
/* ββ SCROLLBAR ββββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 1023 |
+
::-webkit-scrollbar { width: 4px; height: 4px; }
|
| 1024 |
+
::-webkit-scrollbar-track { background: #080F1C; }
|
| 1025 |
+
::-webkit-scrollbar-thumb { background: #1A2E48; border-radius: 2px; }
|
| 1026 |
+
::-webkit-scrollbar-thumb:hover { background: #2A3E58; }
|
| 1027 |
+
|
| 1028 |
+
/* ββ REPORT TITLE βββββββββββββββββββββββββββββββββββββββββββββ */
|
| 1029 |
+
.report-title-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
|
| 1030 |
+
.report-title {
|
| 1031 |
+
font-family: 'Syne', sans-serif;
|
| 1032 |
+
font-size: 14px; font-weight: 700;
|
| 1033 |
+
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
|
| 1034 |
}
|
| 1035 |
+
|
| 1036 |
+
/* ββ FOOTER HTML ββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 1037 |
+
.fn-footer {
|
| 1038 |
+
text-align: center; margin-top: 20px; padding: 14px;
|
| 1039 |
+
border-top: 1px solid #1A2E48;
|
| 1040 |
+
color: #2a4560 !important; -webkit-text-fill-color: #2a4560 !important;
|
| 1041 |
+
font-family: 'IBM Plex Mono', monospace !important; font-size: 11px;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1042 |
}
|
| 1043 |
|
| 1044 |
+
/* Hide Gradio branding */
|
| 1045 |
+
footer.svelte-1ax1toq, .built-with, .show-api { display: none !important; }
|
| 1046 |
|
| 1047 |
+
/* ββ DICOM hint (inside accordion) ββββββββββββββββββββββββββββ */
|
| 1048 |
+
.dicom-hint p, .dicom-hint {
|
| 1049 |
+
color: #3d5e80 !important; -webkit-text-fill-color: #3d5e80 !important;
|
| 1050 |
+
font-size: 11.5px !important;
|
| 1051 |
+
}
|
| 1052 |
+
.dicom-hint code {
|
| 1053 |
+
color: #00C4D4 !important; -webkit-text-fill-color: #00C4D4 !important;
|
| 1054 |
+
background: rgba(0,196,212,0.08) !important;
|
| 1055 |
+
padding: 1px 5px; border-radius: 3px;
|
| 1056 |
+
}
|
| 1057 |
"""
|
| 1058 |
|
| 1059 |
+
# ββ APP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1060 |
+
with gr.Blocks(title="FibrosisNet-V4", theme=theme, css=CSS) as demo:
|
| 1061 |
|
|
|
|
| 1062 |
gr.HTML("""
|
| 1063 |
<div class="fn-header">
|
| 1064 |
+
<span class="fn-logo">π« FibrosisNet-V4</span>
|
| 1065 |
+
<p class="fn-sub">Pulmonary Fibrosis Progression Prediction Β· Multi-Backbone 2.5D Deep Learning</p>
|
| 1066 |
<div class="fn-badges">
|
| 1067 |
<span class="fn-badge">Swin-Tiny 2.5D</span>
|
| 1068 |
<span class="fn-badge">SE Attention Pooling</span>
|
| 1069 |
<span class="fn-badge">Cross-Attention Fusion</span>
|
| 1070 |
<span class="fn-badge">Calibrated Uncertainty</span>
|
| 1071 |
<span class="fn-badge">OOF β6.6629 β</span>
|
| 1072 |
+
<span class="fn-badge">NIT Calicut Β· May 2026</span>
|
| 1073 |
</div>
|
| 1074 |
</div>
|
| 1075 |
""")
|
| 1076 |
|
| 1077 |
+
with gr.Row(equal_height=False):
|
| 1078 |
|
| 1079 |
# ββ LEFT PANEL ββ
|
| 1080 |
+
with gr.Column(scale=1, min_width=360, elem_classes="left-col"):
|
| 1081 |
|
| 1082 |
+
gr.HTML('<div class="step-hdr"><div class="step-num">1</div><div class="step-lbl">Upload OSIC Test CSV</div></div>')
|
|
|
|
|
|
|
|
|
|
| 1083 |
csv_file = gr.File(label="test.csv Β· Patient Β· Weeks Β· FVC Β· Percent Β· Age Β· Sex Β· SmokingStatus",
|
| 1084 |
file_types=[".csv"])
|
| 1085 |
csv_status = gr.Textbox(label="CSV Status", lines=2, interactive=False,
|
| 1086 |
+
elem_classes="status-box")
|
| 1087 |
|
| 1088 |
+
gr.HTML('<div class="step-hdr"><div class="step-num">2</div><div class="step-lbl">Select Patient</div></div>')
|
|
|
|
|
|
|
|
|
|
| 1089 |
patient_dd = gr.Dropdown(label="Patient ID Β· auto-populated from CSV",
|
| 1090 |
choices=[], value=None, allow_custom_value=True)
|
| 1091 |
patient_info = gr.Textbox(label="Patient Preview", lines=10,
|
| 1092 |
+
interactive=False, elem_classes="pat-box")
|
| 1093 |
|
| 1094 |
+
gr.HTML('<div class="step-hdr"><div class="step-num">3</div><div class="step-lbl">Run Prediction</div></div>')
|
|
|
|
|
|
|
|
|
|
| 1095 |
predict_btn = gr.Button("π¬ Run FibrosisNet-V4 Prediction",
|
| 1096 |
elem_classes="run-btn", size="lg")
|
| 1097 |
|
| 1098 |
+
gr.HTML('<div class="step-hdr"><div class="step-num">4</div>'
|
| 1099 |
+
'<div class="step-lbl">Upload CT DICOM <span class="step-opt">(optional)</span></div></div>')
|
| 1100 |
+
with gr.Accordion("π©» Open DICOM Upload Panel", open=False):
|
| 1101 |
+
gr.HTML('<p class="dicom-hint">'
|
|
|
|
|
|
|
| 1102 |
'Upload <code>.dcm</code> slices for one patient\'s CT. '
|
| 1103 |
'Patient ID is auto-read from DICOM tags. '
|
| 1104 |
+
'File list is scrollable β the Predict button stays visible.</p>')
|
| 1105 |
+
dicom_files = gr.File(label="DICOM slices (.dcm)",
|
| 1106 |
file_count="multiple",
|
| 1107 |
file_types=[".dcm",".DCM"],
|
| 1108 |
+
elem_classes="dicom-up")
|
| 1109 |
dicom_status = gr.Textbox(label="DICOM Status", lines=2,
|
| 1110 |
+
interactive=False, elem_classes="status-box")
|
| 1111 |
|
| 1112 |
# ββ RIGHT PANEL ββ
|
| 1113 |
with gr.Column(scale=2):
|
| 1114 |
with gr.Tabs():
|
| 1115 |
with gr.Tab("π FVC Decline Graph"):
|
| 1116 |
+
fvc_plot = gr.Plot()
|
| 1117 |
|
| 1118 |
with gr.Tab("π« CT Lung Viewer"):
|
| 1119 |
+
ct_view = gr.Plot()
|
| 1120 |
+
gr.HTML('<p style="color:#3d5e80;font-size:11px;margin:10px 0 4px;'
|
| 1121 |
+
'font-family:IBM Plex Mono,monospace;letter-spacing:0.2px">'
|
| 1122 |
+
'ββ Slice Explorer: drag to browse axial slices ββ</p>')
|
| 1123 |
+
slice_slider = gr.Slider(0, 300, value=0, step=1, label="Axial Slice Index")
|
| 1124 |
+
slice_view = gr.Plot()
|
| 1125 |
+
slice_slider.change(fn=update_slice, inputs=slice_slider, outputs=slice_view)
|
| 1126 |
|
| 1127 |
with gr.Tab("π Clinical Report"):
|
| 1128 |
with gr.Row():
|
| 1129 |
+
gr.HTML('<div class="report-title">Clinical Summary Report</div>')
|
| 1130 |
+
pdf_btn = gr.Button("β¬ Download PDF Report",
|
| 1131 |
elem_classes="pdf-btn", size="sm", visible=False)
|
| 1132 |
report_box = gr.Textbox(label="", lines=36, max_lines=65,
|
| 1133 |
+
interactive=False, elem_classes="report-box")
|
| 1134 |
pdf_output = gr.File(label="PDF Ready", visible=False)
|
| 1135 |
|
| 1136 |
gr.HTML("""
|
| 1137 |
<div class="fn-footer">
|
| 1138 |
FibrosisNet-V4 Β· Balaji R Β· NIT Calicut Β· May 2026
|
| 1139 |
+
Β· OSIC Pulmonary Fibrosis Progression
|
| 1140 |
+
Β· β Research prototype β not for clinical use without physician oversight
|
| 1141 |
</div>
|
| 1142 |
""")
|
| 1143 |
|
| 1144 |
# Wiring
|
| 1145 |
+
csv_file.upload(fn=on_csv_upload, inputs=csv_file, outputs=[patient_dd, csv_status])
|
| 1146 |
+
dicom_files.upload(fn=on_dicom_upload, inputs=dicom_files, outputs=[patient_dd, dicom_status])
|
| 1147 |
+
patient_dd.change(fn=on_patient_select, inputs=patient_dd, outputs=patient_info)
|
| 1148 |
+
predict_btn.click(fn=run_all, inputs=[patient_dd, dicom_files],
|
| 1149 |
+
outputs=[fvc_plot, ct_view, report_box, pdf_btn, pdf_output])
|
| 1150 |
+
pdf_btn.click(fn=on_download_pdf, inputs=[], outputs=pdf_output)
|
| 1151 |
+
pdf_btn.click(fn=lambda: gr.update(visible=True), inputs=[], outputs=pdf_output)
|
| 1152 |
+
|
| 1153 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|