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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from collections import defaultdict
4
+ from typing import Tuple
5
+
6
+ import gradio as gr
7
+ import networkx as nx
8
+ import numpy as np
9
+ import torch
10
+ from sklearn.metrics.pairwise import euclidean_distances
11
+ from sklearn.preprocessing import OneHotEncoder, StandardScaler
12
+ from torch_geometric.data import Data
13
+
14
+
15
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
16
+ # Actual input feature dimension that the trained GAT expects.
17
+ IN_CHANNELS: int | None = None
18
+
19
+
20
+ def load_model(model_path: str) -> torch.nn.Module:
21
+ """
22
+ Load the trained GAT model from disk.
23
+
24
+ This mirrors the GATClassifier architecture in gat2.ipynb, but it
25
+ infers the correct input feature dimension (in_channels) directly
26
+ from the checkpoint to avoid size mismatch errors.
27
+ """
28
+ from torch import nn
29
+ from torch_geometric.nn import GATConv, global_add_pool
30
+
31
+ # Load the state dict first so we can inspect conv1.lin.weight
32
+ state = torch.load(model_path, map_location=DEVICE)
33
+ conv1_weight = state.get("conv1.lin.weight")
34
+ if conv1_weight is None:
35
+ raise KeyError("conv1.lin.weight not found in checkpoint; cannot infer in_channels.")
36
+
37
+ # For GATConv, conv1.lin.weight has shape [heads * out_channels, in_channels]
38
+ inferred_in_channels = int(conv1_weight.shape[1])
39
+
40
+ # Remember the expected input feature dimension globally so that we can
41
+ # align any computed node features with what the model expects.
42
+ global IN_CHANNELS
43
+ IN_CHANNELS = inferred_in_channels
44
+
45
+ class GATClassifier(nn.Module):
46
+ def __init__(
47
+ self,
48
+ in_channels: int,
49
+ hidden_channels: int = 64,
50
+ num_classes: int = 2,
51
+ dropout: float = 0.5,
52
+ heads: int = 1,
53
+ ) -> None:
54
+ super().__init__()
55
+ self.conv1 = GATConv(in_channels, hidden_channels, heads=heads, dropout=dropout, concat=True)
56
+ out_dim = hidden_channels * heads
57
+ self.conv2 = GATConv(out_dim, hidden_channels, heads=heads, dropout=dropout, concat=True)
58
+ out_dim2 = hidden_channels * heads
59
+ self.dropout = nn.Dropout(dropout)
60
+ self.lin1 = nn.Linear(out_dim2 * 2, out_dim2 * 2)
61
+ self.lin2 = nn.Linear(out_dim2 * 2, num_classes)
62
+
63
+ def forward(self, x, edge_index, batch):
64
+ import torch.nn.functional as F
65
+
66
+ h1 = self.conv1(x, edge_index)
67
+ h1 = F.elu(h1)
68
+ h2 = self.conv2(h1, edge_index)
69
+ h2 = F.elu(h2)
70
+ g1 = global_add_pool(h1, batch)
71
+ g2 = global_add_pool(h2, batch)
72
+ h = torch.cat([g1, g2], dim=1)
73
+ h = self.lin1(h)
74
+ h = F.elu(h)
75
+ h = self.dropout(h)
76
+ h = self.lin2(h)
77
+ return h
78
+
79
+ # Allow an override via env var, but default to the inferred value
80
+ env_override = os.environ.get("GAT_IN_CHANNELS")
81
+ if env_override is not None:
82
+ try:
83
+ in_channels = int(env_override)
84
+ except ValueError:
85
+ in_channels = inferred_in_channels
86
+ else:
87
+ in_channels = inferred_in_channels
88
+
89
+ model = GATClassifier(
90
+ in_channels=in_channels,
91
+ hidden_channels=64,
92
+ num_classes=2,
93
+ dropout=0.5,
94
+ heads=1,
95
+ ).to(DEVICE)
96
+
97
+ model.load_state_dict(state)
98
+ model.eval()
99
+ return model
100
+
101
+
102
+ def load_gat_model() -> Tuple[torch.nn.Module, str]:
103
+ """
104
+ Load the GAT model from a path that can be configured via environment variable.
105
+
106
+ Priority:
107
+ 1. MODEL_PATH env var
108
+ 2. ./models/gat_best.pt inside the container
109
+ 3. ./gat_best.pt in the working directory
110
+ """
111
+ candidate_paths = []
112
+
113
+ env_path = os.environ.get("MODEL_PATH")
114
+ if env_path:
115
+ candidate_paths.append(env_path)
116
+
117
+ candidate_paths.append(os.path.join("models", "gat_best.pt"))
118
+ candidate_paths.append("gat_best.pt")
119
+
120
+ for p in candidate_paths:
121
+ if p and os.path.exists(p):
122
+ model = load_model(p)
123
+ return model, os.path.abspath(p)
124
+
125
+ raise FileNotFoundError(
126
+ "Could not find a trained GAT model. "
127
+ "Set MODEL_PATH or mount a gat_best.pt file into ./models/gat_best.pt."
128
+ )
129
+
130
+
131
+ try:
132
+ MODEL, MODEL_PATH = load_gat_model()
133
+ LOAD_MESSAGE = f"Loaded GAT model from: {MODEL_PATH}"
134
+ except Exception as exc:
135
+ MODEL, MODEL_PATH = None, ""
136
+ LOAD_MESSAGE = f"Failed to load model: {exc}"
137
+
138
+
139
+ # ==============================
140
+ # Dataset + graph construction (ported from gat2.ipynb)
141
+ # ==============================
142
+
143
+ """
144
+ Gradio app for AML vs ALL classification using a GAT model trained on H_100X_C2.
145
+
146
+ IMPORTANT: At runtime we need the dataset annotation JSON files. By default we
147
+ assume they live next to this file (in the same folder as `app.py`):
148
+
149
+ train.json
150
+ test.json
151
+
152
+ You can override the root folder with the DATA_BASE environment variable so that:
153
+
154
+ <DATA_BASE>/train.json
155
+ <DATA_BASE>/test.json
156
+
157
+ exist.
158
+ """
159
+
160
+ # Base path to the dataset annotations.
161
+ # Resolution priority:
162
+ # 1) DATA_BASE env var (if set)
163
+ # 2) Same folder as this file (default)
164
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
165
+
166
+
167
+ def _resolve_data_base() -> str:
168
+ env_base = os.environ.get("DATA_BASE")
169
+ if env_base:
170
+ return env_base
171
+ # Default: same folder as app.py; expects ./train.json and ./test.json
172
+ return BASE_DIR
173
+
174
+
175
+ DATA_BASE = _resolve_data_base()
176
+
177
+ TRAIN_JSON = os.path.join(DATA_BASE, "train.json")
178
+ TEST_JSON = os.path.join(DATA_BASE, "test.json")
179
+ CLEAN_IMPUTED_JSON = os.path.join(DATA_BASE, "train_clean_imputed.json")
180
+
181
+ # Numeric feature columns from the notebook
182
+ NUM_COLS = [
183
+ "cell_size",
184
+ "nuclear_chromatio",
185
+ "nuclear_shape",
186
+ "nucleolus",
187
+ "cytoplasm",
188
+ "cytoplasmic_basophilia",
189
+ "cytoplasmic_vacuoles",
190
+ ]
191
+
192
+
193
+ def _load_train_annotations():
194
+ """
195
+ Load train annotations (prefer cleaned/imputed JSON if present),
196
+ and build encoders/scalers for node features as in gat2.ipynb.
197
+ """
198
+ source_path = CLEAN_IMPUTED_JSON if os.path.exists(CLEAN_IMPUTED_JSON) else TRAIN_JSON
199
+ if not os.path.exists(source_path):
200
+ raise FileNotFoundError(
201
+ f"Could not find train annotations at {source_path}. "
202
+ "Place `train.json` next to `app.py` or set DATA_BASE so that "
203
+ "`<DATA_BASE>/train.json` exists."
204
+ )
205
+
206
+ with open(source_path, "r") as f:
207
+ cj = json.load(f)
208
+
209
+ images_local = {img["id"]: img for img in cj["images"]}
210
+ ann_by_image_local = defaultdict(list)
211
+ for ann in cj["annotations"]:
212
+ ann_by_image_local[ann["image_id"]].append(ann)
213
+
214
+ def get_aml_all_label_from_fname(fname: str):
215
+ f = fname.lower()
216
+ is_aml = "_aml" in f
217
+ is_all = "_all" in f
218
+ if is_aml and not is_all:
219
+ return 1
220
+ if is_all and not is_aml:
221
+ return 0
222
+ return None
223
+
224
+ labels_map = {}
225
+ for img_id, img in images_local.items():
226
+ lbl = get_aml_all_label_from_fname(img["file_name"])
227
+ if lbl is not None:
228
+ labels_map[img_id] = lbl
229
+
230
+ selected_image_ids = sorted(labels_map.keys())
231
+
232
+ cat_list: list[str] = []
233
+ num_list: list[list[float]] = []
234
+ for img_id in selected_image_ids:
235
+ for a in ann_by_image_local.get(img_id, []):
236
+ cat_list.append(a.get("category_name", "unknown"))
237
+ num_list.append([a.get(c) for c in NUM_COLS])
238
+
239
+ cat_unique = sorted(set(cat_list))
240
+ oh_local = OneHotEncoder(sparse_output=False, handle_unknown="ignore")
241
+ oh_local.fit(np.array(cat_unique).reshape(-1, 1))
242
+
243
+ num_arr = np.array(num_list, dtype=float)
244
+ num_arr[num_arr == 4.0] = np.nan
245
+ col_meds_local = np.nanmedian(num_arr, axis=0)
246
+ inds = np.where(np.isnan(num_arr))
247
+ for r, c in zip(*inds):
248
+ num_arr[r, c] = col_meds_local[c] if not np.isnan(col_meds_local[c]) else 0.0
249
+
250
+ scaler_local = StandardScaler()
251
+ scaler_local.fit(num_arr)
252
+
253
+ return images_local, ann_by_image_local, oh_local, scaler_local, col_meds_local
254
+
255
+
256
+ def _load_test_annotations():
257
+ if not os.path.exists(TEST_JSON):
258
+ raise FileNotFoundError(
259
+ f"Could not find test annotations at {TEST_JSON}. "
260
+ "Place `test.json` next to `app.py` or set DATA_BASE so that "
261
+ "`<DATA_BASE>/test.json` exists."
262
+ )
263
+ with open(TEST_JSON, "r") as f:
264
+ tj = json.load(f)
265
+ test_images_local = {img["id"]: img for img in tj["images"]}
266
+ ann_by_image_test_local = defaultdict(list)
267
+ for ann in tj["annotations"]:
268
+ ann_by_image_test_local[ann["image_id"]].append(ann)
269
+ return test_images_local, ann_by_image_test_local
270
+
271
+
272
+ try:
273
+ IMAGES, ANN_BY_IMAGE, OH, SCALER, COL_MEDS = _load_train_annotations()
274
+ TEST_IMAGES, ANN_BY_IMAGE_TEST = _load_test_annotations()
275
+ DATA_READY = True
276
+ DATA_ERROR_MSG = ""
277
+ except FileNotFoundError as e:
278
+ # Dataset not present inside the container / Space.
279
+ IMAGES = ANN_BY_IMAGE = OH = SCALER = COL_MEDS = None
280
+ TEST_IMAGES = ANN_BY_IMAGE_TEST = None
281
+ DATA_READY = False
282
+ DATA_ERROR_MSG = str(e)
283
+
284
+ K_KNN = 6
285
+ EPS = 1e-6
286
+
287
+
288
+ def build_nodes_and_features(anns):
289
+ """
290
+ Build node coordinates + feature matrix for a list of annotations,
291
+ using the same preprocessing as in gat2.ipynb.
292
+ """
293
+ coords, cats, num_feats = [], [], []
294
+ for a in anns:
295
+ x_bbox, y_bbox, w, h = a["bbox"]
296
+ cx = x_bbox + w / 2.0
297
+ cy = y_bbox + h / 2.0
298
+ coords.append([cx, cy])
299
+ cats.append([a.get("category_name", "unknown")])
300
+
301
+ raw_vals = [a.get(c) for c in NUM_COLS]
302
+ cleaned = []
303
+ for i, v in enumerate(raw_vals):
304
+ if v is None or v == 4:
305
+ cleaned.append(np.nan)
306
+ else:
307
+ try:
308
+ cleaned.append(float(v))
309
+ except (TypeError, ValueError):
310
+ cleaned.append(np.nan)
311
+ nf = [COL_MEDS[i] if np.isnan(v) else v for i, v in enumerate(cleaned)]
312
+ num_feats.append(nf)
313
+
314
+ if not coords:
315
+ return None, None, None
316
+
317
+ coords = np.array(coords, dtype=float)
318
+ num_feats = np.array(num_feats, dtype=float)
319
+ num_feats = SCALER.transform(num_feats)
320
+ cat_oh = OH.transform(np.array(cats))
321
+
322
+ x = np.hstack([cat_oh, num_feats]).astype(np.float32)
323
+
324
+ # Align feature dimension with what the trained GAT expects.
325
+ # If, for any reason (e.g. slightly different category set), the computed
326
+ # feature dimension does not match IN_CHANNELS, we truncate or pad with
327
+ # zeros so that matmul shapes are always valid.
328
+ if IN_CHANNELS is not None and x.shape[1] != IN_CHANNELS:
329
+ if x.shape[1] > IN_CHANNELS:
330
+ x = x[:, :IN_CHANNELS]
331
+ else:
332
+ pad_width = IN_CHANNELS - x.shape[1]
333
+ x = np.hstack([x, np.zeros((x.shape[0], pad_width), dtype=x.dtype)])
334
+
335
+ return coords, x, anns
336
+
337
+
338
+ def nx_to_pyg_list(nx_graphs):
339
+ pyg_list = []
340
+ for G in nx_graphs:
341
+ x_vals = []
342
+ for n in sorted(G.nodes):
343
+ v = G.nodes[n]["x"]
344
+ if isinstance(v, torch.Tensor):
345
+ x_vals.append(v.cpu().numpy())
346
+ else:
347
+ x_vals.append(np.array(v))
348
+ x = torch.tensor(np.stack(x_vals, axis=0), dtype=torch.float)
349
+
350
+ edges = list(G.edges)
351
+ if len(edges) == 0:
352
+ edge_index = torch.empty((2, 0), dtype=torch.long)
353
+ edge_attr = torch.empty((0, 1), dtype=torch.float)
354
+ else:
355
+ edge_index = torch.tensor(edges, dtype=torch.long).t().contiguous()
356
+ edge_attr = (
357
+ torch.tensor(
358
+ [G[u][v].get("weight", 1.0) for u, v in edges],
359
+ dtype=torch.float,
360
+ ).unsqueeze(1)
361
+ )
362
+
363
+ y = torch.tensor([G.graph.get("y", 0)], dtype=torch.long)
364
+ data = Data(x=x, edge_index=edge_index, edge_attr=edge_attr, y=y)
365
+ data.img_id = G.graph.get("img_id", None)
366
+ data.file_name = G.graph.get("file_name", None)
367
+ pyg_list.append(data)
368
+ return pyg_list
369
+
370
+
371
+ def build_graph_for_filename(fname: str):
372
+ """
373
+ Build a single-graph PyG Data object for a given image filename.
374
+
375
+ The image must exist in the H_100X_C2 train or test JSON.
376
+ """
377
+ train_match = None
378
+ for img_id, img in IMAGES.items():
379
+ if img.get("file_name") == fname:
380
+ train_match = ("train", img_id)
381
+ break
382
+
383
+ if train_match is not None:
384
+ _, img_id = train_match
385
+ anns = ANN_BY_IMAGE.get(img_id, [])
386
+ else:
387
+ test_match = None
388
+ for t_id, t_img in TEST_IMAGES.items():
389
+ if t_img.get("file_name") == fname:
390
+ test_match = ("test", t_id)
391
+ break
392
+ if test_match is None:
393
+ return None
394
+ _, img_id = test_match
395
+ anns = ANN_BY_IMAGE_TEST.get(img_id, [])
396
+
397
+ if len(anns) == 0:
398
+ return None
399
+
400
+ coords, x, anns_for_img = build_nodes_and_features(anns)
401
+ if coords is None or x is None or coords.shape[0] == 0:
402
+ return None
403
+
404
+ n = coords.shape[0]
405
+ dists = euclidean_distances(coords, coords)
406
+ G = nx.Graph()
407
+
408
+ for i in range(n):
409
+ G.add_node(
410
+ i,
411
+ x=x[i],
412
+ pos_coords=coords[i],
413
+ category=anns_for_img[i].get("category_name", "unknown"),
414
+ cell_size=anns_for_img[i]["cell_size"],
415
+ )
416
+
417
+ k = min(K_KNN, max(1, n - 1))
418
+ for i in range(n):
419
+ order = np.argsort(dists[i])
420
+ nbrs = order[1 : k + 1]
421
+ for j in nbrs:
422
+ if i == j:
423
+ continue
424
+ w = 1.0 / (dists[i, j] + EPS)
425
+ mult = (
426
+ 1.0
427
+ if anns_for_img[i].get("category_name")
428
+ == anns_for_img[j].get("category_name")
429
+ else 0.5
430
+ )
431
+ w *= mult
432
+ G.add_edge(i, j, weight=w)
433
+
434
+ data_list = nx_to_pyg_list([G])
435
+ if not data_list:
436
+ return None
437
+ return data_list[0]
438
+
439
+
440
+ def predict_aml(image_path: str) -> Tuple[str, float]:
441
+ """
442
+ Gradio callback: given an image path, predict AML vs non-AML and confidence.
443
+ """
444
+ try:
445
+ if MODEL is None:
446
+ return LOAD_MESSAGE, 0.0
447
+
448
+ if not DATA_READY:
449
+ return (
450
+ "Dataset annotations are not available inside this Space/container. "
451
+ "Please place `train.json` and `test.json` in the same folder as `app.py`,\n"
452
+ "or set DATA_BASE so that `<DATA_BASE>/train.json` and `<DATA_BASE>/test.json` exist.",
453
+ 0.0,
454
+ )
455
+
456
+ if not image_path:
457
+ return "No image provided.", 0.0
458
+
459
+ fname = os.path.basename(image_path)
460
+ data = build_graph_for_filename(fname)
461
+ if data is None:
462
+ msg = (
463
+ f"No annotations/graph found for file '{fname}'. "
464
+ "Please upload an image that exists in the H_100X_C2 dataset (train/test)."
465
+ )
466
+ return msg, 0.0
467
+
468
+ data = data.to(DEVICE)
469
+ batch_index = torch.zeros(data.x.size(0), dtype=torch.long, device=DEVICE)
470
+
471
+ with torch.no_grad():
472
+ logits = MODEL(data.x, data.edge_index, batch_index)
473
+ probs = torch.softmax(logits, dim=-1).cpu().numpy()[0]
474
+
475
+ pred_idx = int(np.argmax(probs))
476
+ label = "AML" if pred_idx == 1 else "ALL"
477
+ confidence = float(probs[pred_idx])
478
+
479
+ result_text = f"Prediction: {label} (confidence {confidence:.3f})"
480
+ return result_text, confidence
481
+ except Exception as e:
482
+ import traceback
483
+
484
+ tb = traceback.format_exc()
485
+ return f"Internal error during prediction:\n{e}\n\n{tb}", 0.0
486
+
487
+
488
+ demo = gr.Interface(
489
+ fn=predict_aml,
490
+ inputs=gr.Image(type="filepath", label="Upload blood smear image"),
491
+ outputs=[
492
+ gr.Textbox(label="Prediction / Status"),
493
+ gr.Number(label="Confidence (placeholder)"),
494
+ ],
495
+ title="AML vs non-AML GAT Demo (Docker stub)",
496
+ description=(
497
+ "This Gradio app loads the trained GAT model and is ready for deployment in Docker. "
498
+ "Extend the predict_stub function with the full graph-construction pipeline from gat2.ipynb."
499
+ ),
500
+ )
501
+
502
+
503
+ if __name__ == "__main__":
504
+ print(LOAD_MESSAGE)
505
+ # Hugging Face Spaces provides its own public URL; share=True is not supported there.
506
+ # We keep show_api=False to avoid API schema generation issues across versions.
507
+ is_spaces = bool(os.environ.get("SPACE_ID") or os.environ.get("HF_SPACE_ID") or os.environ.get("SYSTEM") == "spaces")
508
+ share = False if is_spaces else bool(os.environ.get("GRADIO_SHARE", "0") == "1")
509
+ demo.launch(
510
+ server_name="0.0.0.0",
511
+ server_port=int(os.environ.get("PORT", "7860")),
512
+ share=share,
513
+ show_api=False,
514
+ )
515
+
gat_best.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7b4f875440c87f13ea07527a49c12b3d27ae2a3ca45c5bf9ae2276a2801420ba
3
+ size 94609