New_Lukemia / app.py
MuahammadHamza's picture
Upload 6 files
ac97690 verified
Raw History Blame Contribute Delete
16.7 kB
import os
import json
from collections import defaultdict
from typing import Tuple
import gradio as gr
import networkx as nx
import numpy as np
import torch
from sklearn.metrics.pairwise import euclidean_distances
from sklearn.preprocessing import OneHotEncoder, StandardScaler
from torch_geometric.data import Data
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
# Actual input feature dimension that the trained GAT expects.
IN_CHANNELS: int | None = None
def load_model(model_path: str) -> torch.nn.Module:
"""
Load the trained GAT model from disk.
This mirrors the GATClassifier architecture in gat2.ipynb, but it
infers the correct input feature dimension (in_channels) directly
from the checkpoint to avoid size mismatch errors.
"""
from torch import nn
from torch_geometric.nn import GATConv, global_add_pool
# Load the state dict first so we can inspect conv1.lin.weight
state = torch.load(model_path, map_location=DEVICE)
conv1_weight = state.get("conv1.lin.weight")
if conv1_weight is None:
raise KeyError("conv1.lin.weight not found in checkpoint; cannot infer in_channels.")
# For GATConv, conv1.lin.weight has shape [heads * out_channels, in_channels]
inferred_in_channels = int(conv1_weight.shape[1])
# Remember the expected input feature dimension globally so that we can
# align any computed node features with what the model expects.
global IN_CHANNELS
IN_CHANNELS = inferred_in_channels
class GATClassifier(nn.Module):
def __init__(
self,
in_channels: int,
hidden_channels: int = 64,
num_classes: int = 2,
dropout: float = 0.5,
heads: int = 1,
) -> None:
super().__init__()
self.conv1 = GATConv(in_channels, hidden_channels, heads=heads, dropout=dropout, concat=True)
out_dim = hidden_channels * heads
self.conv2 = GATConv(out_dim, hidden_channels, heads=heads, dropout=dropout, concat=True)
out_dim2 = hidden_channels * heads
self.dropout = nn.Dropout(dropout)
self.lin1 = nn.Linear(out_dim2 * 2, out_dim2 * 2)
self.lin2 = nn.Linear(out_dim2 * 2, num_classes)
def forward(self, x, edge_index, batch):
import torch.nn.functional as F
h1 = self.conv1(x, edge_index)
h1 = F.elu(h1)
h2 = self.conv2(h1, edge_index)
h2 = F.elu(h2)
g1 = global_add_pool(h1, batch)
g2 = global_add_pool(h2, batch)
h = torch.cat([g1, g2], dim=1)
h = self.lin1(h)
h = F.elu(h)
h = self.dropout(h)
h = self.lin2(h)
return h
# Allow an override via env var, but default to the inferred value
env_override = os.environ.get("GAT_IN_CHANNELS")
if env_override is not None:
try:
in_channels = int(env_override)
except ValueError:
in_channels = inferred_in_channels
else:
in_channels = inferred_in_channels
model = GATClassifier(
in_channels=in_channels,
hidden_channels=64,
num_classes=2,
dropout=0.5,
heads=1,
).to(DEVICE)
model.load_state_dict(state)
model.eval()
return model
def load_gat_model() -> Tuple[torch.nn.Module, str]:
"""
Load the GAT model from a path that can be configured via environment variable.
Priority:
1. MODEL_PATH env var
2. ./models/gat_best.pt inside the container
3. ./gat_best.pt in the working directory
"""
candidate_paths = []
env_path = os.environ.get("MODEL_PATH")
if env_path:
candidate_paths.append(env_path)
candidate_paths.append(os.path.join("models", "gat_best.pt"))
candidate_paths.append("gat_best.pt")
for p in candidate_paths:
if p and os.path.exists(p):
model = load_model(p)
return model, os.path.abspath(p)
raise FileNotFoundError(
"Could not find a trained GAT model. "
"Set MODEL_PATH or mount a gat_best.pt file into ./models/gat_best.pt."
)
try:
MODEL, MODEL_PATH = load_gat_model()
LOAD_MESSAGE = f"Loaded GAT model from: {MODEL_PATH}"
except Exception as exc:
MODEL, MODEL_PATH = None, ""
LOAD_MESSAGE = f"Failed to load model: {exc}"
# ==============================
# Dataset + graph construction (ported from gat2.ipynb)
# ==============================
"""
Gradio app for AML vs ALL classification using a GAT model trained on H_100X_C2.
IMPORTANT: At runtime we need the dataset annotation JSON files. By default we
assume they live next to this file (in the same folder as `app.py`):
train.json
test.json
You can override the root folder with the DATA_BASE environment variable so that:
<DATA_BASE>/train.json
<DATA_BASE>/test.json
exist.
"""
# Base path to the dataset annotations.
# Resolution priority:
# 1) DATA_BASE env var (if set)
# 2) Same folder as this file (default)
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
def _resolve_data_base() -> str:
env_base = os.environ.get("DATA_BASE")
if env_base:
return env_base
# Default: same folder as app.py; expects ./train.json and ./test.json
return BASE_DIR
DATA_BASE = _resolve_data_base()
TRAIN_JSON = os.path.join(DATA_BASE, "train.json")
TEST_JSON = os.path.join(DATA_BASE, "test.json")
CLEAN_IMPUTED_JSON = os.path.join(DATA_BASE, "train_clean_imputed.json")
# Numeric feature columns from the notebook
NUM_COLS = [
"cell_size",
"nuclear_chromatio",
"nuclear_shape",
"nucleolus",
"cytoplasm",
"cytoplasmic_basophilia",
"cytoplasmic_vacuoles",
]
def _load_train_annotations():
"""
Load train annotations (prefer cleaned/imputed JSON if present),
and build encoders/scalers for node features as in gat2.ipynb.
"""
source_path = CLEAN_IMPUTED_JSON if os.path.exists(CLEAN_IMPUTED_JSON) else TRAIN_JSON
if not os.path.exists(source_path):
raise FileNotFoundError(
f"Could not find train annotations at {source_path}. "
"Place `train.json` next to `app.py` or set DATA_BASE so that "
"`<DATA_BASE>/train.json` exists."
)
with open(source_path, "r") as f:
cj = json.load(f)
images_local = {img["id"]: img for img in cj["images"]}
ann_by_image_local = defaultdict(list)
for ann in cj["annotations"]:
ann_by_image_local[ann["image_id"]].append(ann)
def get_aml_all_label_from_fname(fname: str):
f = fname.lower()
is_aml = "_aml" in f
is_all = "_all" in f
if is_aml and not is_all:
return 1
if is_all and not is_aml:
return 0
return None
labels_map = {}
for img_id, img in images_local.items():
lbl = get_aml_all_label_from_fname(img["file_name"])
if lbl is not None:
labels_map[img_id] = lbl
selected_image_ids = sorted(labels_map.keys())
cat_list: list[str] = []
num_list: list[list[float]] = []
for img_id in selected_image_ids:
for a in ann_by_image_local.get(img_id, []):
cat_list.append(a.get("category_name", "unknown"))
num_list.append([a.get(c) for c in NUM_COLS])
cat_unique = sorted(set(cat_list))
oh_local = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
oh_local.fit(np.array(cat_unique).reshape(-1, 1))
num_arr = np.array(num_list, dtype=float)
num_arr[num_arr == 4.0] = np.nan
col_meds_local = np.nanmedian(num_arr, axis=0)
inds = np.where(np.isnan(num_arr))
for r, c in zip(*inds):
num_arr[r, c] = col_meds_local[c] if not np.isnan(col_meds_local[c]) else 0.0
scaler_local = StandardScaler()
scaler_local.fit(num_arr)
return images_local, ann_by_image_local, oh_local, scaler_local, col_meds_local
def _load_test_annotations():
if not os.path.exists(TEST_JSON):
raise FileNotFoundError(
f"Could not find test annotations at {TEST_JSON}. "
"Place `test.json` next to `app.py` or set DATA_BASE so that "
"`<DATA_BASE>/test.json` exists."
)
with open(TEST_JSON, "r") as f:
tj = json.load(f)
test_images_local = {img["id"]: img for img in tj["images"]}
ann_by_image_test_local = defaultdict(list)
for ann in tj["annotations"]:
ann_by_image_test_local[ann["image_id"]].append(ann)
return test_images_local, ann_by_image_test_local
try:
IMAGES, ANN_BY_IMAGE, OH, SCALER, COL_MEDS = _load_train_annotations()
TEST_IMAGES, ANN_BY_IMAGE_TEST = _load_test_annotations()
DATA_READY = True
DATA_ERROR_MSG = ""
except FileNotFoundError as e:
# Dataset not present inside the container / Space.
IMAGES = ANN_BY_IMAGE = OH = SCALER = COL_MEDS = None
TEST_IMAGES = ANN_BY_IMAGE_TEST = None
DATA_READY = False
DATA_ERROR_MSG = str(e)
K_KNN = 6
EPS = 1e-6
def build_nodes_and_features(anns):
"""
Build node coordinates + feature matrix for a list of annotations,
using the same preprocessing as in gat2.ipynb.
"""
coords, cats, num_feats = [], [], []
for a in anns:
x_bbox, y_bbox, w, h = a["bbox"]
cx = x_bbox + w / 2.0
cy = y_bbox + h / 2.0
coords.append([cx, cy])
cats.append([a.get("category_name", "unknown")])
raw_vals = [a.get(c) for c in NUM_COLS]
cleaned = []
for i, v in enumerate(raw_vals):
if v is None or v == 4:
cleaned.append(np.nan)
else:
try:
cleaned.append(float(v))
except (TypeError, ValueError):
cleaned.append(np.nan)
nf = [COL_MEDS[i] if np.isnan(v) else v for i, v in enumerate(cleaned)]
num_feats.append(nf)
if not coords:
return None, None, None
coords = np.array(coords, dtype=float)
num_feats = np.array(num_feats, dtype=float)
num_feats = SCALER.transform(num_feats)
cat_oh = OH.transform(np.array(cats))
x = np.hstack([cat_oh, num_feats]).astype(np.float32)
# Align feature dimension with what the trained GAT expects.
# If, for any reason (e.g. slightly different category set), the computed
# feature dimension does not match IN_CHANNELS, we truncate or pad with
# zeros so that matmul shapes are always valid.
if IN_CHANNELS is not None and x.shape[1] != IN_CHANNELS:
if x.shape[1] > IN_CHANNELS:
x = x[:, :IN_CHANNELS]
else:
pad_width = IN_CHANNELS - x.shape[1]
x = np.hstack([x, np.zeros((x.shape[0], pad_width), dtype=x.dtype)])
return coords, x, anns
def nx_to_pyg_list(nx_graphs):
pyg_list = []
for G in nx_graphs:
x_vals = []
for n in sorted(G.nodes):
v = G.nodes[n]["x"]
if isinstance(v, torch.Tensor):
x_vals.append(v.cpu().numpy())
else:
x_vals.append(np.array(v))
x = torch.tensor(np.stack(x_vals, axis=0), dtype=torch.float)
edges = list(G.edges)
if len(edges) == 0:
edge_index = torch.empty((2, 0), dtype=torch.long)
edge_attr = torch.empty((0, 1), dtype=torch.float)
else:
edge_index = torch.tensor(edges, dtype=torch.long).t().contiguous()
edge_attr = (
torch.tensor(
[G[u][v].get("weight", 1.0) for u, v in edges],
dtype=torch.float,
).unsqueeze(1)
)
y = torch.tensor([G.graph.get("y", 0)], dtype=torch.long)
data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr, y=y)
data.img_id = G.graph.get("img_id", None)
data.file_name = G.graph.get("file_name", None)
pyg_list.append(data)
return pyg_list
def build_graph_for_filename(fname: str):
"""
Build a single-graph PyG Data object for a given image filename.
The image must exist in the H_100X_C2 train or test JSON.
"""
train_match = None
for img_id, img in IMAGES.items():
if img.get("file_name") == fname:
train_match = ("train", img_id)
break
if train_match is not None:
_, img_id = train_match
anns = ANN_BY_IMAGE.get(img_id, [])
else:
test_match = None
for t_id, t_img in TEST_IMAGES.items():
if t_img.get("file_name") == fname:
test_match = ("test", t_id)
break
if test_match is None:
return None
_, img_id = test_match
anns = ANN_BY_IMAGE_TEST.get(img_id, [])
if len(anns) == 0:
return None
coords, x, anns_for_img = build_nodes_and_features(anns)
if coords is None or x is None or coords.shape[0] == 0:
return None
n = coords.shape[0]
dists = euclidean_distances(coords, coords)
G = nx.Graph()
for i in range(n):
G.add_node(
i,
x=x[i],
pos_coords=coords[i],
category=anns_for_img[i].get("category_name", "unknown"),
cell_size=anns_for_img[i]["cell_size"],
)
k = min(K_KNN, max(1, n - 1))
for i in range(n):
order = np.argsort(dists[i])
nbrs = order[1 : k + 1]
for j in nbrs:
if i == j:
continue
w = 1.0 / (dists[i, j] + EPS)
mult = (
1.0
if anns_for_img[i].get("category_name")
== anns_for_img[j].get("category_name")
else 0.5
)
w *= mult
G.add_edge(i, j, weight=w)
data_list = nx_to_pyg_list([G])
if not data_list:
return None
return data_list[0]
def predict_aml(image_path: str) -> Tuple[str, float]:
"""
Gradio callback: given an image path, predict AML vs non-AML and confidence.
"""
try:
if MODEL is None:
return LOAD_MESSAGE, 0.0
if not DATA_READY:
return (
"Dataset annotations are not available inside this Space/container. "
"Please place `train.json` and `test.json` in the same folder as `app.py`,\n"
"or set DATA_BASE so that `<DATA_BASE>/train.json` and `<DATA_BASE>/test.json` exist.",
0.0,
)
if not image_path:
return "No image provided.", 0.0
fname = os.path.basename(image_path)
data = build_graph_for_filename(fname)
if data is None:
msg = (
f"No annotations/graph found for file '{fname}'. "
"Please upload an image that exists in the H_100X_C2 dataset (train/test)."
)
return msg, 0.0
data = data.to(DEVICE)
batch_index = torch.zeros(data.x.size(0), dtype=torch.long, device=DEVICE)
with torch.no_grad():
logits = MODEL(data.x, data.edge_index, batch_index)
probs = torch.softmax(logits, dim=-1).cpu().numpy()[0]
pred_idx = int(np.argmax(probs))
label = "AML" if pred_idx == 1 else "ALL"
confidence = float(probs[pred_idx])
result_text = f"Prediction: {label} (confidence {confidence:.3f})"
return result_text, confidence
except Exception as e:
import traceback
tb = traceback.format_exc()
return f"Internal error during prediction:\n{e}\n\n{tb}", 0.0
demo = gr.Interface(
fn=predict_aml,
inputs=gr.Image(type="filepath", label="Upload blood smear image"),
outputs=[
gr.Textbox(label="Prediction / Status"),
gr.Number(label="Confidence (placeholder)"),
],
title="AML vs non-AML GAT Demo (Docker stub)",
description=(
"This Gradio app loads the trained GAT model and is ready for deployment in Docker. "
"Extend the predict_stub function with the full graph-construction pipeline from gat2.ipynb."
),
)
if __name__ == "__main__":
print(LOAD_MESSAGE)
# Hugging Face Spaces provides its own public URL; share=True is not supported there.
# We keep show_api=False to avoid API schema generation issues across versions.
is_spaces = bool(os.environ.get("SPACE_ID") or os.environ.get("HF_SPACE_ID") or os.environ.get("SYSTEM") == "spaces")
share = False if is_spaces else bool(os.environ.get("GRADIO_SHARE", "0") == "1")
demo.launch(
server_name="0.0.0.0",
server_port=int(os.environ.get("PORT", "7860")),
share=share,
show_api=False,
)