Upload folder using huggingface_hub
Browse filesFiles changed (6)
- app.py+121-39
- app_with_llm.pyAdded+363
- checkpoints/aal_nyu.ckptAdded+3
- checkpoints/aal_ucla.ckptAdded+3
- checkpoints/aal_um.ckptAdded+3
- checkpoints/aal_usm.ckptAdded+3
16 unmodified lines17181920212223242526272829303132333425 unmodified lines60616263646566676869707172737475767778798018 unmodified lines991001011021031041051 unmodified line10710810911011111211311411511611711811912012112212312412 unmodified lines13713813914014114214314428 unmodified lines17317417517617717817913 unmodified lines19319419519619719819920020148 unmodified lines25025125225325425525610 unmodified lines2672682692702712729 unmodified lines2822832842852862872882892902912922932945 unmodified lines30030130230330430530691 unmodified lines398399400401402403404171 unmodified lines57657757857958058158254 unmodified lines63763863964064164264371 unmodified lines71571671771871972072116 unmodified lines_MAX_WINDOWS = 30_FC_THRESHOLD = 0.2# CC200 atlas (Craddock 2012) → approximate Yeo 7-network parcellation_NET_NAMES = ["DMN", "Salience", "Frontoparietal", "Sensorimotor", "Visual", "Dorsal Attn", "Subcortical"]_NET_BOUNDS = [0, 38, 69, 99, 137, 165, 180, 200]_NET_COLORS = ["#e63946", "#f4a261", "#457b9d", "#2dc653", "#a8dadc", "#8b5cf6", "#6b7280"]_CKPTS = {"NYU": Path("checkpoints/nyu.ckpt"),"USM": Path("checkpoints/usm.ckpt"),"UCLA": Path("checkpoints/ucla.ckpt"),"UM": Path("checkpoints/um.ckpt"),}# ── preprocessing ──────────────────────────────────────────────────────────def _zscore(bold):25 unmodified lines# ── model loading ──────────────────────────────────────────────────────────_models = Nonedef get_models():global _modelsif _models is not None:return _modelsfrom brain_gcn.tasks import ClassificationTask_models = []for site, ckpt in _CKPTS.items():if not ckpt.exists():continuetask = ClassificationTask.load_from_checkpoint(str(ckpt), map_location="cpu", strict=False)task.eval()_models.append((site, task))return _models# ── gradient saliency ──────────────────────────────────────────────────────18 unmodified lines[ 14, 4, 4], # Subcortical (thalamus)], dtype=np.float32)def _saliency_figure(sal, p_mean):import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as plt1 unmodified linefrom mpl_toolkits.mplot3d.art3d import Line3DCollectionfrom PIL import Imagen_nets = len(_NET_NAMES)# Aggregate 200×200 saliency → 7×7 network-level matrixnet_sal = np.zeros((n_nets, n_nets))for i, (s1, e1) in enumerate(zip(_NET_BOUNDS[:-1], _NET_BOUNDS[1:])):for j, (s2, e2) in enumerate(zip(_NET_BOUNDS[:-1], _NET_BOUNDS[1:])):net_sal[i, j] = sal[s1:e1, s2:e2].mean()# Network importance: mean outgoing + incoming saliency per networknet_imp = np.array([sal[s:e, :].mean() + sal[:, s:e].mean()for s, e in zip(_NET_BOUNDS[:-1], _NET_BOUNDS[1:])])fig = plt.figure(figsize=(18, 5.5))12 unmodified linesax.set_xticks(range(n_nets))ax.set_yticks(range(n_nets))ax.set_xticklabels(_NET_NAMES, rotation=40, ha="right", fontsize=9, color="#ccc")ax.set_yticklabels(_NET_NAMES, fontsize=9, color="#ccc")ax.tick_params(colors="#555", length=0)for sp in ax.spines.values():sp.set_color("#222")28 unmodified lines# Callout labels for top-3 cross-network edgesfor rank, (score, i, j) in enumerate(top3_edges):label = f"#{rank+1} {_NET_NAMES[i]}↔{_NET_NAMES[j]}"ax.annotate(label,xy=(j, i), xytext=(n_nets - 0.3, rank * 0.85 - 0.3),fontsize=6, color="#fb923c", fontweight="600",13 unmodified linesorder = net_imp.argsort()[::-1]bars = ax2.barh(range(n_nets), net_imp[order],color=[_NET_COLORS[i] for i in order], alpha=0.88, edgecolor="none", height=0.65)ax2.set_yticks(range(n_nets))ax2.set_yticklabels([_NET_NAMES[i] for i in order], fontsize=9.5, color="#ddd")ax2.set_xlabel("Mean gradient magnitude", color="#555", fontsize=9)ax2.set_title("Network Importance for This Prediction", color="#bbb", fontsize=11, pad=14, fontweight="bold")ax2.invert_yaxis()48 unmodified linesax3.set_box_aspect([1.2, 1.4, 1.0])fig.suptitle(f"Gradient Saliency · p(ASD) = {p_mean:.3f} · {len(_models)}-model LOSO ensemble · CC200 → Yeo-7 networks",color="#444", fontsize=8.5, y=1.02,)plt.tight_layout()10 unmodified linesreturn "", "", "", Nonepath = Path(file_path)try:if path.suffix == ".npz":d = np.load(path, allow_pickle=True)9 unmodified linesadj_t = torch.FloatTensor(adj).unsqueeze(0)else:bold = np.loadtxt(path, dtype=np.float32)if bold.ndim != 2 or bold.shape[1] != 200:return f"Error: expected (T×200), got {bold.shape}", "", "", Nonebw_t, adj_t = preprocess(bold)except Exception as e:return f"Error loading file: {e}", "", "", Nonemodels = get_models()per_model = []with torch.no_grad():for site, task in models:5 unmodified linesconf = max(p_mean, 1 - p_mean) * 100try:sal_img = _saliency_figure(_compute_saliency(bw_t, adj_t, models), p_mean)except Exception:sal_img = None91 unmodified lines<div><div style="color:#8b95a7;font-size:0.68rem;text-transform:uppercase;letter-spacing:1px;margin-bottom:3px">ICD-10 Classification</div><div style="color:#cbd5e1;font-size:0.84rem;line-height:1.4">{icd}</div></div><div><div style="color:#8b95a7;font-size:0.68rem;text-transform:uppercase;letter-spacing:1px;margin-bottom:3px">Ensemble Confidence</div><div style="color:#cbd5e1;font-size:0.84rem">{conf:.1f}% · p(ASD) = {p_mean:.3f} · {len(_models)}-model LOSO</div></div></div><div style="color:#8b95a7;font-size:0.68rem;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:4px;font-weight:500">Impression</div>171 unmodified lines<div style="background:#161922;border:1px solid #252a35;border-radius:8px;padding:14px 16px;min-width:130px;text-align:center;flex-shrink:0"><div style="color:#8b95a7;font-size:0.65rem;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px">Input</div><div style="color:#f4f4f5;font-weight:600;font-size:0.88rem">fMRI BOLD</div><div style="color:#5e6675;font-size:0.74rem;margin-top:3px">T × 200 ROIs</div></div><div style="color:#252a35;font-size:1.4rem;padding:0 6px;flex-shrink:0">→</div>54 unmodified lines<div style="background:#161922;border:1px solid #252a35;border-radius:8px;overflow:hidden"><table style="width:100%;border-collapse:collapse;font-size:0.85rem"><tr><td style="padding:10px 16px;color:#8b95a7;width:150px;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Dataset</td><td style="padding:10px 16px;color:#cbd5e1">ABIDE I · 1,102 subjects · 17 acquisition sites</td></tr><tr style="border-top:1px solid #252a35"><td style="padding:10px 16px;color:#8b95a7;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Parcellation</td><td style="padding:10px 16px;color:#cbd5e1">CC200 (Craddock 2012) · 200 functional ROIs</td></tr><tr style="border-top:1px solid #252a35"><td style="padding:10px 16px;color:#8b95a7;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Model</td><td style="padding:10px 16px;color:#cbd5e1">AdversarialBrainModeNetwork · K=16 modes · hidden_dim=64</td></tr><tr style="border-top:1px solid #252a35"><td style="padding:10px 16px;color:#8b95a7;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Validation</td><td style="padding:10px 16px;color:#cbd5e1">LOSO AUC = <span style="color:#ef4444;font-weight:600">0.7872</span> · 529 held-out subjects · 0 confident misclassifications</td></tr><tr style="border-top:1px solid #252a35"><td style="padding:10px 16px;color:#8b95a7;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Interpretability</td><td style="padding:10px 16px;color:#cbd5e1">Real-time gradient saliency · 7-network aggregation · 3D brain surface</td></tr>71 unmodified lineswith gr.Tabs():with gr.Tab("Analysis"):file_input = gr.File(label="Upload CC200 fMRI (.1D or .npz)", type="filepath")gr.HTML("<div style='color:#8b95a7;font-size:0.7rem;text-transform:uppercase;letter-spacing:1.2px;margin:14px 0 8px;font-weight:500'>Or try a real ABIDE subject from a held-out site</div>")with gr.Row():btn_asd = gr.Button("ASD · Stanford 0051160", size="sm")16 unmodified lines171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777825 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512618 unmodified lines1451461471481491501511 unmodified line15315415515615715815916016116216316416516616716816917017117217312 unmodified lines18618718818919019119219328 unmodified lines22222322422522622722813 unmodified lines24224324424524624724824925048 unmodified lines29930030130230330430510 unmodified lines3163173183193203213229 unmodified lines3323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703715 unmodified lines37737837938038138238338438538638738891 unmodified lines480481482483484485486171 unmodified lines65865966066166266366454 unmodified lines71972072172272372472571 unmodified lines79779879980080180280316 unmodified lines_MAX_WINDOWS = 30_FC_THRESHOLD = 0.2# ── Atlas configurations ────────────────────────────────────────────────────# CC200 → Yeo 7-network parcellation (approximate ROI ordering)_ATLAS_CFG = {"cc200": {"n_rois": 200,"label": "CC200","net_names": ["DMN", "Salience", "Frontoparietal", "Sensorimotor", "Visual", "Dorsal Attn", "Subcortical"],"net_bounds": [0, 38, 69, 99, 137, 165, 180, 200],"net_colors": ["#e63946", "#f4a261", "#457b9d", "#2dc653", "#a8dadc", "#8b5cf6", "#6b7280"],"ckpts": {"NYU": Path("checkpoints/nyu.ckpt"),"USM": Path("checkpoints/usm.ckpt"),"UCLA": Path("checkpoints/ucla.ckpt"),"UM": Path("checkpoints/um.ckpt"),},},"aal": {"n_rois": 116,"label": "AAL-116",# Approximate Yeo-7 parcellation for AAL-116 anatomical ordering:# Frontal/FPN (1-28), Sensorimotor (29-40), DMN parietal (41-60),# Temporal/DMN (61-76), Subcortical (77-90), Occipital/Visual (91-116)"net_names": ["Frontoparietal", "Sensorimotor", "Dorsal Attn", "DMN", "Salience", "Subcortical", "Visual"],"net_bounds": [0, 20, 34, 50, 68, 80, 92, 116],"net_colors": ["#457b9d", "#2dc653", "#8b5cf6", "#e63946", "#f4a261", "#6b7280", "#a8dadc"],"ckpts": {"NYU": Path("checkpoints/aal_nyu.ckpt"),"USM": Path("checkpoints/aal_usm.ckpt"),"UCLA": Path("checkpoints/aal_ucla.ckpt"),"UM": Path("checkpoints/aal_um.ckpt"),},},"ho": {"n_rois": 111,"label": "Harvard-Oxford","net_names": ["Frontoparietal", "Sensorimotor", "DMN", "Salience", "Subcortical", "Visual", "Temporal"],"net_bounds": [0, 18, 30, 48, 68, 80, 96, 111],"net_colors": ["#457b9d", "#2dc653", "#e63946", "#f4a261", "#6b7280", "#a8dadc", "#8b5cf6"],"ckpts": {"NYU": Path("checkpoints/ho_nyu.ckpt"),"USM": Path("checkpoints/ho_usm.ckpt"),"UCLA": Path("checkpoints/ho_ucla.ckpt"),"UM": Path("checkpoints/ho_um.ckpt"),},},}# Resolve active atlas config by ROI count_ROI_TO_ATLAS = {cfg["n_rois"]: key for key, cfg in _ATLAS_CFG.items()}# Legacy aliases kept for backward compat_NET_NAMES = _ATLAS_CFG["cc200"]["net_names"]_NET_BOUNDS = _ATLAS_CFG["cc200"]["net_bounds"]_NET_COLORS = _ATLAS_CFG["cc200"]["net_colors"]_CKPTS = _ATLAS_CFG["cc200"]["ckpts"]# ── preprocessing ──────────────────────────────────────────────────────────def _zscore(bold):25 unmodified lines# ── model loading ──────────────────────────────────────────────────────────_model_cache: dict[str, list] = {}def get_models(atlas: str = "cc200"):global _model_cacheif atlas in _model_cache:return _model_cache[atlas]from brain_gcn.tasks import ClassificationTaskcfg = _ATLAS_CFG.get(atlas, _ATLAS_CFG["cc200"])models = []for site, ckpt in cfg["ckpts"].items():if not ckpt.exists():continuetask = ClassificationTask.load_from_checkpoint(str(ckpt), map_location="cpu", strict=False)task.eval()models.append((site, task))_model_cache[atlas] = modelsreturn models# ── gradient saliency ──────────────────────────────────────────────────────18 unmodified lines[ 14, 4, 4], # Subcortical (thalamus)], dtype=np.float32)def _saliency_figure(sal, p_mean, net_names=None, net_bounds=None, net_colors=None):import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as plt1 unmodified linefrom mpl_toolkits.mplot3d.art3d import Line3DCollectionfrom PIL import Image_nn = net_names if net_names is not None else _NET_NAMES_nb = net_bounds if net_bounds is not None else _NET_BOUNDS_nc = net_colors if net_colors is not None else _NET_COLORSn_nets = len(_nn)# Aggregate N×N saliency → 7×7 network-level matrixnet_sal = np.zeros((n_nets, n_nets))for i, (s1, e1) in enumerate(zip(_nb[:-1], _nb[1:])):for j, (s2, e2) in enumerate(zip(_nb[:-1], _nb[1:])):net_sal[i, j] = sal[s1:e1, s2:e2].mean()# Network importance: mean outgoing + incoming saliency per networknet_imp = np.array([sal[s:e, :].mean() + sal[:, s:e].mean()for s, e in zip(_nb[:-1], _nb[1:])])fig = plt.figure(figsize=(18, 5.5))12 unmodified linesax.set_xticks(range(n_nets))ax.set_yticks(range(n_nets))ax.set_xticklabels(_nn, rotation=40, ha="right", fontsize=9, color="#ccc")ax.set_yticklabels(_nn, fontsize=9, color="#ccc")ax.tick_params(colors="#555", length=0)for sp in ax.spines.values():sp.set_color("#222")28 unmodified lines# Callout labels for top-3 cross-network edgesfor rank, (score, i, j) in enumerate(top3_edges):label = f"#{rank+1} {_nn[i]}↔{_nn[j]}"ax.annotate(label,xy=(j, i), xytext=(n_nets - 0.3, rank * 0.85 - 0.3),fontsize=6, color="#fb923c", fontweight="600",13 unmodified linesorder = net_imp.argsort()[::-1]bars = ax2.barh(range(n_nets), net_imp[order],color=[_nc[i] for i in order], alpha=0.88, edgecolor="none", height=0.65)ax2.set_yticks(range(n_nets))ax2.set_yticklabels([_nn[i] for i in order], fontsize=9.5, color="#ddd")ax2.set_xlabel("Mean gradient magnitude", color="#555", fontsize=9)ax2.set_title("Network Importance for This Prediction", color="#bbb", fontsize=11, pad=14, fontweight="bold")ax2.invert_yaxis()48 unmodified linesax3.set_box_aspect([1.2, 1.4, 1.0])fig.suptitle(f"Gradient Saliency · p(ASD) = {p_mean:.3f} · {len(models)}-model LOSO ensemble · CC200 → Yeo-7 networks",color="#444", fontsize=8.5, y=1.02,)plt.tight_layout()10 unmodified linesreturn "", "", "", Nonepath = Path(file_path)atlas_key = "cc200" # default; overridden below for .1D filestry:if path.suffix == ".npz":d = np.load(path, allow_pickle=True)9 unmodified linesadj_t = torch.FloatTensor(adj).unsqueeze(0)else:bold = np.loadtxt(path, dtype=np.float32)if bold.ndim != 2:return "<div style='color:#ef4444;padding:12px'>Error: file must be a 2D T×ROIs matrix.</div>", "", "", Nonen_rois = bold.shape[1]atlas_key = _ROI_TO_ATLAS.get(n_rois)if atlas_key is None:supported = ", ".join(f"{cfg['label']} ({cfg['n_rois']} ROIs)" for cfg in _ATLAS_CFG.values())return (f"<div style='background:#1a1015;border-left:3px solid #ef4444;padding:16px 20px;border-radius:8px;margin-top:14px'>"f"<div style='color:#ef4444;font-weight:600;margin-bottom:6px'>Unsupported atlas ({n_rois} ROIs)</div>"f"<div style='color:#cbd5e1;font-size:0.88rem;line-height:1.6'>"f"Supported: {supported}.<br>"f"Download from FCP-INDI S3: <code style='color:#fb923c'>rois_cc200/</code>, <code style='color:#fb923c'>rois_aal/</code>, or <code style='color:#fb923c'>rois_ho/</code>"f"</div></div>"), "", "", Nonebw_t, adj_t = preprocess(bold)except Exception as e:return f"Error loading file: {e}", "", "", Noneatlas_cfg = _ATLAS_CFG[atlas_key]models = get_models(atlas_key)if not models:atlas_label = atlas_cfg["label"]return (f"<div style='background:#1a1015;border-left:3px solid #f59e0b;padding:16px 20px;border-radius:8px;margin-top:14px'>"f"<div style='color:#f59e0b;font-weight:600;margin-bottom:6px'>{atlas_label} models not yet available</div>"f"<div style='color:#cbd5e1;font-size:0.88rem;line-height:1.6'>"f"Training is in progress. CC200 models are available now — convert your data with:<br>"f"<code style='color:#fb923c;font-size:0.82rem'>aws s3 cp s3://fcp-indi/.../rois_cc200/ . --no-sign-request --recursive</code>"f"</div></div>"), "", "", Noneper_model = []with torch.no_grad():for site, task in models:5 unmodified linesconf = max(p_mean, 1 - p_mean) * 100try:sal_img = _saliency_figure(_compute_saliency(bw_t, adj_t, models), p_mean,net_names=atlas_cfg["net_names"],net_bounds=atlas_cfg["net_bounds"],net_colors=atlas_cfg["net_colors"],)except Exception:sal_img = None91 unmodified lines<div><div style="color:#8b95a7;font-size:0.68rem;text-transform:uppercase;letter-spacing:1px;margin-bottom:3px">ICD-10 Classification</div><div style="color:#cbd5e1;font-size:0.84rem;line-height:1.4">{icd}</div></div><div><div style="color:#8b95a7;font-size:0.68rem;text-transform:uppercase;letter-spacing:1px;margin-bottom:3px">Ensemble Confidence</div><div style="color:#cbd5e1;font-size:0.84rem">{conf:.1f}% · p(ASD) = {p_mean:.3f} · {len(models)}-model LOSO</div></div></div><div style="color:#8b95a7;font-size:0.68rem;text-transform:uppercase;letter-spacing:1.5px;margin-bottom:4px;font-weight:500">Impression</div>171 unmodified lines<div style="background:#161922;border:1px solid #252a35;border-radius:8px;padding:14px 16px;min-width:130px;text-align:center;flex-shrink:0"><div style="color:#8b95a7;font-size:0.65rem;text-transform:uppercase;letter-spacing:1px;margin-bottom:6px">Input</div><div style="color:#f4f4f5;font-weight:600;font-size:0.88rem">fMRI BOLD</div><div style="color:#5e6675;font-size:0.74rem;margin-top:3px">T × ROIs (CC200/AAL/HO)</div></div><div style="color:#252a35;font-size:1.4rem;padding:0 6px;flex-shrink:0">→</div>54 unmodified lines<div style="background:#161922;border:1px solid #252a35;border-radius:8px;overflow:hidden"><table style="width:100%;border-collapse:collapse;font-size:0.85rem"><tr><td style="padding:10px 16px;color:#8b95a7;width:150px;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Dataset</td><td style="padding:10px 16px;color:#cbd5e1">ABIDE I · 1,102 subjects · 17 acquisition sites</td></tr><tr style="border-top:1px solid #252a35"><td style="padding:10px 16px;color:#8b95a7;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Parcellation</td><td style="padding:10px 16px;color:#cbd5e1">CC200 (200 ROIs) · AAL-116 (116 ROIs) · Harvard-Oxford (111 ROIs)</td></tr><tr style="border-top:1px solid #252a35"><td style="padding:10px 16px;color:#8b95a7;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Model</td><td style="padding:10px 16px;color:#cbd5e1">AdversarialBrainModeNetwork · K=16 modes · hidden_dim=64</td></tr><tr style="border-top:1px solid #252a35"><td style="padding:10px 16px;color:#8b95a7;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Validation</td><td style="padding:10px 16px;color:#cbd5e1">LOSO AUC = <span style="color:#ef4444;font-weight:600">0.7872</span> · 529 held-out subjects · 0 confident misclassifications</td></tr><tr style="border-top:1px solid #252a35"><td style="padding:10px 16px;color:#8b95a7;font-size:0.76rem;text-transform:uppercase;letter-spacing:0.5px">Interpretability</td><td style="padding:10px 16px;color:#cbd5e1">Real-time gradient saliency · 7-network aggregation · 3D brain surface</td></tr>71 unmodified lineswith gr.Tabs():with gr.Tab("Analysis"):file_input = gr.File(label="Upload fMRI time series — CC200 (200), AAL (116), or Harvard-Oxford (111) ROIs · .1D or .npz", type="filepath")gr.HTML("<div style='color:#8b95a7;font-size:0.7rem;text-transform:uppercase;letter-spacing:1.2px;margin:14px 0 8px;font-weight:500'>Or try a real ABIDE subject from a held-out site</div>")with gr.Row():btn_asd = gr.Button("ASD · Stanford 0051160", size="sm")
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363"""BrainConnect-ASD — Scanner-site-invariant ASD detection from fMRI.Full pipeline: Adversarial GCN + Qwen2.5-7B fine-tuned on AMD MI300X."""from __future__ import annotations
import iofrom pathlib import Path
import numpy as npimport torchimport gradio as gr
_WINDOW_LEN = 50_STEP = 3_MAX_WINDOWS = 30_FC_THRESHOLD = 0.2
_CKPTS = { "NYU": Path("checkpoints/nyu.ckpt"), "USM": Path("checkpoints/usm.ckpt"), "UCLA": Path("checkpoints/ucla.ckpt"), "UM": Path("checkpoints/um.ckpt"),}
_LLM_MODEL = "Yatsuiii/asd-interpreter-lora"
SYSTEM_PROMPT = ( "You are a clinical AI assistant specializing in functional MRI brain " "connectivity analysis for autism spectrum disorder (ASD) diagnosis support. " "You interpret outputs from a validated graph neural network (GCN) trained on " "the ABIDE I dataset and provide structured clinical summaries for neurologists " "and psychiatrists. Your reports are informative and evidence-based but always " "clarify that findings are AI-assisted and should be integrated with full " "clinical assessment. You do not make a diagnosis.")
# ── preprocessing ──────────────────────────────────────────────────────────
def _zscore(bold): mean = bold.mean(0, keepdims=True) std = bold.std(0, keepdims=True) std[std < 1e-8] = 1.0 return ((bold - mean) / std).astype(np.float32)
def _fc(bold): fc = np.corrcoef(bold.T).astype(np.float32) np.nan_to_num(fc, copy=False) return fc
def _windows(bold): T, N = bold.shape starts = list(range(0, T - _WINDOW_LEN + 1, _STEP)) w = np.stack([bold[s:s+_WINDOW_LEN].std(0) for s in starts]).astype(np.float32) if len(w) >= _MAX_WINDOWS: return w[:_MAX_WINDOWS] return np.concatenate([w, np.repeat(w[-1:], _MAX_WINDOWS - len(w), 0)])
def preprocess(bold): bold = _zscore(bold) fc = _fc(bold) fc = np.arctanh(np.clip(fc, -0.9999, 0.9999)) adj = np.where(np.abs(fc) >= _FC_THRESHOLD, fc, 0.0).astype(np.float32) bw = _windows(bold) return torch.FloatTensor(bw).unsqueeze(0), torch.FloatTensor(adj).unsqueeze(0)
# ── GCN model loading ──────────────────────────────────────────────────────
_models: list | None = None
def get_models(): global _models if _models is not None: return _models from brain_gcn.tasks import ClassificationTask _models = [] for site, ckpt in _CKPTS.items(): if not ckpt.exists(): continue task = ClassificationTask.load_from_checkpoint(str(ckpt), map_location="cpu", strict=False) task.eval() _models.append((site, task)) return _models
# ── LLM loading ────────────────────────────────────────────────────────────
_llm = None
def get_llm(): global _llm if _llm is not None: return _llm from transformers import AutoModelForCausalLM, AutoTokenizer print(f"Loading LLM: {_LLM_MODEL}") tok = AutoTokenizer.from_pretrained(_LLM_MODEL) tok.pad_token = tok.eos_token mdl = AutoModelForCausalLM.from_pretrained( _LLM_MODEL, torch_dtype=torch.bfloat16, device_map="auto", ) mdl.eval() _llm = (mdl, tok) return _llm
def _llm_report(p_mean: float, per_model: list) -> str: consensus = sum(1 for _, p in per_model if p > 0.5) per_model_str = "\n".join( f" {s}-blind: {'ASD' if v > 0.5 else 'TC'} (p={v:.3f})" for s, v in per_model ) conf_label = ( "HIGH" if p_mean >= 0.75 else "MODERATE" if p_mean >= 0.6 else "LOW / UNCERTAIN" if p_mean >= 0.4 else "MODERATE (TC)" if p_mean >= 0.25 else "HIGH (TC)" ) user_msg = ( f"Brain Connectivity GCN Analysis Report\n" f"{'='*40}\n" f"p(ASD) : {p_mean:.3f}\n" f"Confidence Level : {conf_label}\n" f"Model Consensus : {consensus}/4 site-blind models predict ASD\n\n" f"Per-Model Breakdown (LOSO ensemble):\n{per_model_str}\n\n" f"Please provide a structured clinical interpretation of these findings." ) try: mdl, tok = get_llm() messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": user_msg}, ] text = tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) inputs = tok(text, return_tensors="pt").to(next(mdl.parameters()).device) with torch.no_grad(): out = mdl.generate( **inputs, max_new_tokens=512, temperature=0.3, do_sample=True, pad_token_id=tok.eos_token_id, ) generated = out[0][inputs["input_ids"].shape[1]:] return tok.decode(generated, skip_special_tokens=True).strip() except Exception as e: return f"LLM unavailable: {e}"
# ── gradient saliency ──────────────────────────────────────────────────────
def _compute_saliency(bw_t: torch.Tensor, adj_t: torch.Tensor, models) -> np.ndarray: maps = [] for _, task in models: adj = adj_t.clone().requires_grad_(True) logits = task.model(bw_t, adj) p = torch.softmax(logits, -1)[0, 1] p.backward() maps.append(adj.grad[0].abs().detach().numpy()) sal = np.mean(maps, axis=0) sal = (sal + sal.T) / 2 return sal
def _saliency_figure(sal: np.ndarray, p_mean: float): import matplotlib matplotlib.use("Agg") import matplotlib.pyplot as plt from PIL import Image
thresh = np.percentile(sal, 95) sal_top = np.where(sal >= thresh, sal, 0.0) roi_imp = sal.sum(1) top20 = roi_imp.argsort()[-20:][::-1] verdict_color = "#e63946" if p_mean > 0.6 else "#2dc653" if p_mean < 0.4 else "#f4a261"
fig, axes = plt.subplots(1, 2, figsize=(14, 5.5)) fig.patch.set_facecolor("#0d0d0d")
ax = axes[0] ax.set_facecolor("#111") im = ax.imshow(sal_top, cmap="inferno", aspect="auto", interpolation="nearest") ax.set_title("FC Edge Saliency (top 5% connections)", color="#ccc", fontsize=11, pad=10) ax.set_xlabel("ROI index", color="#777", fontsize=9) ax.set_ylabel("ROI index", color="#777", fontsize=9) ax.tick_params(colors="#555", labelsize=8) cb = plt.colorbar(im, ax=ax, fraction=0.046, pad=0.04) cb.ax.yaxis.set_tick_params(color="#555", labelsize=7) plt.setp(cb.ax.yaxis.get_ticklabels(), color="#666") for spine in ax.spines.values(): spine.set_color("#333")
ax2 = axes[1] ax2.set_facecolor("#111") ax2.barh(range(20), roi_imp[top20], color=verdict_color, alpha=0.75, edgecolor="none") ax2.set_yticks(range(20)) ax2.set_yticklabels([f"ROI {i:03d}" for i in top20], fontsize=8, color="#ccc") ax2.set_xlabel("Cumulative gradient magnitude", color="#777", fontsize=9) ax2.set_title("Top-20 ROIs by Prediction Influence", color="#ccc", fontsize=11, pad=10) ax2.tick_params(colors="#555", labelsize=8) ax2.invert_yaxis() for spine in ["top", "right"]: ax2.spines[spine].set_visible(False) for spine in ["bottom", "left"]: ax2.spines[spine].set_color("#333")
fig.suptitle( f"Gradient Saliency · p(ASD) = {p_mean:.3f} · Ensemble of {len(_models)} LOSO models", color="#888", fontsize=10, y=1.02, ) plt.tight_layout() buf = io.BytesIO() plt.savefig(buf, format="png", dpi=120, bbox_inches="tight", facecolor="#0d0d0d") plt.close(fig) buf.seek(0) return Image.open(buf).copy()
# ── inference ──────────────────────────────────────────────────────────────
def run_gcn(file_path: str | None): if file_path is None: return "", "", "", None, ""
path = Path(file_path) try: if path.suffix == ".npz": d = np.load(path, allow_pickle=True) fc = d["mean_fc"].astype(np.float32) fc = np.arctanh(np.clip(fc, -0.9999, 0.9999)) adj = np.where(np.abs(fc) >= _FC_THRESHOLD, fc, 0.0).astype(np.float32) bw = d["bold_windows"].astype(np.float32) if len(bw) >= _MAX_WINDOWS: bw = bw[:_MAX_WINDOWS] else: bw = np.concatenate([bw, np.repeat(bw[-1:], _MAX_WINDOWS - len(bw), 0)]) bw_t = torch.FloatTensor(bw).unsqueeze(0) adj_t = torch.FloatTensor(adj).unsqueeze(0) else: bold = np.loadtxt(path, dtype=np.float32) if bold.ndim != 2 or bold.shape[1] != 200: return f"⚠️ Error: expected (T×200) array, got {bold.shape}", "", "", None, "" bw_t, adj_t = preprocess(bold) except Exception as e: return f"⚠️ Error loading file: {e}", "", "", None, ""
models = get_models()
per_model = [] with torch.no_grad(): for site, task in models: logits = task(bw_t, adj_t) p = torch.softmax(logits, -1)[0, 1].item() per_model.append((site, p))
p_mean = float(np.mean([p for _, p in per_model])) consensus = sum(1 for _, p in per_model if p > 0.5) conf = max(p_mean, 1 - p_mean) * 100
try: sal = _compute_saliency(bw_t, adj_t, models) sal_img = _saliency_figure(sal, p_mean) except Exception: sal_img = None
# Verdict if p_mean > 0.6: verdict = f"""<div style="background:#1a1a2e;border-left:6px solid #e63946;padding:24px 28px;border-radius:12px;margin-bottom:8px"><div style="font-size:2rem;font-weight:800;color:#e63946;letter-spacing:1px">ASD INDICATED</div><div style="font-size:1.1rem;color:#aaa;margin-top:6px">Confidence: <b style="color:white">{conf:.1f}%</b> | p(ASD) = <b style="color:white">{p_mean:.3f}</b> | <b style="color:white">{consensus}/4</b> site-blind models agree</div></div>""" elif p_mean < 0.4: verdict = f"""<div style="background:#1a1a2e;border-left:6px solid #2dc653;padding:24px 28px;border-radius:12px;margin-bottom:8px"><div style="font-size:2rem;font-weight:800;color:#2dc653;letter-spacing:1px">TYPICAL CONTROL</div><div style="font-size:1.1rem;color:#aaa;margin-top:6px">Confidence: <b style="color:white">{conf:.1f}%</b> | p(ASD) = <b style="color:white">{p_mean:.3f}</b> | <b style="color:white">{4-consensus}/4</b> site-blind models agree</div></div>""" else: verdict = f"""<div style="background:#1a1a2e;border-left:6px solid #f4a261;padding:24px 28px;border-radius:12px;margin-bottom:8px"><div style="font-size:2rem;font-weight:800;color:#f4a261;letter-spacing:1px">INCONCLUSIVE</div><div style="font-size:1.1rem;color:#aaa;margin-top:6px">Confidence: <b style="color:white">{conf:.1f}%</b> | p(ASD) = <b style="color:white">{p_mean:.3f}</b> | Model disagreement — clinical review required</div></div>"""
# Ensemble breakdown rows = "" for site, p in per_model: lbl = "ASD" if p > 0.5 else "TC" color = "#e63946" if p > 0.5 else "#2dc653" bar_w = int(p * 100) rows += f"""<tr><td style="padding:8px 12px;color:#ccc;font-weight:600">{site}-blind</td><td style="padding:8px 12px"><div style="background:#333;border-radius:4px;height:18px;width:160px"><div style="background:{color};height:18px;width:{bar_w}%;border-radius:4px;opacity:0.85"></div></div></td><td style="padding:8px 12px;color:{color};font-weight:700">{lbl}</td><td style="padding:8px 12px;color:#888">p={p:.3f}</td></tr>"""
ensemble = f"""<div style="background:#111;border-radius:10px;padding:20px;margin-top:4px"><div style="color:#888;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:14px">Leave-One-Site-Out Ensemble — each model never trained on that site's data</div><table style="width:100%;border-collapse:collapse">{rows}</table><div style="margin-top:14px;color:#666;font-size:0.82rem">Cross-site consensus: {consensus}/4 models agree · LOSO AUC = 0.7872 across 529 held-out subjects</div></div>"""
# LLM clinical report llm_text = _llm_report(p_mean, per_model) report = f"""<div style="background:#111;border-radius:10px;padding:20px;margin-top:4px"><div style="color:#888;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin-bottom:14px">Clinical Report — Qwen2.5-7B fine-tuned on AMD Instinct MI300X</div><div style="color:#ddd;font-size:0.95rem;line-height:1.7;white-space:pre-wrap">{llm_text}</div><div style="background:#1a1a1a;border-radius:6px;padding:12px;color:#555;font-size:0.78rem;margin-top:16px">⚕️ AI-assisted analysis only. Does not constitute a diagnosis. Integrate with clinical history, behavioral assessment, and standardized instruments (ADOS-2, ADI-R).</div></div>"""
return verdict, ensemble, report, sal_img
# ── UI ─────────────────────────────────────────────────────────────────────
css = """body { background: #0d0d0d; }.gradio-container { max-width: 960px; margin: auto; }"""
with gr.Blocks(title="BrainConnect-ASD", css=css, theme=gr.themes.Base()) as demo: gr.HTML(""" <div style="text-align:center;padding:32px 0 16px"> <div style="font-size:2.2rem;font-weight:900;color:white;letter-spacing:-1px">BrainConnect<span style="color:#e63946">-ASD</span></div> <div style="color:#888;font-size:1rem;margin-top:8px">Scanner-site-invariant ASD detection from resting-state fMRI</div> <div style="display:flex;justify-content:center;gap:24px;margin-top:16px;flex-wrap:wrap"> <span style="background:#1a1a2e;color:#aaa;padding:6px 14px;border-radius:20px;font-size:0.85rem">LOSO AUC 0.7872</span> <span style="background:#1a1a2e;color:#aaa;padding:6px 14px;border-radius:20px;font-size:0.85rem">529 held-out subjects</span> <span style="background:#1a1a2e;color:#aaa;padding:6px 14px;border-radius:20px;font-size:0.85rem">4 independent institutions</span> <span style="background:#1a1a2e;color:#aaa;padding:6px 14px;border-radius:20px;font-size:0.85rem">AMD Instinct MI300X</span> </div> </div> """)
file_input = gr.File(label="Upload CC200 fMRI file (.1D or .npz)", type="filepath") verdict_html = gr.HTML() ensemble_html = gr.HTML()
gr.HTML("<div style='color:#888;font-size:0.8rem;text-transform:uppercase;letter-spacing:2px;margin:24px 0 8px'>Gradient Saliency — which brain connections drove this prediction</div>") saliency_img = gr.Image(label="FC Edge Saliency & ROI Importance", type="pil")
report_html = gr.HTML()
file_input.change( fn=run_gcn, inputs=file_input, outputs=[verdict_html, ensemble_html, report_html, saliency_img], )
gr.HTML(""" <div style="text-align:center;padding:24px 0;color:#444;font-size:0.8rem"> Adversarial Brain-Mode GCN (k=16) · Qwen2.5-7B LoRA (AMD MI300X) · ABIDE I · <a href="https://github.com/Yatsuiii/Brain-Connectivity-GCN" style="color:#666">GitHub</a> </div> """)
print("Preloading GCN models...")get_models()print("Preloading LLM...")get_llm()print("All models ready.")
if __name__ == "__main__": demo.launch()123version https://git-lfs.github.com/spec/v1oid sha256:6d588597092f4b9483fdcfb0f8d5aae67030ea9d17df8cf7a0c027ef527b5657size 253386123version https://git-lfs.github.com/spec/v1oid sha256:3af986f0e5909e8551c2473ee3ff876ff9cc814ea38e220de33fad96201eaa37size 253386123version https://git-lfs.github.com/spec/v1oid sha256:9b380df053b6a9a83dc6062070418cd6b8718b4f4c5c5f8b388330dcf0a9abf5size 253386123version https://git-lfs.github.com/spec/v1oid sha256:7410692b93237e59fe5a03726338b7f02f0b61acbb6185dc1ecc79dfbee6bdacsize 252813app.py+121-39
app_with_llm.pyAdded+363
checkpoints/aal_nyu.ckptAdded+3
checkpoints/aal_ucla.ckptAdded+3
checkpoints/aal_um.ckptAdded+3
checkpoints/aal_usm.ckptAdded+3