Update app.py
Browse files
app.py
CHANGED
|
@@ -1,164 +1,183 @@
|
|
| 1 |
import os
|
| 2 |
-
import gradio as gr
|
| 3 |
-
import torch
|
| 4 |
import pickle
|
| 5 |
import numpy as np
|
| 6 |
-
import
|
| 7 |
-
|
| 8 |
-
from
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
# =========================
|
| 18 |
-
# LOAD MODEL
|
| 19 |
-
# =========================
|
| 20 |
-
checkpoint = torch.load(
|
| 21 |
-
"sirenMRI_full_model_final.pt",
|
| 22 |
-
map_location=device
|
| 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 |
-
nii = nib.load(nifti_file.name)
|
| 75 |
-
img = nii.get_fdata()
|
| 76 |
-
|
| 77 |
-
original_shape = img.shape
|
| 78 |
-
|
| 79 |
-
# =========================
|
| 80 |
-
# HANDLE 4D MRI
|
| 81 |
-
# =========================
|
| 82 |
-
if len(img.shape) != 4:
|
| 83 |
-
return "β Expected a 4D MRI (.nii or .nii.gz)", None
|
| 84 |
-
|
| 85 |
-
h, w, slices, vols = img.shape
|
| 86 |
|
| 87 |
-
|
|
|
|
| 88 |
|
| 89 |
-
# =========================
|
| 90 |
-
# GENERATE COORDINATES
|
| 91 |
-
# =========================
|
| 92 |
-
coords = create_coordinates(h, w).to(device)
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
# =========================
|
| 97 |
-
with torch.no_grad():
|
| 98 |
|
| 99 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
|
|
|
|
| 102 |
|
| 103 |
-
pred = pred.cpu().numpy()
|
| 104 |
|
| 105 |
-
|
| 106 |
-
|
|
|
|
| 107 |
|
| 108 |
-
|
|
|
|
|
|
|
|
|
|
| 109 |
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
# =========================
|
| 115 |
-
output_path = "reconstructed_output.nii.gz"
|
| 116 |
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
)
|
| 122 |
|
| 123 |
-
|
|
|
|
| 124 |
|
| 125 |
-
|
| 126 |
-
f"""β
Reconstruction complete
|
| 127 |
|
| 128 |
-
Original Shape: {original_shape}
|
| 129 |
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
output_path
|
| 133 |
-
)
|
| 134 |
|
| 135 |
-
except Exception as e:
|
| 136 |
-
return f"β Error: {str(e)}", None
|
| 137 |
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
#
|
| 142 |
-
|
| 143 |
-
|
|
|
|
|
|
|
| 144 |
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
),
|
| 148 |
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
],
|
| 153 |
|
| 154 |
-
title="Physics-Informed SIREN MRI Reconstruction",
|
| 155 |
|
| 156 |
-
|
| 157 |
-
|
|
|
|
| 158 |
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
""
|
|
|
|
| 162 |
)
|
| 163 |
|
| 164 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
|
|
|
|
|
|
| 2 |
import pickle
|
| 3 |
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
from math import sqrt
|
| 7 |
+
import streamlit as st
|
| 8 |
+
|
| 9 |
+
# ββ Streamlit page config ββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 10 |
+
st.set_page_config(
|
| 11 |
+
page_title="Physics-Informed SIREN MRI Compression",
|
| 12 |
+
page_icon="π§ ",
|
| 13 |
+
layout="wide",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
)
|
| 15 |
|
| 16 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 17 |
+
# 1. Model definitions β must match exactly what was used during training
|
| 18 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 19 |
+
|
| 20 |
+
class Sine(nn.Module):
|
| 21 |
+
def __init__(self, w0=1.0):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self.w0 = w0
|
| 24 |
+
|
| 25 |
+
def forward(self, x):
|
| 26 |
+
return torch.sin(self.w0 * x)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class SirenLayer(nn.Module):
|
| 30 |
+
def __init__(self, dim_in, dim_out, w0=30.0, c=6.0,
|
| 31 |
+
is_first=False, use_bias=True, activation=None):
|
| 32 |
+
super().__init__()
|
| 33 |
+
self.dim_in = dim_in
|
| 34 |
+
self.is_first = is_first
|
| 35 |
+
self.linear = nn.Linear(dim_in, dim_out, bias=use_bias)
|
| 36 |
+
w_std = (1 / dim_in) if is_first else (sqrt(c / dim_in) / w0)
|
| 37 |
+
nn.init.uniform_(self.linear.weight, -w_std, w_std)
|
| 38 |
+
if use_bias:
|
| 39 |
+
nn.init.uniform_(self.linear.bias, -w_std, w_std)
|
| 40 |
+
self.activation = Sine(w0) if activation is None else activation
|
| 41 |
+
|
| 42 |
+
def forward(self, x):
|
| 43 |
+
return self.activation(self.linear(x))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class Siren(nn.Module):
|
| 47 |
+
def __init__(self, dim_in, dim_hidden, dim_out, num_layers,
|
| 48 |
+
w0=30.0, w0_initial=30.0, use_bias=True, final_activation=None):
|
| 49 |
+
super().__init__()
|
| 50 |
+
layers = []
|
| 51 |
+
for i in range(num_layers):
|
| 52 |
+
is_first = i == 0
|
| 53 |
+
layer_w0 = w0_initial if is_first else w0
|
| 54 |
+
layer_dim_in = dim_in if is_first else dim_hidden
|
| 55 |
+
layers.append(SirenLayer(
|
| 56 |
+
dim_in=layer_dim_in, dim_out=dim_hidden,
|
| 57 |
+
w0=layer_w0, use_bias=use_bias, is_first=is_first,
|
| 58 |
+
))
|
| 59 |
+
self.net = nn.Sequential(*layers)
|
| 60 |
+
final_activation = nn.Identity() if final_activation is None else final_activation
|
| 61 |
+
self.last_layer = SirenLayer(
|
| 62 |
+
dim_in=dim_hidden, dim_out=dim_out,
|
| 63 |
+
w0=w0, use_bias=use_bias, activation=final_activation,
|
| 64 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
+
def forward(self, x):
|
| 67 |
+
return self.last_layer(self.net(x))
|
| 68 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 69 |
|
| 70 |
+
class SirenMRIModel(nn.Module):
|
| 71 |
+
"""Multi-slice wrapper β one Siren per axial slice."""
|
|
|
|
|
|
|
| 72 |
|
| 73 |
+
def __init__(self, config: dict):
|
| 74 |
+
super().__init__()
|
| 75 |
+
self.config = config
|
| 76 |
+
self.models = nn.ModuleList()
|
| 77 |
+
for _ in range(config["sz"]):
|
| 78 |
+
self.models.append(Siren(
|
| 79 |
+
dim_in=2,
|
| 80 |
+
dim_hidden=config["layer_size"],
|
| 81 |
+
dim_out=config["vols"],
|
| 82 |
+
num_layers=config["num_layers"],
|
| 83 |
+
w0=config["w0"],
|
| 84 |
+
w0_initial=config["w0_initial"],
|
| 85 |
+
))
|
| 86 |
|
| 87 |
+
def forward(self, coords: torch.Tensor, slice_idx: int) -> torch.Tensor:
|
| 88 |
+
return self.models[slice_idx](coords)
|
| 89 |
|
|
|
|
| 90 |
|
| 91 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 92 |
+
# 2. Load model + scalers (cached so they only load once)
|
| 93 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 94 |
|
| 95 |
+
@st.cache_resource
|
| 96 |
+
def load_model():
|
| 97 |
+
model_path = "sirenMRI_full_model_final.pt"
|
| 98 |
+
scalers_path = "scalers.pkl"
|
| 99 |
|
| 100 |
+
if not os.path.exists(model_path):
|
| 101 |
+
st.error(f"Model file not found: {model_path}")
|
| 102 |
+
st.stop()
|
| 103 |
+
if not os.path.exists(scalers_path):
|
| 104 |
+
st.error(f"Scalers file not found: {scalers_path}")
|
| 105 |
+
st.stop()
|
| 106 |
|
| 107 |
+
checkpoint = torch.load(model_path, map_location="cpu")
|
| 108 |
+
config = checkpoint["config"]
|
|
|
|
|
|
|
| 109 |
|
| 110 |
+
# ββ THE FIX: build SirenMRIModel, not bare Siren ββββββββββββββββββββββ
|
| 111 |
+
model = SirenMRIModel(config)
|
| 112 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 113 |
+
model.eval()
|
|
|
|
| 114 |
|
| 115 |
+
with open(scalers_path, "rb") as f:
|
| 116 |
+
scalers = pickle.load(f)
|
| 117 |
|
| 118 |
+
return model, scalers, config, checkpoint["input_shape"]
|
|
|
|
| 119 |
|
|
|
|
| 120 |
|
| 121 |
+
model, scalers, config, input_shape = load_model()
|
| 122 |
+
sx, sy, sz, vols = input_shape
|
|
|
|
|
|
|
| 123 |
|
|
|
|
|
|
|
| 124 |
|
| 125 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 126 |
+
# 3. Inference helper
|
| 127 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 128 |
|
| 129 |
+
def reconstruct_slice(slice_idx: int) -> np.ndarray:
|
| 130 |
+
"""Return reconstructed slice as (sx, sy, vols) float32 array."""
|
| 131 |
+
# Build normalised (x, y) coordinate grid in [-1, 1]
|
| 132 |
+
xs = torch.linspace(-1, 1, sx)
|
| 133 |
+
ys = torch.linspace(-1, 1, sy)
|
| 134 |
+
grid_x, grid_y = torch.meshgrid(xs, ys, indexing="ij")
|
| 135 |
+
coords = torch.stack([grid_x.reshape(-1), grid_y.reshape(-1)], dim=-1) # (sx*sy, 2)
|
| 136 |
|
| 137 |
+
with torch.no_grad():
|
| 138 |
+
pred = model(coords, slice_idx).numpy() # (sx*sy, vols)
|
|
|
|
| 139 |
|
| 140 |
+
# Inverse-transform back to original intensity range
|
| 141 |
+
pred = scalers[slice_idx].inverse_transform(pred)
|
| 142 |
+
return pred.reshape(sx, sy, vols)
|
|
|
|
| 143 |
|
|
|
|
| 144 |
|
| 145 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 146 |
+
# 4. Streamlit UI
|
| 147 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 148 |
|
| 149 |
+
st.title("π§ Physics-Informed SIREN MRI Compression")
|
| 150 |
+
st.markdown(
|
| 151 |
+
"Reconstruct axial slices from the compressed SIREN representation. "
|
| 152 |
+
"Use the sliders to choose a slice and a diffusion volume."
|
| 153 |
)
|
| 154 |
|
| 155 |
+
col1, col2 = st.columns(2)
|
| 156 |
+
with col1:
|
| 157 |
+
slice_idx = st.slider("Axial slice", 0, sz - 1, sz // 2)
|
| 158 |
+
with col2:
|
| 159 |
+
vol_idx = st.slider("Diffusion volume (b-value index)", 0, vols - 1, 0)
|
| 160 |
+
|
| 161 |
+
if st.button("Reconstruct slice"):
|
| 162 |
+
with st.spinner("Running SIREN inference..."):
|
| 163 |
+
recon = reconstruct_slice(slice_idx) # (sx, sy, vols)
|
| 164 |
+
img = recon[:, :, vol_idx]
|
| 165 |
+
|
| 166 |
+
# Normalise to [0, 1] for display
|
| 167 |
+
img_norm = (img - img.min()) / (img.max() - img.min() + 1e-8)
|
| 168 |
+
|
| 169 |
+
st.image(
|
| 170 |
+
img_norm,
|
| 171 |
+
caption=f"Reconstructed slice {slice_idx}, volume {vol_idx}",
|
| 172 |
+
use_column_width=True,
|
| 173 |
+
clamp=True,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
st.success(f"Slice shape: {img.shape} | Value range: [{img.min():.3f}, {img.max():.3f}]")
|
| 177 |
+
|
| 178 |
+
st.divider()
|
| 179 |
+
st.caption(
|
| 180 |
+
f"Model config β layers: {config['num_layers']}, "
|
| 181 |
+
f"hidden size: {config['layer_size']}, "
|
| 182 |
+
f"w0: {config['w0']}, slices: {sz}, volumes: {vols}"
|
| 183 |
+
)
|