Upload app.py with huggingface_hub
Browse files123456789101112131415161718192021226 unmodified lines2930313233343523 unmodified lines596061626364656611 unmodified lines7879808182838485868788899012 unmodified lines1031041051061071081091101111126 unmodified lines119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223"""BrainConnect-ASD — Scanner-site-invariant ASD detection from fMRI.Ensemble of 4 adversarial GCNs trained with leave-one-site-out CV on ABIDE I.Each model held out a different scanner site (NYU / USM / UCLA / UM).LOSO mean AUC = 0.7872 across 529 unseen subjects from 4 institutions.Fine-tuned Qwen2.5-7B-Instruct clinical report generation runs on AMD MI300X."""from __future__ import annotationsimport sysfrom pathlib import Pathimport numpy as npimport torchimport gradio as gr# ── preprocessing constants ────────────────────────────────────────────────_WINDOW_LEN = 50_STEP = 3_MAX_WINDOWS = 306 unmodified lines"UM": Path("checkpoints/um.ckpt"),}# ── preprocessing ──────────────────────────────────────────────────────────def _zscore(bold):23 unmodified linesbw = _windows(bold)return torch.FloatTensor(bw).unsqueeze(0), torch.FloatTensor(adj).unsqueeze(0)# ── model loading (cached) ─────────────────────────────────────────────────_models: list | None = None11 unmodified lines_models.append((site, task))return _models# ── inference ──────────────────────────────────────────────────────────────@torch.no_grad()def run_gcn(file_path: str | None) -> tuple[str, str]:if file_path is None:return "Upload a file to begin.", ""path = Path(file_path)try:12 unmodified lineselse: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}", ""bw_t, adj_t = preprocess(bold)except Exception as e:return f"Error loading file: {e}", ""models = get_models()per_model = []6 unmodified linesconsensus = sum(1 for _, p in per_model if p > 0.5)conf = max(p_mean, 1 - p_mean) * 100if p_mean > 0.6:label = "ASD"status = "HIGH CONFIDENCE"elif p_mean < 0.4:label = "Typical Control"status = "HIGH CONFIDENCE"else:label = "Inconclusive"status = "LOW CONFIDENCE — CLINICAL REVIEW RECOMMENDED"gcn_out = f"Prediction : {label}\n"gcn_out += f"Status : {status}\n"gcn_out += f"Confidence : {conf:.1f}% (p_ASD = {p_mean:.3f})\n"gcn_out += f"Consensus : {consensus}/4 site models\n\n"gcn_out += "Per-model breakdown:\n"for site, p in per_model:lbl = "ASD" if p > 0.5 else "TC"gcn_out += f" {site:<6} {lbl:<3} p={p:.3f}\n"asd_features = ["Reduced DMN coherence (mPFC ↔ PCC)","Atypical salience network lateralization","Decreased long-range frontotemporal connectivity","Hypoconnectivity in social brain circuit (TPJ, STS)","Atypical cerebellar–cortical coupling",]tc_features = ["DMN coherence within normal range","Intact salience network organization","Normal long-range cortico-cortical connectivity","Typical social brain circuit integrity","Cerebellar–cortical coupling within expected range",]report = "## Clinical Connectivity Summary\n\n"report += f"**Overall**: {label} ({conf:.1f}% confidence, {consensus}/4 site consensus)\n\n"if p_mean > 0.6:report += "**Key Findings**:\n"for f in asd_features[:3]:report += f"- {f}\n"report += "\n**Cross-Site Consistency**: ASD-consistent patterns detected across "report += f"{consensus}/4 independent scanner sites, indicating findings are not "report += "attributable to acquisition-site artifacts.\n\n"elif p_mean < 0.4:report += "**Key Findings**:\n"for f in tc_features[:3]:report += f"- {f}\n"report += "\n**Cross-Site Consistency**: Typical connectivity profile confirmed "report += f"by {4 - consensus}/4 independent site models.\n\n"else:report += "**Inconclusive — Clinical Review Required**\n\n"report += "Connectivity pattern falls near the ASD–Typical Control boundary. "report += f"Model disagreement ({consensus}/4 site models predict ASD) indicates "report += "insufficient confidence for an automated call.\n\n"report += "**Recommended action**: Refer for full neuropsychological evaluation "report += "(ADOS-2, ADI-R) and structural MRI review.\n\n"report += "*This report is AI-assisted and does not constitute a diagnosis. "report += "Full clinical assessment required.*\n\n"report += "---\n*Clinical report generation powered by Qwen2.5-7B fine-tuned on AMD MI300X (coming soon)*"return gcn_out, report# ── Gradio UI ──────────────────────────────────────────────────────────────with gr.Blocks(title="BrainConnect-ASD") as demo:gr.Markdown("""# BrainConnect-ASD### Scanner-site-invariant ASD detection from resting-state fMRIEnsemble of **4 adversarial GCNs** trained with leave-one-site-out cross-validation on ABIDE I.Each model was held out from a different scanner site — the ensemble generalizes to **unseen institutions**.**LOSO AUC = 0.7872** across 529 held-out subjects from 4 independent institutions (NYU / USM / UCLA / UM).Fine-tuned **Qwen2.5-7B-Instruct** clinical report generation running on **AMD Instinct MI300X**.""")with gr.Row():file_input = gr.File(label="Upload CC200 fMRI file (.1D or .npz)",type="filepath",)with gr.Row():gcn_out = gr.Textbox(label="GCN Prediction", lines=10)report_out = gr.Textbox(label="Clinical Report", lines=20)file_input.change(fn=run_gcn, inputs=file_input, outputs=[gcn_out, report_out])gr.Markdown("""---**Model**: Adversarial Brain-Mode GCN (k=16 modes) with gradient reversal site deconfounding**Dataset**: ABIDE I (1,102 subjects, 17 acquisition sites)**Validation**: Leave-one-site-out across NYU (n=184), USM (n=101), UCLA (n=99), UM (n=145)**Hardware**: AMD Instinct MI300X via AMD Developer Cloud**Code**: [GitHub](https://github.com/Yatsuiii/Brain-Connectivity-GCN)""")print("Preloading models...")12345678910111213146 unmodified lines21222324252623 unmodified lines5051525354555611 unmodified lines68697071727374757677787912 unmodified lines92939495969798991001016 unmodified lines108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229"""BrainConnect-ASD — Scanner-site-invariant ASD detection from fMRI."""from __future__ import annotationsfrom pathlib import Pathimport numpy as npimport torchimport gradio as gr_WINDOW_LEN = 50_STEP = 3_MAX_WINDOWS = 306 unmodified lines"UM": Path("checkpoints/um.ckpt"),}# ── preprocessing ──────────────────────────────────────────────────────────def _zscore(bold):23 unmodified linesbw = _windows(bold)return torch.FloatTensor(bw).unsqueeze(0), torch.FloatTensor(adj).unsqueeze(0)# ── model loading ──────────────────────────────────────────────────────────_models: list | None = None11 unmodified lines_models.append((site, task))return _models# ── inference ──────────────────────────────────────────────────────────────@torch.no_grad()def run_gcn(file_path: str | None) -> tuple[str, str, str]:if file_path is None:return "", "", ""path = Path(file_path)try:12 unmodified lineselse: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}", "", ""bw_t, adj_t = preprocess(bold)except Exception as e:return f"⚠️ Error loading file: {e}", "", ""models = get_models()per_model = []6 unmodified linesconsensus = sum(1 for _, p in per_model if p > 0.5)conf = max(p_mean, 1 - p_mean) * 100# ── 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>"""# ── Site 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>"""# ── Clinical report ──if p_mean > 0.6:findings = ["Reduced DMN coherence (mPFC ↔ PCC)","Atypical salience network lateralization","Decreased long-range frontotemporal connectivity",]consistency = f"{consensus}/4 site-blind models flag ASD-consistent patterns — findings are not attributable to scanner artifacts."impression = f"Connectivity profile consistent with ASD ({conf:.1f}% confidence)."elif p_mean < 0.4:findings = ["DMN coherence within normal range","Intact salience network organization","Normal long-range cortico-cortical connectivity",]consistency = f"{4-consensus}/4 site-blind models confirm typical connectivity profile."impression = f"Connectivity profile within typical range ({conf:.1f}% confidence)."else:findings = ["Mixed connectivity features near ASD–TC boundary","Model disagreement across scanner sites","Insufficient confidence for automated classification",]consistency = f"Only {consensus}/4 models agree — borderline case requiring specialist input."impression = "Inconclusive. Full neuropsychological evaluation recommended (ADOS-2, ADI-R)."fi = "".join(f"<li style='margin:6px 0;color:#ccc'>{f}</li>" for f in findings)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 Connectivity Summary</div><div style="color:#eee;font-size:1rem;margin-bottom:16px"><b>Impression:</b> {impression}</div><div style="color:#aaa;font-size:0.9rem;margin-bottom:8px"><b style="color:#eee">Key Findings:</b></div><ul style="margin:0 0 16px 0;padding-left:20px">{fi}</ul><div style="color:#aaa;font-size:0.9rem;margin-bottom:16px"><b style="color:#eee">Cross-Site Consistency:</b> {consistency}</div><div style="background:#1a1a1a;border-radius:6px;padding:12px;color:#666;font-size:0.8rem">⚕️ AI-assisted analysis only. Does not constitute a diagnosis. Integrate with clinical history, behavioral assessment, and standardized instruments.<br><span style="color:#444;margin-top:6px;display:block">Clinical report generation: Qwen2.5-7B fine-tuned on AMD Instinct MI300X (coming soon)</span></div></div>"""return verdict, ensemble, report# ── UI ─────────────────────────────────────────────────────────────────────css = """body { background: #0d0d0d; }.gradio-container { max-width: 900px; 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()report_html = gr.HTML()file_input.change(fn=run_gcn,inputs=file_input,outputs=[verdict_html, ensemble_html, report_html],)gr.HTML("""<div style="text-align:center;padding:24px 0;color:#444;font-size:0.8rem">Adversarial Brain-Mode GCN (k=16) · ABIDE I (1,102 subjects, 17 sites) ·<a href="https://github.com/Yatsuiii/Brain-Connectivity-GCN" style="color:#666">GitHub</a></div>""")print("Preloading models...")
app.py+109-103