Upload app.py with huggingface_hub
Browse files2 unmodified lines34567859 unmodified lines68697071727374757677787912 unmodified lines929394959697989910010110210310410510610710810911011111211311468 unmodified lines18318418518618718818919019119219319419519612 unmodified lines2092102112122132142152162172182192202212222 unmodified lines"""from __future__ import annotationsfrom pathlib import Pathimport numpy as np59 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 = []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# ── 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>68 unmodified lines<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:12 unmodified linesfile_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("""2 unmodified lines345678959 unmodified lines6970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916012 unmodified lines17317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420568 unmodified lines27427527627727827928028128228328428528628712 unmodified lines3003013023033043053063073083093103113123133143153163173183193202 unmodified lines"""from __future__ import annotationsimport iofrom pathlib import Pathimport numpy as np59 unmodified lines_models.append((site, task))return _models# ── gradient saliency ──────────────────────────────────────────────────────def _compute_saliency(bw_t: torch.Tensor, adj_t: torch.Tensor, models) -> np.ndarray:"""Gradient of p(ASD) w.r.t. adjacency matrix, averaged over ensemble."""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) # (200, 200)sal = (sal + sal.T) / 2 # symmetrizereturn saldef _saliency_figure(sal: np.ndarray, p_mean: float):import matplotlibmatplotlib.use("Agg")import matplotlib.pyplot as pltfrom PIL import Imagethresh = 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")# ── Left: FC edge saliency heatmap ──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")# ── Right: top-20 ROI importance bar chart ──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 "", "", "", Nonepath = 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}", "", "", Nonebw_t, adj_t = preprocess(bold)except Exception as e:return f"⚠️ Error loading file: {e}", "", "", Nonemodels = get_models()# ── Ensemble inference (no grad) ──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# ── Gradient saliency ──try:sal = _compute_saliency(bw_t, adj_t, models)sal_img = _saliency_figure(sal, p_mean)except Exception:sal_img = None# ── Verdict card ──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>68 unmodified lines<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, 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:12 unmodified linesfile_input = gr.File(label="Upload CC200 fMRI file (.1D or .npz)", type="filepath")verdict_html = gr.HTML()ensemble_html = gr.HTML()with gr.Row():report_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_html2 = gr.HTML()file_input.change(fn=run_gcn,inputs=file_input,outputs=[verdict_html, ensemble_html, report_html2, saliency_img],)gr.HTML("""
app.py+114-16