Spaces:
Sleeping
Sleeping
File size: 60,129 Bytes
024486e 1dbe98b 024486e de285d0 024486e 3a1057b f49d513 024486e f49d513 024486e f49d513 024486e f49d513 de285d0 1dbe98b de285d0 9bfe4bb 024486e de285d0 1dbe98b 9bfe4bb 024486e 3a1057b 024486e de285d0 9bfe4bb f49d513 024486e de285d0 024486e de285d0 9bfe4bb de285d0 9bfe4bb 024486e de285d0 024486e de285d0 9bfe4bb 024486e de285d0 9bfe4bb de285d0 f49d513 024486e de285d0 024486e de285d0 9bfe4bb de285d0 9bfe4bb de285d0 3a1057b de285d0 3a1057b f49d513 3a1057b 024486e de285d0 9bfe4bb de285d0 3a1057b de285d0 3a1057b de285d0 3a1057b de285d0 3a1057b f49d513 1dbe98b de285d0 024486e de285d0 024486e de285d0 024486e de285d0 024486e de285d0 f49d513 de285d0 1dbe98b de285d0 1dbe98b de285d0 1dbe98b 9bfe4bb de285d0 1e4c2d6 9bfe4bb 1dbe98b 9bfe4bb de285d0 1dbe98b de285d0 9bfe4bb 1dbe98b de285d0 1dbe98b 1e4c2d6 1dbe98b 9bfe4bb de285d0 1dbe98b 1e4c2d6 de285d0 9bfe4bb 1dbe98b de285d0 1dbe98b 3a1057b de285d0 1dbe98b de285d0 9bfe4bb 1e4c2d6 de285d0 1e4c2d6 de285d0 9bfe4bb 1e4c2d6 024486e de285d0 1e4c2d6 1dbe98b 1e4c2d6 9bfe4bb 1dbe98b 9bfe4bb 1e4c2d6 3a1057b 1dbe98b de285d0 1dbe98b 9bfe4bb de285d0 1dbe98b 9bfe4bb 1dbe98b de285d0 9bfe4bb de285d0 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb de285d0 1dbe98b 9bfe4bb de285d0 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b de285d0 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb de285d0 1dbe98b de285d0 1dbe98b 9bfe4bb de285d0 9bfe4bb 1dbe98b de285d0 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b de285d0 1dbe98b 9bfe4bb de285d0 1dbe98b de285d0 9bfe4bb 1dbe98b 9bfe4bb 3a1057b 9bfe4bb de285d0 3a1057b 9bfe4bb 3a1057b de285d0 9bfe4bb de285d0 1dbe98b de285d0 9bfe4bb de285d0 3a1057b 9bfe4bb de285d0 3a1057b 1dbe98b de285d0 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b de285d0 9bfe4bb de285d0 9bfe4bb 1dbe98b de285d0 9bfe4bb de285d0 1dbe98b de285d0 9bfe4bb de285d0 9bfe4bb de285d0 1dbe98b de285d0 9bfe4bb 1dbe98b de285d0 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb de285d0 9bfe4bb de285d0 1dbe98b de285d0 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 024486e 1dbe98b de285d0 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 1e4c2d6 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb 024486e 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b 024486e 9bfe4bb de285d0 1dbe98b 9bfe4bb 1dbe98b 9bfe4bb de285d0 9bfe4bb 1dbe98b 9bfe4bb 1dbe98b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 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 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 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 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 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 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 | """
FibrosisNet-V4 β Fixed Dark Theme Gradio App
"""
import os, json, warnings, math, io, datetime
import numpy as np
import pandas as pd
import gradio as gr
import torch
import torch.nn as nn
import torch.nn.functional as F
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import pydicom
import timm
warnings.filterwarnings("ignore")
try:
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.units import cm
from reportlab.platypus import (SimpleDocTemplate, Paragraph, Spacer,
Table, TableStyle, HRFlowable, Image as RLImage)
from reportlab.lib.enums import TA_CENTER, TA_LEFT
PDF_OK = True
except ImportError:
PDF_OK = False
# ββ CONFIG ββββββββββββββββββββββββββββββββββββββββββββββββββββ
IMG_SIZE = 224
NUM_SLICES = 16
HU_MIN, HU_MAX = -1000, 400
TAB_FEATURES = ["BaselineFVC","Percent","Age","Sex_enc","Smoking_enc",
"FVC_height_ratio","percent_age_interaction"]
SIN_PERIODS = (10., 26., 52., 104.)
SIN_DIM = len(SIN_PERIODS) * 2
TAB_DIM = len(TAB_FEATURES) + SIN_DIM
FUSION_DIM = 512; FUSION_HEADS = 8; FUSION_DEPTH = 1
# ββ MODEL βββββββββββββββββββββββββββββββββββββββββββββββββββββ
class SEAttentionPool(nn.Module):
def __init__(self, enc_dim, reduction=16):
super().__init__()
self.attn = nn.Sequential(nn.Linear(enc_dim,256),nn.Tanh(),nn.Linear(256,1))
self.se = nn.Sequential(nn.Linear(enc_dim,enc_dim//reduction),nn.ReLU(inplace=True),
nn.Linear(enc_dim//reduction,enc_dim),nn.Sigmoid())
def forward(self,feat):
w=F.softmax(self.attn(feat),dim=1); p=(feat*w).sum(dim=1); return p*self.se(p)
class FusionTransformer(nn.Module):
def __init__(self,ct_dim,tab_dim_in,fuse_dim=FUSION_DIM,n_heads=FUSION_HEADS,depth=FUSION_DEPTH):
super().__init__()
self.ct_proj=nn.Linear(ct_dim,fuse_dim); self.tab_proj=nn.Linear(tab_dim_in,fuse_dim)
layer=nn.TransformerDecoderLayer(d_model=fuse_dim,nhead=n_heads,
dim_feedforward=fuse_dim*4,dropout=0.1,activation="gelu",batch_first=True,norm_first=True)
self.cross_attn=nn.TransformerDecoder(layer,num_layers=depth); self.norm=nn.LayerNorm(fuse_dim)
def forward(self,ct_seq,tab_feat):
return self.norm(self.cross_attn(self.tab_proj(tab_feat).unsqueeze(1),self.ct_proj(ct_seq)).squeeze(1))
class TrajectoryHead(nn.Module):
def __init__(self,in_dim):
super().__init__()
self.week_proj=nn.Linear(3,64)
self.fc=nn.Sequential(nn.Linear(in_dim+64,512),nn.LayerNorm(512),nn.GELU(),nn.Dropout(0.20),
nn.Linear(512,256),nn.LayerNorm(256),nn.GELU(),nn.Dropout(0.15),nn.Linear(256,3))
with torch.no_grad():
self.fc[-1].weight.data.zero_()
self.fc[-1].bias.data=torch.tensor([-2.,0.,5.])
self.sigma_rate_fc=nn.Linear(in_dim,1)
def _emb(self,w):
return torch.stack([torch.sin(w/52.),torch.cos(w/52.),(w/100.).clamp(-1,1)],dim=-1)
def forward(self,feat,base_fvc,weeks):
B,T=weeks.shape; sr=torch.exp(self.sigma_rate_fc(feat)).clamp(0.01,10.)
out=self.fc(torch.cat([feat.unsqueeze(1).expand(-1,T,-1),F.gelu(self.week_proj(self._emb(weeks)))],dim=-1))
mu=base_fvc.view(B,1)+out[...,1:2].squeeze(-1)+out[...,0:1].squeeze(-1)*weeks
sigma=(torch.exp(out[...,2:3]).clamp(50,500).squeeze(-1)+sr*weeks.abs()).clamp(70,3000)
return mu,sigma
class FibrosisModel2p5D(nn.Module):
def __init__(self,backbone_name,pretrained=False):
super().__init__()
self.backbone=timm.create_model(backbone_name,pretrained=pretrained,num_classes=0,global_pool="")
enc_dim=self.backbone.num_features; self.gap=nn.AdaptiveAvgPool2d(1)
self.se_pool=SEAttentionPool(enc_dim)
self.tab_mlp=nn.Sequential(nn.Linear(TAB_DIM,256),nn.LayerNorm(256),nn.GELU(),nn.Dropout(0.1),
nn.Linear(256,128),nn.LayerNorm(128),nn.GELU())
self.fusion=FusionTransformer(enc_dim,128); self.head=TrajectoryHead(FUSION_DIM)
def encode_ct(self,x):
B,C,D,H,W=x.shape; x2d=x.permute(0,2,1,3,4).reshape(B*D,C,H,W)
raw=self.backbone.forward_features(x2d)
feat=(raw[:,0] if raw.ndim==3 else
raw.mean(dim=(1,2)) if raw.shape[-1]==self.backbone.num_features else self.gap(raw).flatten(1))
return feat.view(B,D,-1)
def forward(self,vol,tab,base_fvc,weeks):
return self.head(self.fusion(self.encode_ct(vol),self.tab_mlp(tab)),base_fvc,weeks)
def _load_model():
for name in ["swin_tiny_patch4_window7_224.ms_in1k","swin_tiny_patch4_window7_224"]:
try: m=FibrosisModel2p5D(name,pretrained=False); break
except: continue
if os.path.exists("swintiny_fold3.pt"):
ckpt=torch.load("swintiny_fold3.pt",map_location="cpu")
state=ckpt.get("model_state_dict",ckpt.get("ema_state_dict",ckpt))
state={k.replace("_orig_mod.",""):v for k,v in state.items()}
miss,unex=m.load_state_dict(state,strict=False)
print(f"Loaded | missing={len(miss)} unexpected={len(unex)}")
else: print("swintiny_fold3.pt not found β demo mode")
m.eval(); return m
def _load_norm():
if os.path.exists("norm_stats.json"):
ns=json.load(open("norm_stats.json"))
return np.array(ns["t_mean"],dtype=np.float32),np.array(ns["t_std"],dtype=np.float32)
return (np.array([2700.,75.,65.,0.5,1.,0.77,1.07],dtype=np.float32),
np.array([800.,18.,9.,0.5,0.7,0.15,0.20],dtype=np.float32))
MODEL=_load_model(); T_MEAN,T_STD=_load_norm()
# ββ DATA ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def prepare_features(df):
df=df.copy(); df.columns=[c.strip() for c in df.columns]
df["Sex_enc"]=(df["Sex"].str.strip()=="Male").astype(float)
df["Smoking_enc"]=df["SmokingStatus"].str.strip().map(
{"Never smoked":0.,"Never smoker":0.,"Ex-smoker":1.,"Currently smokes":2.}).fillna(0.)
bl_idx=df.groupby("Patient")["Weeks"].idxmin()
bl_map=df.loc[bl_idx].set_index("Patient")[["FVC","Percent","Age"]]
df["BaselineFVC"]=df["Patient"].map(bl_map["FVC"])
df["BaselineWeek"]=df.groupby("Patient")["Weeks"].transform("min")
df["WeekDelta"]=df["Weeks"]-df["BaselineWeek"]
df["Percent"]=df["Patient"].map(bl_map["Percent"])
df["Age"]=df["Patient"].map(bl_map["Age"])
df["DeltaFVC"]=df["FVC"]-df["BaselineFVC"]
df["PredictedFVC"]=(df["BaselineFVC"]/(df["Percent"]/100+1e-6)).clip(1000,8000)
df["FVC_height_ratio"]=df["BaselineFVC"]/(df["PredictedFVC"]+1e-6)
df["percent_age_interaction"]=(df["Percent"]/100.)*(df["Age"]/70.)
return df
def extract_patient(df,pid):
pat=df[df["Patient"]==pid].sort_values("WeekDelta").reset_index(drop=True)
if pat.empty: return None,None
return pat.iloc[0],pat
def detect_pid(files):
for f in (files or []):
try:
ds=pydicom.dcmread(f.name if hasattr(f,"name") else f,stop_before_pixels=True)
pid=str(getattr(ds,"PatientID","")).strip()
if pid: return pid
except: continue
return None
# ββ CT ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def _extent(vol,thr=0.06):
m=vol.mean(axis=(1,2)); mask=m>thr
if mask.sum()<5: return 0,vol.shape[0]-1
return int(np.argmax(mask)),int(len(mask)-np.argmax(mask[::-1])-1)
def _sample(vol,n=NUM_SLICES,basal=0.65):
lo,hi=_extent(vol); mid=(lo+hi)//2; nl=int(n*basal)
idx=np.concatenate([np.linspace(lo,mid-1,n-nl).astype(int),
np.linspace(mid,hi,nl).astype(int)]).clip(0,vol.shape[0]-1)
t=torch.from_numpy(vol[idx]).unsqueeze(0).unsqueeze(0).float()
t=F.interpolate(t,size=(n,IMG_SIZE,IMG_SIZE),mode="trilinear",align_corners=False)
return t.squeeze(0).squeeze(0).numpy()
def _3ch(sl):
return np.stack([sl,(sl>0.05).astype(np.float32),np.clip((sl-0.3)*2.,0,1)],axis=0).astype(np.float32)
def load_dicoms(files):
if not files: return None
slices,positions=[],[]
for f in files:
try:
ds=pydicom.dcmread(f.name if hasattr(f,"name") else f)
img=ds.pixel_array.astype(np.float32)
img=img*float(getattr(ds,"RescaleSlope",1))+float(getattr(ds,"RescaleIntercept",0))
pos=float(getattr(ds,"ImagePositionPatient",[0,0,0])[-1] if hasattr(ds,"ImagePositionPatient") else 0)
slices.append(img); positions.append(pos)
except: continue
if not slices: return None
vol=np.stack([slices[i] for i in np.argsort(positions)])
return np.clip((vol-HU_MIN)/(HU_MAX-HU_MIN),0,1)
def _sin(w):
return np.array([f(w/p) for p in SIN_PERIODS for f in (math.sin,math.cos)],dtype=np.float32)
def build_tab(bl,bw=0.):
vals=np.array([bl[f] for f in TAB_FEATURES],dtype=np.float32)
return np.concatenate([(vals-T_MEAN)/(T_STD+1e-6),_sin(bw)])
def run_inference(bl,volume,bw=0.):
tab_t=torch.from_numpy(build_tab(bl,bw)).unsqueeze(0)
bfvc_t=torch.tensor([float(bl["BaselineFVC"])],dtype=torch.float32)
weeks_t=torch.arange(0,145,dtype=torch.float32).unsqueeze(0)
vol_t=(torch.from_numpy(_3ch(_sample(volume))).unsqueeze(0) if volume is not None
else torch.zeros(1,3,NUM_SLICES,IMG_SIZE,IMG_SIZE))
with torch.no_grad():
mu,sigma=MODEL(vol_t,tab_t,bfvc_t,weeks_t)
return mu.squeeze().numpy(),sigma.squeeze().numpy()
# ββ MATPLOTLIB DARK THEME βββββββββββββββββββββββββββββββββββββ
BG = "#0D1B2E"
BG2 = "#0A1628"
COL = {"text":"#C8D8F0","muted":"#5A7A9A","border":"#1A2E48",
"cyan":"#00C4D4","green":"#00B87C","amber":"#E8971A",
"red":"#E03C3C","blue":"#1A6FBF","teal":"#0B8C7A"}
def _mpl_fig(w=15,h=7.5):
fig=plt.figure(figsize=(w,h),facecolor=BG)
return fig
def _style_ax(ax):
ax.set_facecolor(BG2)
for sp in ax.spines.values(): sp.set_edgecolor(COL["border"])
ax.tick_params(colors=COL["muted"],labelsize=9)
ax.xaxis.label.set_color(COL["text"]); ax.yaxis.label.set_color(COL["text"])
ax.title.set_color(COL["text"])
ax.grid(True,color=COL["border"],alpha=0.6,linewidth=0.5)
def _empty(msg=""):
fig=_mpl_fig(8,3.5)
ax=fig.add_subplot(111); _style_ax(ax)
ax.text(0.5,0.5,msg,ha="center",va="center",transform=ax.transAxes,
color=COL["muted"],fontsize=12,style="italic")
ax.axis("off"); return fig
def make_fvc_plot(bl,visits,mu,sigma):
fvc_bl=float(bl["BaselineFVC"]); norm_fvc=float(bl["PredictedFVC"])
pid=str(bl["Patient"]); weeks=np.arange(0,145)
vis_wk=visits["WeekDelta"].values.astype(float)
vis_fvc=visits["FVC"].values.astype(float)
dec_1yr=(fvc_bl-mu[52])/fvc_bl*100
fig=_mpl_fig(18,9)
gs=gridspec.GridSpec(2,3,figure=fig,hspace=0.50,wspace=0.38,
left=0.06,right=0.98,top=0.92,bottom=0.10)
ax_main=fig.add_subplot(gs[:,0:2])
ax_bar =fig.add_subplot(gs[0,2])
ax_sev =fig.add_subplot(gs[1,2])
for ax in [ax_main,ax_bar,ax_sev]: _style_ax(ax)
ax_main.fill_between(weeks,mu-2*sigma,mu+2*sigma,alpha=0.07,color=COL["cyan"])
ax_main.fill_between(weeks,mu-sigma, mu+sigma, alpha=0.18,color=COL["cyan"],label="Β±1Ο confidence")
ax_main.plot(weeks,mu,color=COL["cyan"],lw=2.5,zorder=5,label="FibrosisNet-V4")
ax_main.axhline(fvc_bl, color=COL["muted"],ls="--",lw=1.4,alpha=0.8,label=f"Baseline {fvc_bl:.0f} ml")
ax_main.axhline(fvc_bl*0.90, color=COL["amber"],ls=":" ,lw=2.0,label="β10% threshold")
ax_main.axhline(fvc_bl*0.80, color=COL["red"], ls=":" ,lw=1.3,alpha=0.65,label="β20% threshold")
ax_main.axhline(norm_fvc, color=COL["teal"], ls="-.",lw=1.2,alpha=0.65,label=f"Est. normal {norm_fvc:.0f} ml")
for wk,lbl in [(26,"6mo"),(52,"1yr"),(78,"18mo"),(104,"2yr")]:
ax_main.axvline(wk,color=COL["border"],lw=1,alpha=0.8)
ax_main.text(wk+1,mu.min()*0.974,lbl,fontsize=7.5,color=COL["muted"])
if len(vis_wk)>0:
ax_main.plot(vis_wk,vis_fvc,color=COL["red"],lw=1.6,ls="--",alpha=0.75,zorder=6)
ax_main.scatter(vis_wk,vis_fvc,color=COL["red"],s=90,zorder=7,
edgecolors=BG,linewidths=1.8,label="Actual FVC (CSV)")
for wk,fv in zip(vis_wk,vis_fvc):
ax_main.annotate(f"{fv:.0f}",xy=(wk,fv),xytext=(5,9),textcoords="offset points",
fontsize=7.5,color=COL["red"],fontweight="bold")
ax_main.scatter([0],[fvc_bl],color=COL["cyan"],s=120,zorder=8,edgecolors=BG,lw=2)
ax_main.set_xlabel("Weeks from Baseline",fontsize=13,labelpad=10)
ax_main.set_ylabel("Forced Vital Capacity (ml)",fontsize=13,labelpad=10)
ax_main.set_title(f"FVC Decline Trajectory Β· {pid}",fontsize=15,fontweight="bold",pad=14)
leg=ax_main.legend(fontsize=9.5,loc="lower left",facecolor=BG2,edgecolor=COL["border"],framealpha=0.92)
for t in leg.get_texts(): t.set_color(COL["text"])
cps=[0,13,26,52,78,104,144]; clabs=["0w","3m","6m","1yr","18m","2yr","End"]
fvc_ck=[mu[min(w,144)] for w in cps]
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]
bars=ax_bar.bar(clabs,fvc_ck,color=bcols,edgecolor=BG,lw=1.2,width=0.68,zorder=3)
ax_bar.axhline(fvc_bl, color=COL["muted"],ls="--",lw=1.1,alpha=0.7,zorder=4)
ax_bar.axhline(fvc_bl*0.9,color=COL["amber"],ls=":",lw=1.1,alpha=0.7,zorder=4)
ax_bar.set_title("FVC at Key Timepoints",fontweight="bold",fontsize=11,pad=10)
ax_bar.tick_params(axis="x",labelsize=9)
for bar,val in zip(bars,fvc_ck):
ax_bar.text(bar.get_x()+bar.get_width()/2,bar.get_height()+18,
f"{val:.0f}",ha="center",fontsize=6.5,fontweight="bold",color=COL["text"])
if len(vis_wk)>0:
bx,by=[],[]
for wk,fv in zip(vis_wk,vis_fvc):
ni=int(np.argmin(np.abs(np.array(cps)-int(wk)))); bx.append(clabs[ni]); by.append(fv)
ax_bar.scatter(bx,by,color=COL["red"],zorder=6,s=55,edgecolors=BG,lw=1.5,label="Actual")
leg2=ax_bar.legend(fontsize=7,facecolor=BG2,edgecolor=COL["border"])
for t in leg2.get_texts(): t.set_color(COL["text"])
sev_label=("Stable / Mild" if dec_1yr<5 else "Moderate" if dec_1yr<10 else "Severe / Rapid")
sev_col=COL["green"] if dec_1yr<5 else COL["amber"] if dec_1yr<10 else COL["red"]
for (lo,hi),col in [((0,5),COL["green"]),((5,10),COL["amber"]),((10,20),"#D06020"),((20,30),COL["red"])]:
ax_sev.barh(0,hi-lo,left=lo,color=col,height=0.5,alpha=0.55)
mx=float(np.clip(dec_1yr,0,29))
ax_sev.axvline(mx,color="white",lw=3.5,zorder=5)
ax_sev.scatter([mx],[0],color=sev_col,s=100,zorder=6,edgecolors="white",lw=2)
ax_sev.set_xlim(0,30); ax_sev.set_ylim(-0.8,0.8); ax_sev.set_yticks([])
ax_sev.set_xlabel("Annual FVC Decline (%)",fontsize=10,labelpad=6)
ax_sev.set_title(f"{sev_label}\n{dec_1yr:.1f}% / year",fontweight="bold",fontsize=11,color=sev_col,pad=10)
for xt,xtl in zip([0,5,10,20,30],["0%","5%","10%","20%","30%"]):
ax_sev.text(xt,-0.65,xtl,fontsize=8,ha="center",color=COL["muted"])
age=int(bl["Age"]); sex="Male" if bl["Sex_enc"]==1. else "Female"
fig.suptitle(f"Age {age} Β· {sex} Β· Baseline FVC {fvc_bl:.0f} ml Β· {float(bl['Percent']):.0f}% predicted",
fontsize=11,color=COL["muted"],y=0.98)
return fig
def make_multiview(volume):
D,H,W=volume.shape
# DICOM slices are superiorβinferior; flip vertically so anatomy is right-way-up
axial = np.flipud(volume[D//2])
coronal = np.flipud(volume[:,H//2,:])
sagital = np.flipud(volume[:,:,W//2])
views=[(axial, f"Axial Β· {D//2+1}/{D}"),
(coronal, "Coronal Β· mid"),
(sagital, "Sagittal Β· mid")]
fig=plt.figure(figsize=(18,7.0),facecolor=BG)
fig.patch.set_facecolor(BG)
gs=gridspec.GridSpec(1,3,figure=fig,wspace=0.04,left=0.02,right=0.93,top=0.88,bottom=0.04)
for i,(img,ttl) in enumerate(views):
ax=fig.add_subplot(gs[0,i]); ax.set_facecolor("#010810")
im=ax.imshow(img,cmap="bone",vmin=0,vmax=1,
aspect="equal",interpolation="lanczos",
extent=[0,img.shape[1],0,img.shape[0]])
# Cyan border frame
for sp in ax.spines.values():
sp.set_edgecolor(COL["cyan"]); sp.set_linewidth(1.2); sp.set_visible(True)
ax.set_xticks([]); ax.set_yticks([])
ax.set_title(ttl,color=COL["cyan"],fontsize=11,pad=10,fontweight="bold",
fontfamily="monospace")
# Colorbar
cax=fig.add_axes([0.945,0.04,0.012,0.84])
cb=fig.colorbar(im,cax=cax)
cb.set_label("HU [0 β 1]",color=COL["muted"],fontsize=8,labelpad=8)
cb.ax.yaxis.set_tick_params(color=COL["muted"],labelsize=7)
plt.setp(cb.ax.yaxis.get_ticklabels(),color=COL["muted"])
cb.outline.set_edgecolor(COL["border"])
fig.suptitle("CT Lung Volume Β· Multi-Plane Reconstruction",
color=COL["text"],fontsize=13,fontweight="bold",y=0.97)
return fig
def update_slice(idx):
vol=_CACHE.get("vol")
if vol is None: return _empty("Upload DICOM and run prediction first")
idx=int(np.clip(idx,0,vol.shape[0]-1)); D,H,W=vol.shape
axial = np.flipud(vol[idx])
coronal = np.flipud(vol[:,H//2,:])
sagital = np.flipud(vol[:,:,W//2])
views=[(axial,f"Axial Β· {idx+1}/{D}"),(coronal,"Coronal Β· mid"),(sagital,"Sagittal Β· mid")]
fig=plt.figure(figsize=(18,7.0),facecolor=BG)
gs2=gridspec.GridSpec(1,3,figure=fig,wspace=0.04,left=0.02,right=0.93,top=0.88,bottom=0.04)
for i,(img,ttl) in enumerate(views):
ax=fig.add_subplot(gs2[0,i]); ax.set_facecolor("#010810")
ax.imshow(img,cmap="bone",vmin=0,vmax=1,aspect="equal",interpolation="lanczos",
extent=[0,img.shape[1],0,img.shape[0]])
for sp in ax.spines.values():
sp.set_edgecolor(COL["cyan"]); sp.set_linewidth(1.2); sp.set_visible(True)
ax.set_xticks([]); ax.set_yticks([])
ax.set_title(ttl,color=COL["cyan"],fontsize=11,pad=10,fontweight="bold",fontfamily="monospace")
fig.suptitle(f"Slice Explorer Β· Frame {idx+1} / {D}",color=COL["text"],fontsize=13,fontweight="bold",y=0.97)
return fig
# ββ PDF ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
def generate_pdf(bl,visits,mu,sigma,fvc_fig):
if not PDF_OK: return None
buf=io.BytesIO()
doc=SimpleDocTemplate(buf,pagesize=A4,leftMargin=2*cm,rightMargin=2*cm,topMargin=2.2*cm,bottomMargin=2*cm)
W=A4[0]-4*cm; styles=getSampleStyleSheet()
cNavy=colors.HexColor("#0F2142"); cBlue=colors.HexColor("#0D5EAF")
cCyan=colors.HexColor("#00A8BC"); cGreen=colors.HexColor("#00B87C")
cAmber=colors.HexColor("#E8971A"); cRed=colors.HexColor("#E03C3C")
cText=colors.HexColor("#1E293B"); cMuted=colors.HexColor("#64748B")
cLight=colors.HexColor("#F0F4FA"); cLighter=colors.HexColor("#E8EEF8")
def PS(name,**kw):
return ParagraphStyle(name,parent=styles.get(kw.pop("parent","Normal"),styles["Normal"]),**kw)
sTitle=PS("T",fontSize=26,fontName="Helvetica-Bold",textColor=cNavy,alignment=TA_CENTER,spaceAfter=3)
sSub =PS("S",fontSize=10,fontName="Helvetica",textColor=cBlue,alignment=TA_CENTER,spaceAfter=5)
sMeta =PS("M",fontSize=8.5,fontName="Helvetica",textColor=cMuted,alignment=TA_CENTER,spaceAfter=14)
sH =PS("H",fontSize=12,fontName="Helvetica-Bold",textColor=cNavy,spaceBefore=16,spaceAfter=5)
sBody =PS("B",fontSize=9.5,fontName="Helvetica",textColor=cText,leading=15,spaceAfter=4)
sBullet=PS("Bu",fontSize=9.5,fontName="Helvetica",textColor=cText,leading=15,leftIndent=12,spaceAfter=4)
sWarn =PS("W",fontSize=8,fontName="Helvetica-Oblique",textColor=colors.HexColor("#92400E"),alignment=TA_CENTER)
sFooter=PS("F",fontSize=7.5,fontName="Helvetica",textColor=cMuted,alignment=TA_CENTER)
pid=str(bl["Patient"]); age=int(bl["Age"])
sex="Male" if bl["Sex_enc"]==1. else "Female"
smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
fvc_bl=float(bl["BaselineFVC"]); pct=float(bl["Percent"]); norm=float(bl["PredictedFVC"])
fvc_6m=mu[26]; fvc_1yr=mu[52]; fvc_2yr=mu[104]
dec_pct=(fvc_bl-fvc_1yr)/fvc_bl*100; sig_1yr=sigma[52]
sev="Mild" if pct>=70 else "Moderate" if pct>=50 else "Severe"
sev_col=cGreen if sev=="Mild" else cAmber if sev=="Moderate" else cRed
sev_bg=(colors.HexColor("#D1FAE5") if sev=="Mild" else
colors.HexColor("#FEF3C7") if sev=="Moderate" else colors.HexColor("#FEE2E2"))
traj,monitor=(("Stable β within expected physiological variation","every 6 months") if dec_pct<5 else
("Slow Decline β clinically meaningful progression","every 3β4 months") if dec_pct<10 else
("Rapid Decline β urgent clinical attention warranted","monthly"))
wks10=next((w for w in range(145) if mu[w]<=fvc_bl*0.90),None)
vis_wk=visits["WeekDelta"].values.astype(float); vis_fvc=visits["FVC"].values.astype(float)
story=[]
story.append(Paragraph("FibrosisNet-V4",sTitle))
story.append(Paragraph("Pulmonary Fibrosis Progression Report",sSub))
story.append(Paragraph(
f"Generated {datetime.datetime.now().strftime('%d %B %Y at %H:%M')} Β· "
f"Swin-Tiny 2.5D Β· OOF β6.6629 Β· Beats Kaggle Baseline",sMeta))
story.append(HRFlowable(width="100%",thickness=3,color=cNavy,spaceAfter=1))
story.append(HRFlowable(width="100%",thickness=1,color=cCyan,spaceBefore=2,spaceAfter=14))
story.append(Paragraph("Patient Profile",sH))
def cell(lbl,val):
return Paragraph(f"<font size='7.5' color='#64748B'>{lbl}</font><br/>"
f"<font name='Helvetica-Bold' size='10'>{val}</font>",
PS(f"c{lbl}",fontSize=10,leading=15))
profile_data=[
[cell("PATIENT ID",pid), cell("AGE",f"{age} years"), cell("SEX",sex)],
[cell("SMOKING",smoking), cell("BASELINE FVC",f"{fvc_bl:.0f} ml"), cell("% PREDICTED",f"{pct:.1f}%")],
[cell("ESTIMATED NORMAL",f"{norm:.0f} ml"), cell("MODEL INPUTS","Baseline visit + CT"),
cell("CSV VISITS",f"{len(vis_wk)} recorded")],
]
pt=Table(profile_data,colWidths=[W/3]*3)
pt.setStyle(TableStyle([
("ROWBACKGROUNDS",(0,0),(-1,-1),[cLight,cLighter]),
("BOX",(0,0),(-1,-1),1,colors.HexColor("#CBD5E1")),
("INNERGRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
("TOPPADDING",(0,0),(-1,-1),8),("BOTTOMPADDING",(0,0),(-1,-1),8),
("LEFTPADDING",(0,0),(-1,-1),10),("RIGHTPADDING",(0,0),(-1,-1),8),
("VALIGN",(0,0),(-1,-1),"MIDDLE"),
]))
story.append(pt); story.append(Spacer(1,10))
story.append(Paragraph("Severity Assessment",sH))
sb_sty=PS("SBadge",fontSize=15,fontName="Helvetica-Bold",textColor=sev_col,alignment=TA_CENTER)
sb_sub=PS("SSub",fontSize=9,fontName="Helvetica",textColor=cMuted,alignment=TA_CENTER)
sev_tbl=Table([[Paragraph(f"{sev.upper()}",sb_sty)],
[Paragraph(f"{pct:.1f}% predicted Β· Mild β₯70% | Moderate 50β69% | Severe <50%",sb_sub)]],colWidths=[W])
sev_tbl.setStyle(TableStyle([("BACKGROUND",(0,0),(-1,-1),sev_bg),
("BOX",(0,0),(-1,-1),1.5,sev_col),
("TOPPADDING",(0,0),(-1,-1),10),("BOTTOMPADDING",(0,0),(-1,-1),8)]))
story.append(sev_tbl); story.append(Spacer(1,6))
story.append(Paragraph(f"<b>Trajectory:</b> {traj}",sBody))
story.append(Paragraph("Predicted FVC Trajectory",sH))
ph=["Timepoint","Predicted FVC","Change from Baseline","Β±1Ο Uncertainty"]
pd_rows=[
["6 months (Week 26)",f"{fvc_6m:.0f} ml",
f"β{fvc_bl-fvc_6m:.0f} ml ({(fvc_bl-fvc_6m)/fvc_bl*100:.1f}%)",
f"{fvc_6m-sigma[26]:.0f} β {fvc_6m+sigma[26]:.0f} ml"],
["1 year (Week 52)",f"{fvc_1yr:.0f} ml",
f"β{fvc_bl-fvc_1yr:.0f} ml ({dec_pct:.1f}%/yr)",
f"{fvc_1yr-sig_1yr:.0f} β {fvc_1yr+sig_1yr:.0f} ml"],
["2 years (Week 104)",f"{fvc_2yr:.0f} ml",
f"β{fvc_bl-fvc_2yr:.0f} ml ({(fvc_bl-fvc_2yr)/fvc_bl*100:.1f}%)",
f"{fvc_2yr-sigma[104]:.0f} β {fvc_2yr+sigma[104]:.0f} ml"],
]
prt=Table([ph]+pd_rows,colWidths=[W*0.28,W*0.17,W*0.31,W*0.24])
prt.setStyle(TableStyle([
("BACKGROUND",(0,0),(-1,0),cNavy),("TEXTCOLOR",(0,0),(-1,0),colors.white),
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,0),9),
("ROWBACKGROUNDS",(0,1),(-1,-1),[cLight,cLighter]),
("FONTSIZE",(0,1),(-1,-1),9),("FONTNAME",(0,1),(0,-1),"Helvetica-Bold"),
("TEXTCOLOR",(0,1),(0,-1),cNavy),
("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),
("LEFTPADDING",(0,0),(-1,-1),9),("ALIGN",(1,1),(-1,-1),"CENTER"),
]))
story.append(prt); story.append(Spacer(1,6))
thr_txt=(f"Week {wks10} (~{wks10//4} months)" if wks10 else "Not reached within 2.5-year horizon")
story.append(Paragraph(f"<b>Time to 10% FVC decline:</b> {thr_txt}",sBody))
if len(vis_wk)>0:
story.append(Paragraph("Observed vs Predicted",sH))
obs_h=["Visit Week","Actual FVC","Predicted FVC","Error","Within Β±1Ο"]
obs_rows=[]; errs=[]
for wk,afvc in zip(vis_wk,vis_fvc):
wi=int(np.clip(int(wk),0,144)); pred=mu[wi]; err=afvc-pred; errs.append(abs(err))
within="β" if abs(err)<=sigma[wi] else "β"
obs_rows.append([f"Week {int(wk)}",f"{afvc:.0f} ml",f"{pred:.0f} ml",
f"{'+' if err>=0 else ''}{err:.0f} ml",within])
obs_rows.append(["","","Mean Abs. Error",f"{np.mean(errs):.1f} ml",""])
ot=Table([obs_h]+obs_rows,colWidths=[W*0.18,W*0.18,W*0.20,W*0.17,W*0.13])
ot.setStyle(TableStyle([
("BACKGROUND",(0,0),(-1,0),cBlue),("TEXTCOLOR",(0,0),(-1,0),colors.white),
("FONTNAME",(0,0),(-1,0),"Helvetica-Bold"),("FONTSIZE",(0,0),(-1,0),9),
("ROWBACKGROUNDS",(0,1),(-1,-2),[cLight,cLighter]),
("BACKGROUND",(0,-1),(-1,-1),cLighter),("FONTNAME",(0,-1),(-1,-1),"Helvetica-Bold"),
("FONTSIZE",(0,1),(-1,-1),9),
("GRID",(0,0),(-1,-1),0.5,colors.HexColor("#CBD5E1")),
("TOPPADDING",(0,0),(-1,-1),6),("BOTTOMPADDING",(0,0),(-1,-1),6),
("LEFTPADDING",(0,0),(-1,-1),9),("ALIGN",(1,1),(-1,-1),"CENTER"),
]))
story.append(ot); story.append(Spacer(1,6))
story.append(Paragraph("FVC Decline Trajectory Chart",sH))
fig_buf=io.BytesIO(); fvc_fig.savefig(fig_buf,format="png",dpi=140,bbox_inches="tight")
fig_buf.seek(0)
story.append(RLImage(fig_buf,width=W,height=W*7.5/15)); story.append(Spacer(1,10))
story.append(Paragraph("Clinical Recommendations",sH))
for r in [f"<b>Spirometry:</b> {monitor}",
"<b>Physical:</b> 6-minute walk test at each visit",
"<b>Treatment:</b> "+("Discuss antifibrotic therapy (nintedanib / pirfenidone)"
if sev!="Mild" or dec_pct>=10 else "Continue current management plan"),
"<b>Rehabilitation:</b> Pulmonary rehabilitation referral recommended"]:
story.append(Paragraph(f" β’ {r}",sBullet))
story.append(Spacer(1,16))
story.append(HRFlowable(width="100%",thickness=1,color=colors.HexColor("#CBD5E1"),spaceAfter=8))
story.append(Paragraph(
"This report is produced by an AI research model for academic purposes only. "
"It must not substitute for clinical decisions without review by a qualified pulmonologist.",sWarn))
story.append(Spacer(1,4))
story.append(Paragraph(
"FibrosisNet-V4 Β· Swin-Tiny 2.5D Β· OOF β6.6629 vs Kaggle β6.6743 Β· "
"Balaji R Β· NIT Calicut Β· May 2026",sFooter))
doc.build(story); buf.seek(0); return buf.getvalue()
# ββ CACHE & CALLBACKS βββββββββββββββββββββββββββββββββββββββββ
_CACHE={"vol":None,"df":None,"last_fig":None,"last_bl":None,
"last_visits":None,"last_mu":None,"last_sigma":None}
def on_csv_upload(csv_file):
if csv_file is None: return gr.update(choices=[],value=None),"Upload a CSV file."
try:
df_raw=pd.read_csv(csv_file.name if hasattr(csv_file,"name") else csv_file)
df_raw.columns=[c.strip() for c in df_raw.columns]
if "Patient" not in df_raw.columns:
return gr.update(choices=[],value=None),"'Patient' column not found."
df_prep=prepare_features(df_raw); _CACHE["df"]=df_prep
pids=sorted(df_prep["Patient"].unique().tolist())
msg=f"β
{len(pids)} patients Β· {len(df_raw)} rows\n{', '.join(df_raw.columns[:6].tolist())}"
return gr.update(choices=pids,value=pids[0] if pids else None),msg
except Exception as e: return gr.update(choices=[],value=None),f"β {e}"
def on_dicom_upload(dicom_files):
if not dicom_files: return gr.update(),"No DICOM files."
n=len(dicom_files); pid=detect_pid(dicom_files); df=_CACHE.get("df")
if pid and df is not None and pid in df["Patient"].values:
return gr.update(value=pid),f"β
{n} files Β· Auto-matched:\n{pid}"
elif pid: return gr.update(),f"β {n} files Β· '{pid}' not in CSV"
return gr.update(),f"βΉ {n} files Β· No ID in DICOM tags"
def on_patient_select(pid):
df=_CACHE.get("df")
if df is None or not pid: return "Upload a CSV first."
bl,visits=extract_patient(df,pid)
if bl is None: return f"Patient '{pid}' not found."
sex="Male" if bl["Sex_enc"]==1. else "Female"
smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
sev="Mild" if float(bl['Percent'])>=70 else "Moderate" if float(bl['Percent'])>=50 else "Severe"
lines="\n".join(f" Week {int(r['WeekDelta']):>4} βΊ {r['FVC']:.0f} ml" for _,r in visits.iterrows())
return (f"ID βΊ {pid}\n"
f"Age/Sex βΊ {int(bl['Age'])} yrs / {sex}\n"
f"Smoking βΊ {smoking}\n"
f"Baseline βΊ {bl['BaselineFVC']:.0f} ml ({bl['Percent']:.1f}% predicted)\n"
f"Normal βΊ {bl['PredictedFVC']:.0f} ml\n"
f"Severity βΊ {sev}\n\nVisits\n{'β'*22}\n{lines}")
def run_all(pid,dicom_files):
NO=(gr.update(visible=False),gr.update(visible=False))
df=_CACHE.get("df")
if df is None: return _empty("Upload CSV first"),_empty(""),"Upload CSV first.",*NO
if not pid: return _empty("Select a patient"),_empty(""),"Select a Patient ID.",*NO
bl,visits=extract_patient(df,pid)
if bl is None: return _empty(f"Patient {pid} not found"),_empty(""),"Not found.",*NO
volume=load_dicoms(dicom_files) if dicom_files else None
_CACHE["vol"]=volume
mu,sigma=run_inference(bl,volume,float(bl.get("BaselineWeek",0.)))
fvc_fig=make_fvc_plot(bl,visits,mu,sigma)
ct_view=make_multiview(volume) if volume is not None else _empty("No DICOM β CT view unavailable")
_CACHE.update({"last_fig":fvc_fig,"last_bl":bl,"last_visits":visits,"last_mu":mu,"last_sigma":sigma})
fvc_bl=float(bl["BaselineFVC"]); pct=float(bl["Percent"])
sev="Mild" if pct>=70 else "Moderate" if pct>=50 else "Severe"
dec_pct=(fvc_bl-mu[52])/fvc_bl*100
traj,monitor=(("STABLE","every 6 months") if dec_pct<5 else
("SLOW DECLINE","every 3β4 months") if dec_pct<10 else ("RAPID DECLINE","monthly"))
wks10=next((w for w in range(145) if mu[w]<=fvc_bl*0.90),None)
vis_wk=visits["WeekDelta"].values.astype(float); vis_fvc=visits["FVC"].values.astype(float)
sex="Male" if bl["Sex_enc"]==1. else "Female"
smoking={0.:"Never smoker",1.:"Ex-smoker",2.:"Currently smokes"}.get(float(bl["Smoking_enc"]),"Unknown")
obs=""
if len(vis_wk)>0:
rows=[f" {'Week':>6} {'Actual':>8} {'Predicted':>10} {'Error':>8}"," "+"β"*40]
errs=[]
for wk,afvc in zip(vis_wk,vis_fvc):
wi=int(np.clip(int(wk),0,144)); pred=mu[wi]; err=afvc-pred; errs.append(abs(err))
rows.append(f" {int(wk):>6} {afvc:>8.0f} {pred:>10.0f} {err:>+8.0f} ml")
rows.append(f"\n Mean Absolute Error βΊ {np.mean(errs):.1f} ml")
obs="\n\n OBSERVED vs PREDICTED\n"+"".join(f" {r}\n" for r in rows)
report=(
f" FIBROSISNET-V4 Β· CLINICAL SUMMARY\n"
f" {'β'*46}\n\n"
f" PATIENT\n"
f" β ID βΊ {pid}\n"
f" β Age/Sex βΊ {int(bl['Age'])} yrs / {sex}\n"
f" β Smoking βΊ {smoking}\n"
f" β Baseline βΊ {fvc_bl:.0f} ml ({pct:.1f}% predicted)\n"
f" β Normal βΊ {float(bl['PredictedFVC']):.0f} ml (estimated)\n\n"
f" {'β'*46}\n"
f" SEVERITY (ATS/ERS)\n"
f" βΊ {sev.upper()} β {pct:.1f}% predicted FVC\n"
f" Mild β₯70% β Moderate 50β69% β Severe <50%\n\n"
f" {'β'*46}\n"
f" TRAJECTORY βΊ {traj}\n\n"
f" β 6 months βΊ {mu[26]:.0f} ml (β{fvc_bl-mu[26]:.0f} ml)\n"
f" β 1 year βΊ {mu[52]:.0f} ml (β{fvc_bl-mu[52]:.0f} ml Β· {dec_pct:.1f}%/yr)\n"
f" β 2 years βΊ {mu[104]:.0f} ml (β{fvc_bl-mu[104]:.0f} ml cumulative)\n"
f" β Β±1Ο@1yr βΊ {mu[52]-sigma[52]:.0f} β {mu[52]+sigma[52]:.0f} ml\n\n"
f" {'β'*46}\n"
f" 10% THRESHOLD\n"
f" βΊ {'Week '+str(wks10)+f' (~{wks10//4} months)' if wks10 else 'Not reached in 2.5-yr horizon'}\n"
f"{obs}\n"
f" {'β'*46}\n"
f" MONITORING\n"
f" βΊ Spirometry {monitor}\n"
f" βΊ {'Discuss antifibrotic therapy with specialist' if sev!='Mild' or dec_pct>=10 else 'Continue current management plan'}\n\n"
f" {'β'*46}\n"
f" β AI research model\n"
f" OOF β6.6629 β Kaggle baseline β6.6743 β\n"
f" Not for clinical use without physician oversight"
)
return fvc_fig,ct_view,report,gr.update(visible=True),gr.update(visible=False)
def on_download_pdf():
bl=_CACHE.get("last_bl"); visits=_CACHE.get("last_visits")
mu=_CACHE.get("last_mu"); sigma=_CACHE.get("last_sigma"); fig=_CACHE.get("last_fig")
if bl is None or mu is None: return None
pdf_bytes=generate_pdf(bl,visits,mu,sigma,fig)
if pdf_bytes is None: return None
path=f"/tmp/FibrosisNet_{str(bl['Patient'])[:20]}.pdf"
with open(path,"wb") as f: f.write(pdf_bytes)
return path
# ββ THEME βββββββββββββββββββββββββββββββββββββββββββββββββββββ
theme = gr.themes.Base(
primary_hue=gr.themes.Color(
c50="#e0f7fa", c100="#b2ebf2", c200="#80deea", c300="#4dd0e1",
c400="#26c6da", c500="#00BCD4", c600="#00ACC1", c700="#0097A7",
c800="#00838F", c900="#006064", c950="#004D40"),
secondary_hue=gr.themes.Color(
c50="#e8eaf6", c100="#c5cae9", c200="#9fa8da", c300="#7986cb",
c400="#5c6bc0", c500="#3f51b5", c600="#3949ab", c700="#303f9f",
c800="#283593", c900="#1a237e", c950="#0d1b69"),
neutral_hue=gr.themes.Color(
c50="#f0f4fa", c100="#d0dcea", c200="#a8bdd4", c300="#7a9ab8",
c400="#5a7a9a", c500="#3d5e80", c600="#2a4560", c700="#1a2e48",
c800="#0f1e34", c900="#080f1c", c950="#040810"),
font=[gr.themes.GoogleFont("Syne"), gr.themes.GoogleFont("IBM Plex Mono"), "sans-serif"],
font_mono=[gr.themes.GoogleFont("IBM Plex Mono"), "monospace"],
).set(
body_background_fill="#070E1D",
body_background_fill_dark="#070E1D",
body_text_color="#C8D8F0",
body_text_color_dark="#C8D8F0",
block_background_fill="#0D1B2E",
block_background_fill_dark="#0D1B2E",
block_border_color="#1A2E48",
block_border_color_dark="#1A2E48",
block_label_background_fill="#0D1B2E",
block_label_background_fill_dark="#0D1B2E",
block_label_text_color="#5A7A9A",
block_label_text_color_dark="#5A7A9A",
block_title_text_color="#C8D8F0",
block_title_text_color_dark="#C8D8F0",
input_background_fill="#111E33",
input_background_fill_dark="#111E33",
input_border_color="#1A2E48",
input_border_color_dark="#1A2E48",
input_placeholder_color="#3d5e80",
input_placeholder_color_dark="#3d5e80",
# CRITICAL: force input text color via theme vars
input_background_fill_focus="#111E33",
input_background_fill_focus_dark="#111E33",
panel_background_fill="#0A1628",
panel_background_fill_dark="#0A1628",
panel_border_color="#1A2E48",
panel_border_color_dark="#1A2E48",
button_primary_background_fill="linear-gradient(135deg, #0D5EAF, #00A8BC)",
button_primary_background_fill_dark="linear-gradient(135deg, #0D5EAF, #00A8BC)",
button_primary_text_color="#ffffff",
button_primary_text_color_dark="#ffffff",
button_secondary_background_fill="#111E33",
button_secondary_background_fill_dark="#111E33",
button_secondary_text_color="#C8D8F0",
button_secondary_text_color_dark="#C8D8F0",
checkbox_background_color="#111E33",
checkbox_background_color_dark="#111E33",
slider_color="#00C4D4",
slider_color_dark="#00C4D4",
table_even_background_fill="#0D1B2E",
table_even_background_fill_dark="#0D1B2E",
table_odd_background_fill="#0A1628",
table_odd_background_fill_dark="#0A1628",
border_color_primary="#1A2E48",
border_color_primary_dark="#1A2E48",
color_accent="#00C4D4",
color_accent_soft="#00A8BC22",
)
# ββ CSS ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
CSS = """
@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');
/* βββ NUCLEAR DARK OVERRIDE βββββββββββββββββββββββββββββββββββ */
*, *::before, *::after { box-sizing: border-box; }
html, body {
background: #070E1D !important;
color: #C8D8F0 !important;
}
/* Root & layout */
.gradio-container {
background: #070E1D !important;
max-width: 1440px !important;
margin: 0 auto !important;
padding: 16px 20px !important;
color: #C8D8F0 !important;
}
.gradio-container * {
font-family: 'IBM Plex Sans', sans-serif !important;
}
/* Kill ALL white panel backgrounds */
.gradio-container .block,
.gradio-container .wrap,
.gradio-container .gap,
.gradio-container .form,
.gradio-container .prose,
.gradio-container section,
.gradio-container .contain,
footer {
background: transparent !important;
background-color: transparent !important;
}
/* Visible block backgrounds */
.gradio-container .block.padded,
.gradio-container .gr-padded {
background: #0D1B2E !important;
background-color: #0D1B2E !important;
border: 1px solid #1A2E48 !important;
border-radius: 10px !important;
}
/* Force ALL text to be visible */
.gradio-container label,
.gradio-container span,
.gradio-container p,
.gradio-container div,
.gradio-container h1, .gradio-container h2,
.gradio-container h3, .gradio-container h4 {
color: #C8D8F0;
}
/* ββ HEADER βββββββββββββββββββββββββββββββββββββββββββββββββββ */
.fn-header {
background: linear-gradient(135deg, #050E1F 0%, #0C1D38 50%, #0D3060 100%) !important;
border: 1px solid #1A2E48;
border-radius: 16px;
padding: 28px 40px;
margin-bottom: 20px;
box-shadow: 0 8px 48px rgba(0,0,0,0.65), 0 0 0 1px rgba(0,196,212,0.07);
position: relative; overflow: hidden;
}
.fn-header::after {
content: '';
position: absolute; top: -80px; right: -80px;
width: 320px; height: 320px; border-radius: 50%;
background: radial-gradient(circle, rgba(0,196,212,0.07) 0%, transparent 70%);
pointer-events: none;
}
.fn-logo {
font-family: 'Syne', sans-serif !important;
font-size: 32px; font-weight: 800; letter-spacing: -1.5px;
background: linear-gradient(135deg, #ffffff 0%, #00C4D4 100%);
-webkit-background-clip: text; -webkit-text-fill-color: transparent;
background-clip: text; margin: 0 0 6px; display: block;
}
.fn-sub {
color: #5A7A9A !important;
-webkit-text-fill-color: #5A7A9A !important;
font-size: 13px; margin: 0 0 14px;
}
.fn-badges { display: flex; gap: 8px; flex-wrap: wrap; }
.fn-badge {
background: rgba(0,196,212,0.08);
border: 1px solid rgba(0,196,212,0.22);
color: #00C4D4 !important;
-webkit-text-fill-color: #00C4D4 !important;
font-family: 'IBM Plex Mono', monospace !important;
font-size: 11px; font-weight: 500; letter-spacing: 0.4px;
padding: 3px 12px; border-radius: 20px;
}
/* ββ LEFT COLUMN ββββββββββββββββββββββββββββββββββββββββββββββ */
.left-col {
background: #0D1B2E !important;
background-color: #0D1B2E !important;
border: 1px solid #1A2E48 !important;
border-radius: 14px !important;
padding: 20px !important;
}
.left-col > * { background: transparent !important; background-color: transparent !important; }
/* ββ STEP HEADERS βββββββββββββββββββββββββββββββββββββββββββββ */
.step-hdr { display: flex; align-items: center; gap: 10px; margin: 20px 0 10px; }
.step-num {
width: 26px; height: 26px; border-radius: 50%;
background: linear-gradient(135deg, #0D5EAF, #00A8BC) !important;
display: flex; align-items: center; justify-content: center;
font-family: 'Syne', sans-serif !important; font-size: 12px; font-weight: 700;
color: white !important; -webkit-text-fill-color: white !important;
flex-shrink: 0; box-shadow: 0 0 16px rgba(0,196,212,0.3);
min-width: 26px;
}
.step-lbl {
font-family: 'Syne', sans-serif !important;
font-size: 13px; font-weight: 600;
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
}
.step-opt { color: #3d5e80 !important; -webkit-text-fill-color: #3d5e80 !important; font-size: 11px; }
/* ββ LABEL TEXT (above inputs) ββββββββββββββββββββββββββββββββ */
.gradio-container label > span,
.gradio-container .block > label > span,
.gradio-container .block-label span,
.gradio-container .label-wrap span,
.svelte-1b6s6s {
font-size: 11px !important;
font-weight: 600 !important;
letter-spacing: 0.6px !important;
text-transform: uppercase !important;
color: #5A7A9A !important;
-webkit-text-fill-color: #5A7A9A !important;
}
/* ββ TEXTBOXES / INPUTS βββββββββββββββββββββββββββββββββββββββ */
.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container [data-testid="textbox"] textarea,
.gradio-container [data-testid="textbox"] input {
background: #111E33 !important;
background-color: #111E33 !important;
border: 1px solid #1A2E48 !important;
color: #C8D8F0 !important;
-webkit-text-fill-color: #C8D8F0 !important;
border-radius: 8px !important;
font-size: 13px !important;
transition: border-color 0.2s, box-shadow 0.2s !important;
}
.gradio-container input:focus,
.gradio-container textarea:focus {
border-color: #00A8BC !important;
box-shadow: 0 0 0 3px rgba(0,196,212,0.12) !important;
outline: none !important;
}
.gradio-container input::placeholder,
.gradio-container textarea::placeholder {
color: #2a4560 !important;
-webkit-text-fill-color: #2a4560 !important;
}
/* Status boxes */
.status-box textarea {
background: rgba(0,196,212,0.04) !important;
background-color: rgba(0,196,212,0.04) !important;
border: 1px solid rgba(0,196,212,0.15) !important;
color: #00C4D4 !important; -webkit-text-fill-color: #00C4D4 !important;
font-family: 'IBM Plex Mono', monospace !important;
font-size: 11.5px !important; line-height: 1.6 !important;
}
/* Patient preview */
.pat-box textarea {
background: #080F1C !important; background-color: #080F1C !important;
border: 1px solid #1A2E48 !important;
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
font-family: 'IBM Plex Mono', monospace !important;
font-size: 12px !important; line-height: 1.8 !important;
}
/* Clinical report */
.report-box textarea {
background: #080F1C !important; background-color: #080F1C !important;
border: 1px solid #1A2E48 !important;
color: #9BB5D0 !important; -webkit-text-fill-color: #9BB5D0 !important;
font-family: 'IBM Plex Mono', monospace !important;
font-size: 12px !important; line-height: 1.85 !important;
padding: 16px !important;
}
/* ββ DROPDOWN βββββββββββββββββββββββββββββββββββββββββββββββββ */
.gradio-container [data-testid="dropdown"],
.gradio-container .gr-dropdown {
background: #111E33 !important; background-color: #111E33 !important;
border: 1px solid #1A2E48 !important;
border-radius: 8px !important;
}
.gradio-container [data-testid="dropdown"] input,
.gradio-container [data-testid="dropdown"] span,
.gradio-container [data-testid="dropdown"] div {
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
background: transparent !important;
}
ul[role="listbox"] {
background: #111E33 !important; background-color: #111E33 !important;
border: 1px solid #1A2E48 !important;
border-radius: 8px !important;
box-shadow: 0 8px 32px rgba(0,0,0,0.55) !important;
}
li[role="option"] {
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
background: transparent !important;
}
li[role="option"]:hover { background: #1A2E48 !important; }
li[role="option"][aria-selected="true"] {
background: rgba(0,168,188,0.15) !important;
color: #00C4D4 !important; -webkit-text-fill-color: #00C4D4 !important;
}
/* ββ BUTTONS ββββββββββββββββββββββββββββββββββββββββββββββββββ */
.run-btn button {
background: linear-gradient(135deg, #0D5EAF 0%, #00A8BC 100%) !important;
border: none !important; border-radius: 10px !important;
font-family: 'Syne', sans-serif !important;
font-size: 15px !important; font-weight: 700 !important;
color: white !important; -webkit-text-fill-color: white !important;
padding: 16px !important;
box-shadow: 0 4px 24px rgba(0,168,188,0.35) !important;
transition: all 0.25s !important; width: 100% !important;
}
.run-btn button:hover {
box-shadow: 0 6px 32px rgba(0,168,188,0.55) !important;
transform: translateY(-2px) !important;
}
.pdf-btn button {
background: linear-gradient(135deg, #00B87C 0%, #0B8C7A 100%) !important;
border: none !important; border-radius: 8px !important;
font-family: 'Syne', sans-serif !important;
font-size: 13px !important; font-weight: 600 !important;
color: white !important; -webkit-text-fill-color: white !important;
box-shadow: 0 3px 16px rgba(0,184,124,0.3) !important;
transition: all 0.2s !important;
}
.pdf-btn button:hover { transform: translateY(-1px) !important; }
/* ββ ACCORDION ββββββββββββββββββββββββββββββββββββββββββββββββ */
.gradio-container details,
.gradio-container details > summary {
background: #0D1B2E !important;
background-color: #0D1B2E !important;
border: 1px solid #1A2E48 !important;
border-radius: 10px !important;
color: #C8D8F0 !important;
}
.gradio-container details > summary {
font-family: 'Syne', sans-serif !important;
font-size: 13px !important; font-weight: 600 !important;
padding: 12px 16px !important; cursor: pointer !important;
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
list-style: none;
}
.gradio-container details[open] > summary { border-radius: 10px 10px 0 0 !important; }
/* ββ FILE UPLOAD ββββββββββββββββββββββββββββββββββββββββββββββ */
.gradio-container [data-testid="upload-btn"],
.gradio-container .upload-container,
.gradio-container [class*="upload-zone"],
.gradio-container .gr-file {
background: #111E33 !important; background-color: #111E33 !important;
border: 1.5px dashed #1A2E48 !important;
border-radius: 10px !important; transition: all 0.2s !important;
}
.gradio-container [data-testid="upload-btn"]:hover,
.gradio-container .upload-container:hover {
border-color: #00A8BC !important;
background-color: rgba(0,168,188,0.04) !important;
}
.gradio-container [data-testid="upload-btn"] *,
.gradio-container .upload-container * {
color: #5A7A9A !important; -webkit-text-fill-color: #5A7A9A !important;
}
/* File list inside upload */
.gradio-container [class*="file-preview"],
.gradio-container [data-testid="file"] {
background: #080F1C !important; background-color: #080F1C !important;
border: 1px solid #1A2E48 !important; border-radius: 6px !important;
max-height: 150px !important; overflow-y: auto !important;
}
.gradio-container [class*="file-name"],
.gradio-container [class*="file"] span {
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
font-size: 11.5px !important;
}
/* ββ TABS βββββββββββββββββββββββββββββββββββββββββββββββββββββ */
.gradio-container .tab-nav,
.gradio-container [role="tablist"] {
background: #0A1628 !important; background-color: #0A1628 !important;
border-bottom: 1px solid #1A2E48 !important;
border-radius: 12px 12px 0 0 !important;
padding: 0 4px !important;
}
.gradio-container button[role="tab"] {
font-family: 'Syne', sans-serif !important;
font-size: 13px !important; font-weight: 600 !important;
color: #5A7A9A !important; -webkit-text-fill-color: #5A7A9A !important;
padding: 12px 20px !important;
border-bottom: 2px solid transparent !important;
background: transparent !important; transition: all 0.2s !important;
}
.gradio-container button[role="tab"][aria-selected="true"] {
color: #00C4D4 !important; -webkit-text-fill-color: #00C4D4 !important;
border-bottom: 2px solid #00C4D4 !important;
}
.gradio-container button[role="tab"]:hover {
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
}
.gradio-container [role="tabpanel"] {
background: #0A1628 !important; background-color: #0A1628 !important;
border: 1px solid #1A2E48 !important; border-top: none !important;
border-radius: 0 0 12px 12px !important; padding: 16px !important;
}
/* ββ PLOT CONTAINERS ββββββββββββββββββββββββββββββββββββββββββ */
.gradio-container .gr-plot,
.gradio-container [data-testid="plot"],
.gradio-container [class*="plot"] {
background: #0D1B2E !important; background-color: #0D1B2E !important;
border: 1px solid #1A2E48 !important;
border-radius: 10px !important; overflow: hidden !important;
}
/* ββ SLIDER βββββββββββββββββββββββββββββββββββββββββββββββββββ */
input[type="range"] { accent-color: #00C4D4 !important; }
.gradio-container [data-testid="slider"],
.gradio-container .gr-slider {
background: transparent !important;
}
/* ββ SCROLLBAR ββββββββββββββββββββββββββββββββββββββββββββββββ */
::-webkit-scrollbar { width: 4px; height: 4px; }
::-webkit-scrollbar-track { background: #080F1C; }
::-webkit-scrollbar-thumb { background: #1A2E48; border-radius: 2px; }
::-webkit-scrollbar-thumb:hover { background: #2A3E58; }
/* ββ REPORT TITLE βββββββββββββββββββββββββββββββββββββββββββββ */
.report-title-row { display: flex; align-items: center; justify-content: space-between; margin-bottom: 8px; }
.report-title {
font-family: 'Syne', sans-serif;
font-size: 14px; font-weight: 700;
color: #C8D8F0 !important; -webkit-text-fill-color: #C8D8F0 !important;
}
/* ββ FOOTER HTML ββββββββββββββββββββββββββββββββββββββββββββββ */
.fn-footer {
text-align: center; margin-top: 20px; padding: 14px;
border-top: 1px solid #1A2E48;
color: #2a4560 !important; -webkit-text-fill-color: #2a4560 !important;
font-family: 'IBM Plex Mono', monospace !important; font-size: 11px;
}
/* Hide Gradio branding */
footer.svelte-1ax1toq, .built-with, .show-api { display: none !important; }
/* ββ DICOM hint (inside accordion) ββββββββββββββββββββββββββββ */
.dicom-hint p, .dicom-hint {
color: #3d5e80 !important; -webkit-text-fill-color: #3d5e80 !important;
font-size: 11.5px !important;
}
.dicom-hint code {
color: #00C4D4 !important; -webkit-text-fill-color: #00C4D4 !important;
background: rgba(0,196,212,0.08) !important;
padding: 1px 5px; border-radius: 3px;
}
"""
# ββ APP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Blocks(title="FibrosisNet-V4", theme=theme, css=CSS) as demo:
gr.HTML("""
<div class="fn-header">
<span class="fn-logo">π« FibrosisNet-V4</span>
<p class="fn-sub">Pulmonary Fibrosis Progression Prediction Β· Multi-Backbone 2.5D Deep Learning</p>
<div class="fn-badges">
<span class="fn-badge">Swin-Tiny 2.5D</span>
<span class="fn-badge">SE Attention Pooling</span>
<span class="fn-badge">Cross-Attention Fusion</span>
<span class="fn-badge">Calibrated Uncertainty</span>
<span class="fn-badge">OOF β6.6629 β</span>
<span class="fn-badge">NIT Calicut Β· May 2026</span>
</div>
</div>
""")
with gr.Row(equal_height=False):
# ββ LEFT PANEL ββ
with gr.Column(scale=1, min_width=360, elem_classes="left-col"):
gr.HTML('<div class="step-hdr"><div class="step-num">1</div><div class="step-lbl">Upload OSIC Test CSV</div></div>')
csv_file = gr.File(label="test.csv Β· Patient Β· Weeks Β· FVC Β· Percent Β· Age Β· Sex Β· SmokingStatus",
file_types=[".csv"])
csv_status = gr.Textbox(label="CSV Status", lines=2, interactive=False,
elem_classes="status-box")
gr.HTML('<div class="step-hdr"><div class="step-num">2</div><div class="step-lbl">Select Patient</div></div>')
patient_dd = gr.Dropdown(label="Patient ID Β· auto-populated from CSV",
choices=[], value=None, allow_custom_value=True)
patient_info = gr.Textbox(label="Patient Preview", lines=10,
interactive=False, elem_classes="pat-box")
gr.HTML('<div class="step-hdr"><div class="step-num">3</div><div class="step-lbl">Run Prediction</div></div>')
predict_btn = gr.Button("π¬ Run FibrosisNet-V4 Prediction",
elem_classes="run-btn", size="lg")
gr.HTML('<div class="step-hdr"><div class="step-num">4</div>'
'<div class="step-lbl">Upload CT DICOM</div></div>')
with gr.Accordion("π©» Open DICOM Upload Panel", open=False):
gr.HTML('<p class="dicom-hint">'
'Upload <code>.dcm</code> slices for one patient\'s CT. '
'Patient ID is auto-read from DICOM tags. '
'File list is scrollable β the Predict button stays visible.</p>')
dicom_files = gr.File(label="DICOM slices (.dcm)",
file_count="multiple",
file_types=[".dcm",".DCM"],
elem_classes="dicom-up")
dicom_status = gr.Textbox(label="DICOM Status", lines=2,
interactive=False, elem_classes="status-box")
# ββ RIGHT PANEL ββ
with gr.Column(scale=2):
with gr.Tabs():
with gr.Tab("π FVC Decline Graph"):
fvc_plot = gr.Plot()
with gr.Tab("π« CT Lung Viewer"):
ct_view = gr.Plot()
gr.HTML('<p style="color:#3d5e80;font-size:11px;margin:10px 0 4px;'
'font-family:IBM Plex Mono,monospace;letter-spacing:0.2px">'
'ββ Slice Explorer: drag to browse axial slices ββ</p>')
slice_slider = gr.Slider(0, 300, value=0, step=1, label="Axial Slice Index")
slice_view = gr.Plot()
slice_slider.change(fn=update_slice, inputs=slice_slider, outputs=slice_view)
with gr.Tab("π Clinical Report"):
with gr.Row():
gr.HTML('<div class="report-title">Clinical Summary Report</div>')
pdf_btn = gr.Button("β¬ Download PDF Report",
elem_classes="pdf-btn", size="sm", visible=False)
report_box = gr.Textbox(label="", lines=36, max_lines=65,
interactive=False, elem_classes="report-box")
pdf_output = gr.File(label="PDF Ready", visible=False)
gr.HTML("""
<div class="fn-footer">
FibrosisNet-V4 Β· Balaji R Β· NIT Calicut Β· May 2026
Β· OSIC Pulmonary Fibrosis Progression
Β· β Research prototype β not for clinical use without physician oversight
</div>
""")
# Wiring
csv_file.upload(fn=on_csv_upload, inputs=csv_file, outputs=[patient_dd, csv_status])
dicom_files.upload(fn=on_dicom_upload, inputs=dicom_files, outputs=[patient_dd, dicom_status])
patient_dd.change(fn=on_patient_select, inputs=patient_dd, outputs=patient_info)
predict_btn.click(fn=run_all, inputs=[patient_dd, dicom_files],
outputs=[fvc_plot, ct_view, report_box, pdf_btn, pdf_output])
pdf_btn.click(fn=on_download_pdf, inputs=[], outputs=pdf_output)
pdf_btn.click(fn=lambda: gr.update(visible=True), inputs=[], outputs=pdf_output)
demo.launch(server_name="0.0.0.0", server_port=7860) |