LiangLabUMB commited on
Commit
a58fce7
Β·
verified Β·
1 Parent(s): ceb77c3

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +1636 -0
app.py ADDED
@@ -0,0 +1,1636 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ from cellpose import models
4
+ import numpy as np
5
+ import cv2
6
+ import matplotlib.pyplot as plt
7
+ import tempfile
8
+ from PIL import Image, ImageDraw
9
+ import io
10
+ from huggingface_hub import hf_hub_download
11
+ import base64
12
+ from concurrent.futures import ThreadPoolExecutor, as_completed
13
+ import csv
14
+ import joblib
15
+ import os
16
+
17
+ HF_REPO_ID = "myang4218/cellposemodel"
18
+ HF_REPO_ID2 = "LiangLabUMB/viability_model"
19
+ MODEL_OPTIONS = {
20
+ "Hemocytometer Model": "hemocytometermodel.npy",
21
+ "General Model": "generalmodel.npy"
22
+ }
23
+
24
+ loaded_models = {}
25
+
26
+ VIABILITY_CLF = None
27
+ VIABILITY_SCALER = None
28
+
29
+ try:
30
+ _clf_path = hf_hub_download(repo_id=HF_REPO_ID2, filename="viability_clf.pkl")
31
+ _scaler_path = hf_hub_download(repo_id=HF_REPO_ID2, filename="viability_scaler.pkl")
32
+ VIABILITY_CLF = joblib.load(_clf_path)
33
+ VIABILITY_SCALER = joblib.load(_scaler_path)
34
+ print("βœ“ Viability classifier loaded.")
35
+ except Exception as e:
36
+ print(f"Viability classifier not found or failed to load: {e}")
37
+
38
+ # ---- mobile-safe size limits (aggressive for Safari) ----
39
+ MAX_SIDE = 1024
40
+ MAX_PIXELS = 1024 * 1024
41
+
42
+
43
+ def safe_resize(image_np):
44
+ """
45
+ Downscale image to fit within MAX_SIDE and MAX_PIXELS while
46
+ preserving aspect ratio. Works for RGB / RGBA / grayscale.
47
+ """
48
+ h, w = image_np.shape[:2]
49
+ total = h * w
50
+
51
+ if max(h, w) <= MAX_SIDE and total <= MAX_PIXELS:
52
+ return image_np
53
+
54
+ # compute scale
55
+ scale_side = MAX_SIDE / max(h, w)
56
+ scale_pixels = (MAX_PIXELS / total) ** 0.5
57
+ scale = min(scale_side, scale_pixels)
58
+
59
+ new_w = max(1, int(w * scale))
60
+ new_h = max(1, int(h * scale))
61
+
62
+ return cv2.resize(image_np, (new_w, new_h), interpolation=cv2.INTER_AREA)
63
+
64
+
65
+ def draw_exclusion_overlay(image_np, left_width_pct, top_width_pct):
66
+
67
+ h, w = image_np.shape[:2]
68
+
69
+ # Convert to PIL for drawing
70
+ img_pil = Image.fromarray(image_np)
71
+ draw = ImageDraw.Draw(img_pil, 'RGBA')
72
+
73
+ # Calculate pixel widths from percentages
74
+ left_px = int(w * left_width_pct / 100)
75
+ top_px = int(h * top_width_pct / 100)
76
+
77
+ # Draw overlays for exclusion zones
78
+ if left_px > 0:
79
+ # Left exclusion zone
80
+ draw.rectangle(
81
+ [(0, 0), (left_px, h)],
82
+ fill=(255, 0, 0, 80) # Semi-transparent red
83
+ )
84
+ # border line
85
+ draw.line([(left_px, 0), (left_px, h)], fill=(255, 0, 0, 255), width=3)
86
+
87
+ if top_px > 0:
88
+ # Top exclusion zone
89
+ draw.rectangle(
90
+ [(0, 0), (w, top_px)],
91
+ fill=(255, 0, 0, 80) # Semi-transparent red
92
+ )
93
+ # border line
94
+ draw.line([(0, top_px), (w, top_px)], fill=(255, 0, 0, 255), width=3)
95
+
96
+ return np.array(img_pil)
97
+
98
+
99
+ def apply_stereological_exclusion(masks, left_width_pct, top_width_pct):
100
+ h, w = masks.shape
101
+
102
+ # Calculate pixel widths from percentages
103
+ left_px = int(w * left_width_pct / 100)
104
+ top_px = int(h * top_width_pct / 100)
105
+
106
+ filtered_masks = masks.copy()
107
+ cell_ids = np.unique(masks)
108
+ cell_ids = cell_ids[cell_ids > 0]
109
+
110
+ excluded_cells = []
111
+ included_cells = []
112
+
113
+ for cell_id in cell_ids:
114
+ cell_mask = (masks == cell_id)
115
+
116
+ # Get cell boundary coordinates
117
+ rows, cols = np.where(cell_mask)
118
+
119
+ # Check if cell touches left exclusion zone
120
+ touches_left = np.any(cols < left_px) if left_px > 0 else False
121
+
122
+ # Check if cell touches top exclusion zone
123
+ touches_top = np.any(rows < top_px) if top_px > 0 else False
124
+
125
+ # Exclude if touching left or top
126
+ if touches_left or touches_top:
127
+ filtered_masks[cell_mask] = 0
128
+ excluded_cells.append(cell_id)
129
+ else:
130
+ included_cells.append(cell_id)
131
+
132
+ # Renumber remaining cells
133
+ unique_ids = np.unique(filtered_masks)
134
+ unique_ids = unique_ids[unique_ids > 0]
135
+
136
+ renumbered_masks = np.zeros_like(filtered_masks)
137
+ for new_id, old_id in enumerate(unique_ids, start=1):
138
+ renumbered_masks[filtered_masks == old_id] = new_id
139
+
140
+ return renumbered_masks, len(excluded_cells), len(included_cells)
141
+
142
+
143
+
144
+ FEATURE_COLS_INFERENCE = [
145
+ "mean_r", "mean_g", "mean_b", "std_r", "std_g", "std_b",
146
+ "mean_h", "mean_s", "mean_v", "std_s", "std_v",
147
+ "blue_red_ratio", "blue_green_ratio", "rg_ratio",
148
+ "inner_brightness", "peak_brightness",
149
+ "bright_spot_fraction", "ring_darkness",
150
+ "centre_periphery_ratio", "brightness_std_normalised",
151
+ ]
152
+
153
+
154
+ def classify_cells_by_model(image_np, masks):
155
+ """
156
+ Run the trained LogisticRegression classifier to predict live/dead per cell.
157
+ Returns (dead_count, alive_count, overlay_np, {cell_id: label}).
158
+ Requires VIABILITY_CLF and VIABILITY_SCALER to be loaded.
159
+ """
160
+ import numpy as np
161
+ cell_ids = np.unique(masks)
162
+ cell_ids = cell_ids[cell_ids > 0]
163
+ if len(cell_ids) == 0:
164
+ return 0, 0, image_np.copy(), {}
165
+
166
+ features = extract_cell_features(image_np, masks)
167
+ if not features:
168
+ return 0, 0, image_np.copy(), {}
169
+
170
+ import numpy as np
171
+ X = np.array([[f[c] for c in FEATURE_COLS_INFERENCE] for f in features], dtype=np.float32)
172
+
173
+ # replace any NaN/Inf with column median
174
+ for j in range(X.shape[1]):
175
+ bad = ~np.isfinite(X[:, j])
176
+ if bad.any():
177
+ X[bad, j] = float(np.nanmedian(X[:, j]))
178
+
179
+ X_scaled = VIABILITY_SCALER.transform(X)
180
+ predictions = VIABILITY_CLF.predict(X_scaled) # 0=live, 1=dead
181
+
182
+ label_map = {int(f["cell_id"]): int(p) for f, p in zip(features, predictions)}
183
+ overlay = draw_viability_overlay(image_np, masks, label_map)
184
+
185
+ dead = int(sum(predictions))
186
+ alive = int(len(predictions) - dead)
187
+ return dead, alive, overlay, label_map
188
+
189
+
190
+ def draw_viability_overlay(image_np, masks, label_map):
191
+ """
192
+ Draw coloured contours + cell-number labels onto image_np.
193
+ label_map: {cell_id: 0=live, 1=dead}
194
+ Returns a uint8 numpy array.
195
+ """
196
+ overlay = image_np.copy()
197
+ cell_ids = np.unique(masks)
198
+ cell_ids = cell_ids[cell_ids > 0]
199
+ cell_enum = {int(cid): idx + 1 for idx, cid in enumerate(sorted(cell_ids))}
200
+
201
+ for cid in cell_ids:
202
+ cid_int = int(cid)
203
+ label = label_map.get(cid_int, 0)
204
+ color = (220, 50, 50) if label == 1 else (50, 220, 80)
205
+ cell_mask = (masks == cid).astype(np.uint8)
206
+ contours, _ = cv2.findContours(cell_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
207
+ cv2.drawContours(overlay, contours, -1, color, thickness=2)
208
+
209
+ ys, xs = np.where(cell_mask)
210
+ if len(ys) > 0:
211
+ cx, cy = int(xs.mean()), int(ys.mean())
212
+ label_str = str(cell_enum[cid_int])
213
+ font = cv2.FONT_HERSHEY_SIMPLEX
214
+ font_scale = 0.35
215
+ thickness = 1
216
+ (tw, th), _ = cv2.getTextSize(label_str, font, font_scale, thickness)
217
+ cv2.rectangle(overlay,
218
+ (cx - tw//2 - 1, cy - th//2 - 1),
219
+ (cx + tw//2 + 1, cy + th//2 + 1),
220
+ (0, 0, 0), -1)
221
+ cv2.putText(overlay, label_str,
222
+ (cx - tw//2, cy + th//2),
223
+ font, font_scale, color, thickness, cv2.LINE_AA)
224
+ return overlay
225
+
226
+
227
+ def classify_cells_by_blueness(image_np, masks, threshold_bias):
228
+ """
229
+ Classify cells as dead (blue) or alive using an adaptive Otsu threshold
230
+ on per-cell blueness scores, with a user bias to fine-tune.
231
+
232
+ Args:
233
+ image_np: RGB image array
234
+ masks: Cellpose segmentation masks
235
+ threshold_bias: Slider value -50..+50; shifts Otsu threshold up/down.
236
+ Negative = more cells classified dead (looser).
237
+ Positive = fewer cells classified dead (stricter).
238
+ 0 = pure Otsu (fully automatic).
239
+
240
+ Returns:
241
+ dead_count, alive_count, colored_overlay, otsu_threshold, final_threshold
242
+ """
243
+
244
+ if len(image_np.shape) == 2:
245
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
246
+ elif len(image_np.shape) == 3 and image_np.shape[2] == 4:
247
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
248
+
249
+ hsv = cv2.cvtColor(image_np, cv2.COLOR_RGB2HSV)
250
+
251
+ hue = hsv[:, :, 0].astype(np.float32)
252
+ saturation = hsv[:, :, 1].astype(np.float32)
253
+
254
+ # Raw blueness: hue proximity to 115Β° Γ— saturation
255
+ hue_distance = np.minimum(np.abs(hue - 115), 180 - np.abs(hue - 115))
256
+ hue_score = np.maximum(0, 1 - hue_distance / 65)
257
+ blueness = hue_score * (saturation / 255.0)
258
+
259
+ # --- Compute per-cell mean blueness scores ---
260
+ cell_ids = np.unique(masks)
261
+ cell_ids = cell_ids[cell_ids > 0]
262
+
263
+ if len(cell_ids) == 0:
264
+ blank = image_np.copy()
265
+ return 0, 0, blank, 0.0, 0.0
266
+
267
+ cell_scores = np.array([np.mean(blueness[masks == cid]) for cid in cell_ids])
268
+
269
+ # --- Otsu on the distribution of per-cell scores ---
270
+ # cv2.threshold expects uint8; scale 0-1 β†’ 0-255
271
+ scores_u8 = (np.clip(cell_scores, 0, 1) * 255).astype(np.uint8)
272
+
273
+ if scores_u8.max() == scores_u8.min():
274
+ # All cells identical β†’ Otsu is undefined; use midpoint
275
+ otsu_threshold = float(scores_u8[0]) / 255.0
276
+ else:
277
+ # Reshape to a single-column image so cv2.threshold works
278
+ thresh_val, _ = cv2.threshold(
279
+ scores_u8.reshape(-1, 1), 0, 255,
280
+ cv2.THRESH_BINARY + cv2.THRESH_OTSU
281
+ )
282
+ otsu_threshold = thresh_val / 255.0
283
+
284
+ # --- Apply user bias: slider -50..+50 maps to Β±0.20 shift ---
285
+ bias = (threshold_bias / 50.0) * 0.20
286
+ final_threshold = float(np.clip(otsu_threshold + bias, 0.0, 1.0))
287
+
288
+ # --- Classify ---
289
+ dead_cells = [cid for cid, s in zip(cell_ids, cell_scores) if s > final_threshold]
290
+ alive_cells = [cid for cid, s in zip(cell_ids, cell_scores) if s <= final_threshold]
291
+
292
+ # --- Outline-only overlay on raw image with enumerated labels ---
293
+ final_overlay = image_np.copy()
294
+
295
+ # Compute a consistent enumeration order (cell_ids is already sorted ascending)
296
+ cell_enum = {cid: idx + 1 for idx, cid in enumerate(cell_ids)}
297
+
298
+ dead_set = set(dead_cells)
299
+ alive_set = set(alive_cells)
300
+
301
+ for cid in cell_ids:
302
+ cell_mask = (masks == cid).astype(np.uint8)
303
+ contours, _ = cv2.findContours(cell_mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
304
+ color = (220, 50, 50) if cid in dead_set else (50, 220, 80)
305
+ cv2.drawContours(final_overlay, contours, -1, color, thickness=2)
306
+
307
+ # Draw enumeration label at centroid
308
+ ys, xs = np.where(cell_mask)
309
+ if len(ys) > 0:
310
+ cx, cy = int(xs.mean()), int(ys.mean())
311
+ label_str = str(cell_enum[cid])
312
+ font = cv2.FONT_HERSHEY_SIMPLEX
313
+ font_scale = 0.35
314
+ thickness = 1
315
+ (tw, th), _ = cv2.getTextSize(label_str, font, font_scale, thickness)
316
+ # Dark background rectangle for readability
317
+ cv2.rectangle(
318
+ final_overlay,
319
+ (cx - tw // 2 - 1, cy - th // 2 - 1),
320
+ (cx + tw // 2 + 1, cy + th // 2 + 1),
321
+ (0, 0, 0),
322
+ -1
323
+ )
324
+ cv2.putText(
325
+ final_overlay, label_str,
326
+ (cx - tw // 2, cy + th // 2),
327
+ font, font_scale, color, thickness, cv2.LINE_AA
328
+ )
329
+
330
+ return len(dead_cells), len(alive_cells), final_overlay, otsu_threshold, final_threshold
331
+
332
+
333
+ def measure_confluency(masks, image_np):
334
+ tot_pixels = image_np.shape[0] * image_np.shape[1]
335
+ cell_pixels = np.count_nonzero(masks)
336
+ confluency = cell_pixels / tot_pixels * 100
337
+ return confluency
338
+
339
+ def filter_mask_by_size(masks, minimum_pixels):
340
+ filtered_masks = masks.copy()
341
+ cell_ids = np.unique(masks)
342
+ cell_ids = cell_ids[cell_ids > 0]
343
+
344
+ removed_count = 0
345
+
346
+ for cell_id in cell_ids:
347
+ cell_mask = (masks == cell_id)
348
+ cell_pixels = np.count_nonzero(cell_mask)
349
+ if cell_pixels < minimum_pixels:
350
+ filtered_masks[cell_mask] = 0
351
+ removed_count += 1
352
+
353
+ unique_ids = np.unique(filtered_masks)
354
+ unique_ids = unique_ids[unique_ids > 0]
355
+
356
+ renumbered_masks = np.zeros_like(filtered_masks)
357
+ for new_id, old_id in enumerate(unique_ids, start=1):
358
+ renumbered_masks[filtered_masks == old_id] = new_id
359
+
360
+ return renumbered_masks, removed_count
361
+
362
+
363
+ def filter_mask_by_maxsize(masks, maximum_pixels):
364
+ filtered_masks = masks.copy()
365
+ cell_ids = np.unique(masks)
366
+ cell_ids = cell_ids[cell_ids > 0]
367
+
368
+ removed_count = 0
369
+ for cell_id in cell_ids:
370
+ cell_mask = (masks == cell_id)
371
+ cell_pixels = np.count_nonzero(cell_mask)
372
+ if cell_pixels > maximum_pixels:
373
+ filtered_masks[cell_mask] = 0
374
+ removed_count += 1
375
+
376
+ unique_ids = np.unique(filtered_masks)
377
+ unique_ids = unique_ids[unique_ids > 0]
378
+
379
+ renumbered_masks = np.zeros_like(filtered_masks)
380
+ for new_id, old_id in enumerate(unique_ids, start=1):
381
+ renumbered_masks[filtered_masks == old_id] = new_id
382
+
383
+ return renumbered_masks, removed_count
384
+
385
+
386
+ def rec_min_size(masks, q=25):
387
+ ids = np.unique(masks)
388
+ ids = ids[ids > 0]
389
+ if len(ids) == 0:
390
+ return 0
391
+ sizes = np.array([np.count_nonzero(masks == cid) for cid in ids])
392
+ return int(round(np.percentile(sizes, q)))
393
+
394
+
395
+ def apply_polygon_mask(image_pil, points_json):
396
+ """
397
+ Given a PIL image and a JSON string of [[x,y],...] points,
398
+ zero out everything outside the polygon and return a PIL image.
399
+ """
400
+ import json
401
+ if not points_json or points_json.strip() in ("", "[]"):
402
+ return image_pil
403
+ try:
404
+ pts = json.loads(points_json)
405
+ except Exception:
406
+ return image_pil
407
+ if len(pts) < 3:
408
+ return image_pil
409
+
410
+ image_np = np.array(image_pil)
411
+ h, w = image_np.shape[:2]
412
+ poly = np.array(pts, dtype=np.int32)
413
+ poly[:, 0] = np.clip(poly[:, 0], 0, w - 1)
414
+ poly[:, 1] = np.clip(poly[:, 1], 0, h - 1)
415
+ mask = np.zeros((h, w), dtype=np.uint8)
416
+ cv2.fillPoly(mask, [poly], 255)
417
+ if len(image_np.shape) == 3:
418
+ result = np.where(mask[:, :, np.newaxis] == 255, image_np, 0).astype(np.uint8)
419
+ else:
420
+ result = np.where(mask == 255, image_np, 0).astype(np.uint8)
421
+ return Image.fromarray(result)
422
+
423
+ def order_quad(pts):
424
+ """
425
+ Order 4 points as (top-left, top-right, bottom-right, bottom-left).
426
+ Sorts by angle about the centroid so the result stays correct for
427
+ rotated quads, where the sum/difference heuristic breaks down.
428
+ """
429
+ pts = np.asarray(pts, dtype=np.float32)
430
+ centre = pts.mean(axis=0)
431
+ angles = np.arctan2(pts[:, 1] - centre[1], pts[:, 0] - centre[0])
432
+ # Clockwise on screen (y grows downward) == increasing angle here
433
+ ordered = pts[np.argsort(angles)]
434
+ # Rotate so the corner nearest the top-left of the quad comes first
435
+ start = np.argmin(ordered.sum(axis=1))
436
+ return np.roll(ordered, -start, axis=0)
437
+
438
+
439
+ def quad_output_size(points):
440
+ """
441
+ Width and height, in source pixels, of the rectangle a 4-point quad
442
+ warps to. Shared by the warp itself and the exclusion-zone preview so
443
+ the two can never disagree about the ROI's dimensions.
444
+ """
445
+ tl, tr, br, bl = order_quad(points)
446
+ out_w = max(1, int(round(max(np.linalg.norm(br - bl), np.linalg.norm(tr - tl)))))
447
+ out_h = max(1, int(round(max(np.linalg.norm(tr - br), np.linalg.norm(tl - bl)))))
448
+ return out_w, out_h
449
+
450
+
451
+ def warp_polygon_to_square(image_np, points):
452
+ src = order_quad(points)
453
+ out_w, out_h = quad_output_size(points)
454
+
455
+ dst = np.array(
456
+ [[0, 0],
457
+ [out_w - 1, 0],
458
+ [out_w - 1, out_h - 1],
459
+ [0, out_h - 1]],
460
+ dtype=np.float32)
461
+
462
+ M = cv2.getPerspectiveTransform(src, dst)
463
+ warped = cv2.warpPerspective(image_np, M, (out_w, out_h))
464
+ return warped
465
+
466
+
467
+ def toggle_stereological_mode(use_stereology):
468
+ """Show/hide stereological controls based on checkbox"""
469
+ return gr.update(visible=use_stereology)
470
+
471
+
472
+ def exclusion_pct_for_preview(image_shape, crop_points, left_pct, top_pct):
473
+ """
474
+ Exclusion percentages restated relative to the FULL image.
475
+
476
+ The exclusion zones are applied to the cropped/warped ROI, so a given
477
+ percentage covers far fewer pixels than the same percentage of the whole
478
+ upload. Rescaling by the ROI's dimensions lets the full-image preview draw
479
+ a band of the true width instead of a misleadingly wide one.
480
+ """
481
+ h, w = image_shape[:2]
482
+ if not crop_points or len(crop_points) != 4 or w == 0 or h == 0:
483
+ return left_pct, top_pct
484
+ out_w, out_h = quad_output_size(crop_points)
485
+ return left_pct * out_w / float(w), top_pct * out_h / float(h)
486
+
487
+
488
+ def update_exclusion_preview(image, left_width, top_width, crop_points=None):
489
+ """Update the preview image with exclusion zone overlay"""
490
+ if image is None:
491
+ return None
492
+
493
+ image_np = np.array(image)
494
+ left_shown, top_shown = exclusion_pct_for_preview(
495
+ image_np.shape, crop_points, left_width, top_width
496
+ )
497
+ overlay = draw_exclusion_overlay(image_np, left_shown, top_shown)
498
+ return Image.fromarray(overlay)
499
+
500
+
501
+ # ---------------------------------------------------------------------------
502
+ # Patch segmentation
503
+ # ---------------------------------------------------------------------------
504
+ PATCH_SIZE = 512 # target patch side length
505
+ PATCH_OVERLAP = 64 # overlap border on each edge (pixels)
506
+ MIN_PATCH_DIM = 256 # don't bother patching if image fits comfortably
507
+
508
+
509
+ def _split_patches(image_np, patch_size=PATCH_SIZE, overlap=PATCH_OVERLAP):
510
+ """
511
+ Split image into overlapping patches.
512
+ Returns list of (patch_np, row_start, col_start) tuples.
513
+ """
514
+ h, w = image_np.shape[:2]
515
+ patches = []
516
+ row = 0
517
+ while row < h:
518
+ row_end = min(row + patch_size, h)
519
+ col = 0
520
+ while col < w:
521
+ col_end = min(col + patch_size, w)
522
+ patch = image_np[row:row_end, col:col_end]
523
+ patches.append((patch, row, col))
524
+ if col_end == w:
525
+ break
526
+ col += patch_size - overlap
527
+ if row_end == h:
528
+ break
529
+ row += patch_size - overlap
530
+ return patches
531
+
532
+
533
+ def _merge_patch_masks(patch_results, full_h, full_w, overlap=PATCH_OVERLAP):
534
+ """
535
+ Stitch per-patch masks into a single full-image mask.
536
+
537
+ Strategy:
538
+ - Each patch gets a unique ID offset so cell IDs never collide.
539
+ - Patches are pasted into the canvas using a priority canvas that
540
+ gives interior pixels precedence over overlap-border pixels.
541
+ - After pasting, cells whose centroids fall in the overlap zone
542
+ of two adjacent patches are deduplicated: if two cells from
543
+ different patches share >50% IoU they are the same cell β€” keep
544
+ the one whose centroid is furthest from a patch edge.
545
+ """
546
+ full_mask = np.zeros((full_h, full_w), dtype=np.int32)
547
+ # track which patch_idx owns each pixel (used for overlap resolution)
548
+ owner_map = np.full((full_h, full_w), -1, dtype=np.int32)
549
+ # distance-to-nearest-edge for the owning patch (higher = more central)
550
+ priority = np.zeros((full_h, full_w), dtype=np.float32)
551
+
552
+ id_offset = 0
553
+ patch_meta = [] # (offset, row_start, col_start, patch_h, patch_w)
554
+
555
+ for patch_idx, (mask_patch, row_start, col_start) in enumerate(patch_results):
556
+ ph, pw = mask_patch.shape
557
+ # offset all non-zero IDs so they're globally unique
558
+ shifted = np.where(mask_patch > 0, mask_patch + id_offset, 0).astype(np.int32)
559
+
560
+ # compute per-pixel priority = min distance to any patch edge
561
+ rows_idx = np.arange(ph)
562
+ cols_idx = np.arange(pw)
563
+ dist_r = np.minimum(rows_idx, ph - 1 - rows_idx) # (ph,)
564
+ dist_c = np.minimum(cols_idx, pw - 1 - cols_idx) # (pw,)
565
+ pri_patch = np.minimum(dist_r[:, None], dist_c[None, :]) # (ph, pw)
566
+
567
+ roi_full = full_mask [row_start:row_start+ph, col_start:col_start+pw]
568
+ roi_owner = owner_map [row_start:row_start+ph, col_start:col_start+pw]
569
+ roi_pri = priority [row_start:row_start+ph, col_start:col_start+pw]
570
+
571
+ # where this patch has higher priority, overwrite
572
+ better = pri_patch > roi_pri
573
+ roi_full [better] = shifted [better]
574
+ roi_owner[better] = patch_idx
575
+ roi_pri [better] = pri_patch [better]
576
+
577
+ max_id = int(mask_patch.max())
578
+ patch_meta.append((id_offset, row_start, col_start, ph, pw))
579
+ id_offset += max_id + 1
580
+
581
+ # --- Renumber to compact sequential IDs ---
582
+ unique_ids = np.unique(full_mask)
583
+ unique_ids = unique_ids[unique_ids > 0]
584
+ renumbered = np.zeros_like(full_mask)
585
+ for new_id, old_id in enumerate(unique_ids, start=1):
586
+ renumbered[full_mask == old_id] = new_id
587
+
588
+ return renumbered
589
+
590
+
591
+ def _segment_patch(args):
592
+ """Worker: run cellpose on a single patch. Called from a thread pool."""
593
+ patch_np, row_start, col_start, model_filename, hf_repo = args
594
+ # Each thread uses the shared loaded_models cache (GIL-safe for reads;
595
+ # model.eval() releases the GIL during GPU work so threads overlap.)
596
+ model_path = hf_hub_download(repo_id=hf_repo, filename=model_filename)
597
+ if model_filename in loaded_models:
598
+ model = loaded_models[model_filename]
599
+ else:
600
+ model = models.CellposeModel(gpu=True, pretrained_model=model_path)
601
+ loaded_models[model_filename] = model
602
+
603
+ mask, _, _ = model.eval(patch_np, diameter=None, channels=[0, 0])
604
+ return mask, row_start, col_start
605
+
606
+
607
+ def run_segmentation_patched(image_np, model_filename):
608
+ """
609
+ Split image into overlapping patches, run Cellpose on each in parallel,
610
+ then stitch back into a single full-resolution mask.
611
+ Falls back to whole-image segmentation if the image is small enough
612
+ that patching adds overhead without benefit.
613
+ """
614
+ h, w = image_np.shape[:2]
615
+ model_path = hf_hub_download(repo_id=HF_REPO_ID, filename=model_filename)
616
+ if model_filename in loaded_models:
617
+ model = loaded_models[model_filename]
618
+ else:
619
+ model = models.CellposeModel(gpu=True, pretrained_model=model_path)
620
+ loaded_models[model_filename] = model
621
+
622
+ # Small images: no benefit from patching
623
+ if max(h, w) <= MIN_PATCH_DIM * 2:
624
+ mask, _, _ = model.eval(image_np, diameter=None, channels=[0, 0])
625
+ return mask, 1 # 1 patch
626
+
627
+ patches = _split_patches(image_np)
628
+ n_patches = len(patches)
629
+
630
+ # Build argument list for the thread pool
631
+ args_list = [
632
+ (patch, r, c, model_filename, HF_REPO_ID)
633
+ for patch, r, c in patches
634
+ ]
635
+
636
+ patch_results = [] # (mask, row_start, col_start) in submission order
637
+
638
+ # ThreadPoolExecutor: GPU kernels release the GIL so threads overlap on GPU
639
+ with ThreadPoolExecutor(max_workers=min(n_patches, 4)) as pool:
640
+ futures = {pool.submit(_segment_patch, a): a for a in args_list}
641
+ for future in as_completed(futures):
642
+ mask_patch, row_start, col_start = future.result()
643
+ patch_results.append((mask_patch, row_start, col_start))
644
+
645
+ # Re-sort by (row, col) so stitching is deterministic
646
+ patch_results.sort(key=lambda x: (x[1], x[2]))
647
+
648
+ full_mask = _merge_patch_masks(patch_results, h, w)
649
+ return full_mask, n_patches
650
+
651
+
652
+ @spaces.GPU
653
+ def run_segmentation(image, model_choice, min_cell_size, max_cell_size,
654
+ use_stereology, left_exclusion, top_exclusion,
655
+ crop_points=None, use_min_filter=False, use_max_filter=False):
656
+ image_np = np.array(image)
657
+
658
+ # Crop BEFORE downscaling, so the ROI is sampled from the original pixels
659
+ # rather than upscaled out of a ≀MAX_SIDE working copy. The crop points were
660
+ # clicked on the full-resolution upload, so they are already in this space.
661
+ # (Need β‰₯3 points for a polygon.)
662
+ if crop_points and len(crop_points) >= 3:
663
+ import json
664
+ if len(crop_points) == 4:
665
+ # The perspective warp already discards everything outside the quad,
666
+ # so masking first would only round the corners off.
667
+ image_np = warp_polygon_to_square(image_np, crop_points)
668
+ else:
669
+ pts_json = json.dumps([[float(x), float(y)] for x, y in crop_points])
670
+ image_pil_masked = apply_polygon_mask(Image.fromarray(image_np), pts_json)
671
+ image_np = np.array(image_pil_masked)
672
+
673
+ # Cap the working image only after cropping β€” a small ROI now keeps its
674
+ # native detail, and a large one is still bounded for segmentation.
675
+ image_np = safe_resize(image_np)
676
+
677
+ # Un-annotated copy of whatever we actually segment, kept for cell thumbnails.
678
+ # Must be taken after the crop so it stays index-compatible with the masks.
679
+ raw_image_np = image_np.copy()
680
+
681
+
682
+ try:
683
+ model_filename = MODEL_OPTIONS[model_choice]
684
+
685
+ # Process image format to RGB
686
+ if len(image_np.shape) == 2:
687
+ processed_image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
688
+ elif len(image_np.shape) == 3 and image_np.shape[2] == 4:
689
+ processed_image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
690
+ else:
691
+ processed_image_np = image_np
692
+
693
+ # Run patch-parallel Cellpose segmentation
694
+ masks_raw, n_patches = run_segmentation_patched(processed_image_np, model_filename)
695
+
696
+ ids = np.unique(masks_raw)
697
+ ids = ids[ids > 0]
698
+
699
+ sizes = np.array([np.count_nonzero(masks_raw == cid) for cid in ids])
700
+
701
+ print("num_cells:", len(ids))
702
+ print("mean:", sizes.mean() if len(sizes) > 0 else 0)
703
+ print("median:", np.median(sizes) if len(sizes) > 0 else 0)
704
+ print("p90:", np.percentile(sizes, 90) if len(sizes) > 0 else 0)
705
+ print("max:", sizes.max() if len(sizes) > 0 else 0)
706
+
707
+ # Compute recommendation from RAW masks
708
+ recommend_min = rec_min_size(masks_raw)
709
+
710
+ # Surface the recommendation as text rather than writing it into the
711
+ # slider, which would overwrite a threshold the user had chosen.
712
+ if recommend_min > 0:
713
+ rec_msg = (f"*Recommended minimum: **{recommend_min}** pixels "
714
+ f"(25th percentile of detected object sizes). "
715
+ f"Enable the filter and leave the slider at 0 to use it.*")
716
+ else:
717
+ rec_msg = "*No objects detected β€” no minimum size recommendation.*"
718
+
719
+ # Size filters only run when their checkbox is ticked. When the minimum
720
+ # filter is on but the slider is still at 0, fall back to the
721
+ # recommendation; when it is off, nothing is filtered at all.
722
+ min_used = 0
723
+ if use_min_filter:
724
+ min_used = recommend_min if (min_cell_size == 0) else int(min_cell_size)
725
+
726
+ masks = masks_raw.copy()
727
+ removed_small = 0
728
+ removed_large = 0
729
+
730
+ if use_min_filter and min_used > 0:
731
+ masks, removed_small = filter_mask_by_size(masks, min_used)
732
+
733
+ if use_max_filter and max_cell_size > 0:
734
+ masks, removed_large = filter_mask_by_maxsize(masks, int(max_cell_size))
735
+
736
+ # Apply stereological exclusion if enabled
737
+ excluded_count = 0
738
+ if use_stereology:
739
+ masks, excluded_count, included_count = apply_stereological_exclusion(
740
+ masks, left_exclusion, top_exclusion
741
+ )
742
+
743
+ filter_msg = ""
744
+ if removed_small:
745
+ filter_msg += f"Removed {removed_small} small objects (< {min_used} pixels).\n"
746
+ if removed_large:
747
+ filter_msg += f"Removed {removed_large} large objects (> {int(max_cell_size)} pixels).\n"
748
+ if use_stereology and excluded_count > 0:
749
+ filter_msg += f"Stereological exclusion: {excluded_count} cells excluded (touching left/top zones).\n"
750
+
751
+ cell_count = len(np.unique(masks)) - 1
752
+ confluency = measure_confluency(masks, processed_image_np)
753
+
754
+ # Create a basic segmentation overlay (without viability)
755
+ segmentation_overlay = processed_image_np.copy().astype(np.float32)
756
+ if masks.max() > 0:
757
+ np.random.seed(42) # For consistent random colors
758
+ colors = np.random.randint(0, 255, size=(masks.max() + 1, 3))
759
+ colors[0] = [0, 0, 0]
760
+ colored_mask = colors[masks]
761
+ alpha = 0.4
762
+ segmentation_overlay = (1 - alpha) * segmentation_overlay + alpha * colored_mask
763
+ segmentation_overlay = np.clip(segmentation_overlay, 0, 255).astype(np.uint8)
764
+
765
+ # Add exclusion zone overlay if stereology is enabled
766
+ if use_stereology:
767
+ segmentation_overlay = draw_exclusion_overlay(segmentation_overlay, left_exclusion, top_exclusion)
768
+
769
+ info_msg = ""
770
+ if filter_msg:
771
+ info_msg += filter_msg
772
+ info_msg += f"Segmentation complete! Found {cell_count} cells.\n"
773
+ info_msg += f"Confluency: {confluency:.1f}%\n"
774
+ info_msg += f"Processed as {n_patches} patch{'es' if n_patches > 1 else ''} (parallel).\n"
775
+ if use_stereology:
776
+ info_msg += f"Stereological counting enabled (Left: {left_exclusion}%, Top: {top_exclusion}%)\n"
777
+ info_msg += "Now run the viability classification model for viability assessment."
778
+
779
+ return (
780
+ cell_count,
781
+ Image.fromarray(segmentation_overlay),
782
+ info_msg,
783
+ gr.update(visible=True),
784
+ pack_array(masks),
785
+ pack_array(processed_image_np),
786
+ confluency,
787
+ gr.update(value=rec_msg),
788
+ pack_array(raw_image_np),
789
+ )
790
+
791
+ except Exception as e:
792
+ import traceback
793
+ traceback.print_exc()
794
+ return (
795
+ 0,
796
+ None,
797
+ f"Error during segmentation: {str(e)}",
798
+ gr.update(visible=False),
799
+ None,
800
+ None,
801
+ 0.0,
802
+ gr.update(),
803
+ None,
804
+ )
805
+
806
+
807
+ def run_viability(stored_masks, stored_image_np):
808
+ """Run model-based viability classification. Returns overlay + counts + label_map."""
809
+ if stored_masks is None or stored_image_np is None:
810
+ return None, 0, 0, 0.0, "Please run segmentation first.", {}
811
+ if VIABILITY_CLF is None:
812
+ return None, 0, 0, 0.0, "No viability model found. Add viability_clf.pkl and viability_scaler.pkl to the app directory.", {}
813
+
814
+ masks = unpack_array(stored_masks)
815
+ image_np = unpack_array(stored_image_np)
816
+
817
+ try:
818
+ dead, alive, overlay_np, label_map = classify_cells_by_model(image_np, masks)
819
+ total = alive + dead
820
+ viab_pct = (alive / total * 100) if total > 0 else 0.0
821
+ confluency = measure_confluency(masks, image_np)
822
+ info_msg = f"Total cells: {total}\nLive (green): {alive}\nDead (red): {dead}\n"
823
+ info_msg += f"Viability: {viab_pct:.1f}%\nConfluency: {confluency:.1f}%"
824
+ return Image.fromarray(overlay_np), alive, dead, viab_pct, info_msg, label_map
825
+ except Exception as e:
826
+ import traceback; traceback.print_exc()
827
+ return None, 0, 0, 0.0, f"Error: {str(e)}", {}
828
+
829
+
830
+ def pack_array(arr):
831
+ pil = Image.fromarray(arr.astype(np.uint8))
832
+ buf = io.BytesIO()
833
+ pil.save(buf, format="PNG")
834
+ return buf.getvalue()
835
+
836
+
837
+ def unpack_array(data):
838
+ return np.array(Image.open(io.BytesIO(data)))
839
+
840
+
841
+ def save_tab_result(cell_count, confluency, viab_percent):
842
+ """Package per-tab results into a dict for Tab 5 summary."""
843
+ return {
844
+ "cell_count": float(cell_count) if cell_count is not None else None,
845
+ "confluency": float(confluency) if confluency is not None else None,
846
+ "viab_percent": float(viab_percent) if viab_percent is not None else None,
847
+ }
848
+
849
+
850
+ def compute_summary(r1, r2, r3, r4):
851
+ """Average cell count, confluency, and viability across tabs that have data."""
852
+ all_results = [r1, r2, r3, r4]
853
+ valid = [(i + 1, r) for i, r in enumerate(all_results)
854
+ if r is not None and r.get("cell_count") is not None]
855
+
856
+ if not valid:
857
+ return (
858
+ 0.0, 0.0, 0.0,
859
+ "No data yet β€” run segmentation in at least one tab, then click Refresh Summary."
860
+ )
861
+
862
+ avg_count = sum(r["cell_count"] for _, r in valid) / len(valid)
863
+ avg_conf = sum(r["confluency"] for _, r in valid) / len(valid)
864
+ avg_viab = sum(r["viab_percent"] for _, r in valid) / len(valid)
865
+
866
+ lines = [f"Tab {tab_num}: {r['cell_count']:.0f} cells | "
867
+ f"{r['confluency']:.1f}% confluency | "
868
+ f"{r['viab_percent']:.1f}% viability"
869
+ for tab_num, r in valid]
870
+ lines.append(f"\nAverages ({len(valid)} tab{'s' if len(valid) > 1 else ''}):")
871
+ lines.append(f" Cell count: {avg_count:.1f}")
872
+ lines.append(f" Confluency: {avg_conf:.1f}%")
873
+ lines.append(f" Viability: {avg_viab:.1f}%")
874
+
875
+ return avg_count, avg_conf, avg_viab, "\n".join(lines)
876
+
877
+
878
+ # ---------------------------------------------------------------------------
879
+ # Training data export β€” feature extraction per cell
880
+ # ---------------------------------------------------------------------------
881
+
882
+ def extract_cell_features(image_np, masks):
883
+ """
884
+ For every segmented cell, extract a fixed feature vector from the pixels
885
+ inside its mask. Returns a list of dicts, one per cell.
886
+
887
+ Features:
888
+ RGB channels β€” mean_r, mean_g, mean_b, std_r, std_g, std_b
889
+ HSV channels β€” mean_h, mean_s, mean_v, std_s, std_v
890
+ Ratios β€” blue_red_ratio, blue_green_ratio, rg_ratio
891
+ Morphology β€” area_px, circularity
892
+ Centre/edge profile β€” inner_brightness, peak_brightness,
893
+ bright_spot_fraction, ring_darkness,
894
+ centre_periphery_ratio, brightness_std_normalised
895
+
896
+ Profile zones are tuned to hemocytometer live-cell morphology:
897
+ a small intense specular highlight at the centre surrounded by a dark
898
+ navy membrane ring. Dead cells are pale blue-grey blobs with no ring
899
+ and no bright spot.
900
+ """
901
+ if len(image_np.shape) == 2:
902
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_GRAY2RGB)
903
+ elif image_np.shape[2] == 4:
904
+ image_np = cv2.cvtColor(image_np, cv2.COLOR_RGBA2RGB)
905
+
906
+ hsv = cv2.cvtColor(image_np, cv2.COLOR_RGB2HSV).astype(np.float32)
907
+
908
+ h_img, w_img = image_np.shape[:2]
909
+ grid_y, grid_x = np.mgrid[:h_img, :w_img]
910
+
911
+ cell_ids = np.unique(masks)
912
+ cell_ids = cell_ids[cell_ids > 0]
913
+ rows = []
914
+
915
+ for cid in cell_ids:
916
+ cell_mask = (masks == cid)
917
+ pixels_rgb = image_np[cell_mask].astype(np.float32)
918
+ pixels_hsv = hsv[cell_mask]
919
+
920
+ r, g, b = pixels_rgb[:, 0], pixels_rgb[:, 1], pixels_rgb[:, 2]
921
+ h, s, v = pixels_hsv[:, 0], pixels_hsv[:, 1], pixels_hsv[:, 2]
922
+
923
+ eps = 1e-6
924
+ blue_red_ratio = b.mean() / (r.mean() + eps)
925
+ blue_green_ratio = b.mean() / (g.mean() + eps)
926
+ rg_ratio = r.mean() / (g.mean() + eps)
927
+
928
+ area_px = int(cell_mask.sum())
929
+ contours, _ = cv2.findContours(
930
+ cell_mask.astype(np.uint8), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE
931
+ )
932
+ perimeter = cv2.arcLength(contours[0], True) if contours else 1.0
933
+ circularity = (4 * np.pi * area_px / (perimeter ** 2 + eps)) if perimeter > 0 else 0.0
934
+
935
+ ys_cell = grid_y[cell_mask].astype(np.float32)
936
+ xs_cell = grid_x[cell_mask].astype(np.float32)
937
+ centroid_y = ys_cell.mean()
938
+ centroid_x = xs_cell.mean()
939
+
940
+ cell_radius = np.sqrt(area_px / np.pi) + eps
941
+ dist_norm = np.sqrt((xs_cell - centroid_x)**2 + (ys_cell - centroid_y)**2) / cell_radius
942
+
943
+ v_all = hsv[:, :, 2][cell_mask]
944
+
945
+ # Tight inner core (15% radius) β€” captures specular highlight spot only
946
+ inner_mask = dist_norm < 0.15
947
+ # Membrane ring zone (20-60%) β€” dark navy ring on live cells
948
+ ring_mask = (dist_norm >= 0.20) & (dist_norm <= 0.60)
949
+ # Outer zone (>60%) β€” denominator for centre ratio
950
+ outer_mask = dist_norm > 0.60
951
+
952
+ inner_brightness = float(v_all[inner_mask].mean()) if inner_mask.any() else float(v.mean())
953
+ ring_brightness = float(v_all[ring_mask].mean()) if ring_mask.any() else float(v.mean())
954
+ outer_brightness = float(v_all[outer_mask].mean()) if outer_mask.any() else float(v.mean())
955
+
956
+ # Peak V β€” specular spot is just a few pixels so mean dilutes it
957
+ peak_brightness = float(v_all.max())
958
+
959
+ # Fraction of cell pixels with V > 200 (specular highlight region)
960
+ bright_spot_fraction = float((v_all > 200).sum()) / (len(v_all) + eps)
961
+
962
+ # Ring darkness: ratio of ring zone to outer zone brightness
963
+ # Live: ring << outer (dark membrane ring) -> ratio < 1
964
+ # Dead: uniform blob -> ratio ~ 1
965
+ ring_darkness = ring_brightness / (outer_brightness + eps)
966
+
967
+ centre_periphery_ratio = inner_brightness / (outer_brightness + eps)
968
+
969
+ brightness_std_normalised = float(v.std()) / (float(v.mean()) + eps)
970
+
971
+ rows.append({
972
+ "cell_id": int(cid),
973
+ "mean_r": float(r.mean()),
974
+ "mean_g": float(g.mean()),
975
+ "mean_b": float(b.mean()),
976
+ "std_r": float(r.std()),
977
+ "std_g": float(g.std()),
978
+ "std_b": float(b.std()),
979
+ "mean_h": float(h.mean()),
980
+ "mean_s": float(s.mean()),
981
+ "mean_v": float(v.mean()),
982
+ "std_s": float(s.std()),
983
+ "std_v": float(v.std()),
984
+ "blue_red_ratio": round(blue_red_ratio, 5),
985
+ "blue_green_ratio": round(blue_green_ratio, 5),
986
+ "rg_ratio": round(rg_ratio, 5),
987
+ "area_px": area_px,
988
+ "circularity": round(float(circularity), 5),
989
+ "inner_brightness": round(inner_brightness, 3),
990
+ "peak_brightness": round(peak_brightness, 3),
991
+ "bright_spot_fraction": round(bright_spot_fraction, 6),
992
+ "ring_darkness": round(ring_darkness, 5),
993
+ "centre_periphery_ratio": round(centre_periphery_ratio, 5),
994
+ "brightness_std_normalised": round(brightness_std_normalised, 5),
995
+ })
996
+
997
+ return rows
998
+
999
+ def attach_viability_labels(cell_features, masks, image_np, label_map=None):
1000
+ """
1001
+ Attach model predictions (from label_map) to each feature dict.
1002
+ label_map: {cell_id: 0=live, 1=dead} from classify_cells_by_model.
1003
+ If label_map is None, defaults all labels to 0 (live).
1004
+ """
1005
+ if not cell_features:
1006
+ return []
1007
+ labelled = []
1008
+ for feat in cell_features:
1009
+ row = dict(feat)
1010
+ cid = int(feat["cell_id"])
1011
+ row["label"] = int(label_map.get(cid, 0)) if label_map else 0
1012
+ row["corrected"] = False
1013
+ labelled.append(row)
1014
+ return labelled
1015
+
1016
+
1017
+ def export_cell_data_csv(cell_data):
1018
+ """Write cell_data list-of-dicts to a temp CSV and return the file path."""
1019
+ if not cell_data:
1020
+ return None
1021
+ tmp = tempfile.NamedTemporaryFile(
1022
+ mode="w", suffix=".csv", delete=False, newline=""
1023
+ )
1024
+ # Union of all keys across rows so any late-added keys (e.g. "corrected") are included
1025
+ fieldnames = list(dict.fromkeys(k for row in cell_data for k in row.keys()))
1026
+ writer = csv.DictWriter(tmp, fieldnames=fieldnames, extrasaction="ignore")
1027
+ writer.writeheader()
1028
+ writer.writerows(cell_data)
1029
+ tmp.close()
1030
+ return tmp.name
1031
+
1032
+
1033
+ def prepare_export(stored_masks, stored_image, threshold_bias):
1034
+ """
1035
+ Called by the Export button. Unpacks state, extracts features,
1036
+ attaches labels, writes CSV, returns (path, status_message).
1037
+ """
1038
+ if stored_masks is None or stored_image is None:
1039
+ return None, "Run segmentation first before exporting."
1040
+
1041
+ masks = unpack_array(stored_masks)
1042
+ image_np = unpack_array(stored_image)
1043
+
1044
+ features = extract_cell_features(image_np, masks)
1045
+ if not features:
1046
+ return None, "No cells found to export."
1047
+
1048
+ labelled = attach_viability_labels(features, masks, image_np, threshold_bias)
1049
+ path = export_cell_data_csv(labelled)
1050
+
1051
+ n = len(labelled)
1052
+ dead = sum(1 for r in labelled if r["label"] == 1)
1053
+ alive = n - dead
1054
+ msg = (f"Exported {n} cells ({alive} live, {dead} dead) β€” "
1055
+ f"threshold bias={threshold_bias:+d}.\n"
1056
+ f"Columns: {', '.join(list(labelled[0].keys())[:6])}… "
1057
+ f"({len(labelled[0])} total).")
1058
+ return path, msg
1059
+
1060
+
1061
+ # ---------------------------------------------------------------------------
1062
+ # Tab builder
1063
+ # ---------------------------------------------------------------------------
1064
+
1065
+ def draw_polygon_overlay(image_pil, points):
1066
+ """
1067
+ Draw numbered vertex dots and polygon edges onto a copy of image_pil.
1068
+ points: list of (x, y) tuples in original image pixel space.
1069
+ Returns a new PIL image.
1070
+ """
1071
+ img = image_pil.copy().convert("RGBA")
1072
+ overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
1073
+ draw = ImageDraw.Draw(overlay)
1074
+
1075
+ if len(points) >= 2:
1076
+ # Draw edges
1077
+ for i in range(len(points) - 1):
1078
+ draw.line([points[i], points[i + 1]], fill=(74, 170, 255, 220), width=3)
1079
+ if len(points) == 4:
1080
+ draw.line([points[-1], points[0]], fill=(74, 170, 255, 220), width=3)
1081
+ # Semi-transparent fill
1082
+ draw.polygon(points, fill=(74, 170, 255, 50))
1083
+
1084
+ # Draw vertex dots + numbers
1085
+ r = max(8, min(img.width, img.height) // 60)
1086
+ for i, (x, y) in enumerate(points):
1087
+ draw.ellipse([x - r, y - r, x + r, y + r],
1088
+ fill=(74, 170, 255, 255), outline=(255, 255, 255, 255))
1089
+ draw.text((x, y), str(i + 1), fill=(255, 255, 255, 255), anchor="mm")
1090
+
1091
+ combined = Image.alpha_composite(img, overlay)
1092
+ return combined.convert("RGB")
1093
+
1094
+
1095
+ def add_crop_point(image_pil, points, evt: gr.SelectData):
1096
+ """
1097
+ Called by gr.Image .select(). Appends the clicked coordinate,
1098
+ redraws the overlay, returns (updated_image, updated_points).
1099
+ Ignores clicks once 4 points are set.
1100
+ """
1101
+ if image_pil is None:
1102
+ return image_pil, points
1103
+ if points is None:
1104
+ points = []
1105
+ if len(points) >= 4:
1106
+ return draw_polygon_overlay(image_pil, points), points
1107
+
1108
+ x, y = int(evt.index[0]), int(evt.index[1])
1109
+ new_points = points + [(x, y)]
1110
+ return draw_polygon_overlay(image_pil, new_points), new_points
1111
+
1112
+
1113
+ def clear_crop_points(image_pil):
1114
+ """Reset polygon β€” return original image with no overlay and empty points."""
1115
+ return image_pil, []
1116
+
1117
+
1118
+
1119
+
1120
+
1121
+ # ---------------------------------------------------------------------------
1122
+ # Label correction grid
1123
+ # ---------------------------------------------------------------------------
1124
+
1125
+ THUMB_SIZE = 80 # each cell thumbnail is THUMB_SIZE Γ— THUMB_SIZE px
1126
+ GRID_COLS = 8 # thumbnails per row
1127
+ BORDER = 4 # coloured border thickness in px
1128
+ LABEL_H = 16 # height of the text label strip at the bottom of each thumb
1129
+
1130
+ def _crop_cell_thumb(image_np, masks, cid):
1131
+ """
1132
+ Return a tight square crop of the cell, padded to THUMB_SIZE Γ— THUMB_SIZE.
1133
+ """
1134
+ ys, xs = np.where(masks == cid)
1135
+ if len(ys) == 0:
1136
+ return Image.fromarray(np.zeros((THUMB_SIZE, THUMB_SIZE, 3), dtype=np.uint8))
1137
+
1138
+ y0, y1 = ys.min(), ys.max() + 1
1139
+ x0, x1 = xs.min(), xs.max() + 1
1140
+
1141
+ # add a small context border around the tight bounding box
1142
+ pad = max(4, int(max(y1 - y0, x1 - x0) * 0.15))
1143
+ h, w = image_np.shape[:2]
1144
+ y0c = max(0, y0 - pad)
1145
+ y1c = min(h, y1 + pad)
1146
+ x0c = max(0, x0 - pad)
1147
+ x1c = min(w, x1 + pad)
1148
+
1149
+ crop = image_np[y0c:y1c, x0c:x1c].copy()
1150
+
1151
+ # dim pixels that don't belong to this cell
1152
+ dim_mask = (masks[y0c:y1c, x0c:x1c] != cid)
1153
+ crop[dim_mask] = (crop[dim_mask] * 0.3).astype(np.uint8)
1154
+
1155
+ pil = Image.fromarray(crop).resize((THUMB_SIZE, THUMB_SIZE), Image.LANCZOS)
1156
+ return pil
1157
+
1158
+
1159
+ def build_correction_grid(image_np, masks, labelled_features, raw_image_np=None):
1160
+ """
1161
+ Render all cell thumbnails into a single PIL image grid.
1162
+ Each thumbnail has a coloured border: green=live(0), red=dead(1).
1163
+ A small number in the corner identifies the cell_id.
1164
+
1165
+ Returns the PIL grid image.
1166
+ Cell order in the grid matches the order of labelled_features.
1167
+ """
1168
+ if not labelled_features:
1169
+ placeholder = Image.fromarray(
1170
+ np.zeros((THUMB_SIZE, THUMB_SIZE, 3), dtype=np.uint8)
1171
+ )
1172
+ return placeholder
1173
+
1174
+ thumb_src = raw_image_np if raw_image_np is not None else image_np
1175
+
1176
+ n = len(labelled_features)
1177
+ n_cols = GRID_COLS
1178
+ n_rows = (n + n_cols - 1) // n_cols
1179
+
1180
+ cell_h = THUMB_SIZE + 2 * BORDER + LABEL_H
1181
+ cell_w = THUMB_SIZE + 2 * BORDER
1182
+
1183
+ grid_w = n_cols * cell_w
1184
+ grid_h = n_rows * cell_h
1185
+
1186
+ grid = Image.new("RGB", (grid_w, grid_h), (30, 30, 30))
1187
+ draw = ImageDraw.Draw(grid)
1188
+
1189
+ for idx, feat in enumerate(labelled_features):
1190
+ cid = feat["cell_id"]
1191
+ label = feat["label"] # 0=live, 1=dead (may have been corrected)
1192
+ color = (220, 50, 50) if label == 1 else (50, 200, 80)
1193
+
1194
+ thumb = _crop_cell_thumb(thumb_src, masks, cid)
1195
+
1196
+ col = idx % n_cols
1197
+ row = idx // n_cols
1198
+ x0 = col * cell_w
1199
+ y0 = row * cell_h
1200
+
1201
+ # coloured border rectangle
1202
+ draw.rectangle([x0, y0, x0 + cell_w - 1, y0 + cell_h - 1], outline=color, width=BORDER)
1203
+
1204
+ # paste thumbnail inside border
1205
+ grid.paste(thumb, (x0 + BORDER, y0 + BORDER))
1206
+
1207
+ # small cell-id label strip
1208
+ strip_y = y0 + BORDER + THUMB_SIZE
1209
+ draw.rectangle([x0, strip_y, x0 + cell_w - 1, y0 + cell_h - 1],
1210
+ fill=(20, 20, 20))
1211
+ draw.text((x0 + BORDER + 2, strip_y + 1),
1212
+ f"#{cid} {'D' if label == 1 else 'L'}",
1213
+ fill=color)
1214
+
1215
+ return grid
1216
+
1217
+
1218
+ def toggle_cell_label(labelled_features, image_np, masks, raw_image_np, evt: gr.SelectData):
1219
+ """
1220
+ Called when user taps the correction grid image.
1221
+ Maps the tap pixel coordinate back to which thumbnail was tapped,
1222
+ flips that cell's label, rebuilds and returns the updated grid.
1223
+ """
1224
+ if not labelled_features or image_np is None:
1225
+ return build_correction_grid(image_np, masks, labelled_features), labelled_features
1226
+
1227
+ cell_w = THUMB_SIZE + 2 * BORDER
1228
+ cell_h = THUMB_SIZE + 2 * BORDER + LABEL_H
1229
+
1230
+ px, py = int(evt.index[0]), int(evt.index[1])
1231
+ col = px // cell_w
1232
+ row = py // cell_h
1233
+ idx = row * GRID_COLS + col
1234
+
1235
+ if idx < 0 or idx >= len(labelled_features):
1236
+ return build_correction_grid(image_np, masks, labelled_features, raw_image_np), labelled_features
1237
+
1238
+ # Flip the label
1239
+ updated = list(labelled_features) # shallow copy of list
1240
+ cell = dict(updated[idx]) # copy the dict so we don't mutate in place
1241
+ cell["label"] = 1 - cell["label"] # 0β†’1 or 1β†’0
1242
+ cell["corrected"] = True
1243
+ updated[idx] = cell
1244
+
1245
+ grid = build_correction_grid(image_np, masks, updated, raw_image_np)
1246
+ n_corrected = sum(1 for f in updated if f.get("corrected"))
1247
+ return grid, updated, f"Tapped cell #{cell['cell_id']} β†’ {'Dead' if cell['label']==1 else 'Live'}. {n_corrected} correction(s) total."
1248
+
1249
+
1250
+ def prepare_export_corrected(stored_masks, stored_image, labelled_features, label_map):
1251
+ """Export CSV using labelled_features with any manual corrections applied."""
1252
+ if stored_masks is None or stored_image is None:
1253
+ return None, "Run segmentation first before exporting."
1254
+ masks = unpack_array(stored_masks)
1255
+ image_np = unpack_array(stored_image)
1256
+ if not labelled_features:
1257
+ features = extract_cell_features(image_np, masks)
1258
+ labelled_features = attach_viability_labels(features, masks, image_np, label_map)
1259
+ if not labelled_features:
1260
+ return None, "No cells found to export."
1261
+ path = export_cell_data_csv(labelled_features)
1262
+ n = len(labelled_features)
1263
+ dead = sum(1 for r in labelled_features if r["label"] == 1)
1264
+ alive = n - dead
1265
+ corrected = sum(1 for r in labelled_features if r.get("corrected"))
1266
+ msg = (f"Exported {n} cells ({alive} live, {dead} dead). "
1267
+ f"{corrected} label(s) manually corrected.")
1268
+ return path, msg
1269
+
1270
+ def build_tab(tab_index, masks_state, image_state, result_state):
1271
+ with gr.Tab(f"Tab {tab_index}"):
1272
+ gr.Markdown("Run segmentation")
1273
+
1274
+ # Per-tab state: list of (x,y) crop polygon points
1275
+ crop_points_state = gr.State(value=[])
1276
+ # Clean copy of the uploaded image (no polygon drawn on it)
1277
+ base_image_state = gr.State(value=None)
1278
+ #raw image state
1279
+ raw_image_state = gr.State(value=None)
1280
+
1281
+ with gr.Row():
1282
+ with gr.Column():
1283
+ img_input = gr.Image(
1284
+ type="pil",
1285
+ label="Upload image",
1286
+ image_mode="RGB",
1287
+ height=512
1288
+ )
1289
+
1290
+ gr.Markdown(
1291
+ "### Crop region (optional)\n"
1292
+ "Click/tap up to **4 points** on the image below to define the region "
1293
+ "to segment. The polygon will be drawn as you click. "
1294
+ "Leave empty to segment the full image."
1295
+ )
1296
+
1297
+ crop_display = gr.Image(
1298
+ type="pil",
1299
+ label="Click to set crop vertices (up to 4)",
1300
+ interactive=True,
1301
+ height=400,
1302
+ )
1303
+
1304
+ crop_status = gr.Markdown("*Upload an image to enable cropping*")
1305
+
1306
+ clear_crop_btn = gr.Button("βœ• Clear crop points", size="sm")
1307
+
1308
+ model_dropdown = gr.Dropdown(
1309
+ choices=list(MODEL_OPTIONS.keys()),
1310
+ label="Select Model",
1311
+ value="Hemocytometer Model"
1312
+ )
1313
+
1314
+ gr.Markdown("### Size Filters")
1315
+
1316
+ use_min_filter = gr.Checkbox(
1317
+ label="Enable minimum size filter",
1318
+ value=False,
1319
+ info="Remove objects smaller than the threshold below"
1320
+ )
1321
+ min_size_slider = gr.Slider(
1322
+ minimum=0,
1323
+ maximum=500,
1324
+ value=0,
1325
+ step=10,
1326
+ label="Minimum Cell Size (pixels)",
1327
+ interactive=False,
1328
+ )
1329
+ min_size_recommendation = gr.Markdown(
1330
+ value="*Run segmentation to see recommended minimum*",
1331
+ )
1332
+
1333
+ use_max_filter = gr.Checkbox(
1334
+ label="Enable maximum size filter",
1335
+ value=False,
1336
+ info="Remove objects larger than the threshold below"
1337
+ )
1338
+ max_size_slider = gr.Slider(
1339
+ minimum=0,
1340
+ maximum=10000,
1341
+ value=10000,
1342
+ step=10,
1343
+ label="Maximum Cell Size (pixels)",
1344
+ interactive=False,
1345
+ )
1346
+
1347
+ gr.Markdown("### Stereological Counting")
1348
+ use_stereo = gr.Checkbox(
1349
+ label="Enable Stereological Counting",
1350
+ value=False,
1351
+ info="Use unbiased stereological rules for cell counting"
1352
+ )
1353
+
1354
+ with gr.Group(visible=False) as stereo_controls:
1355
+ gr.Markdown("""
1356
+ **Stereological Counting Rules:**
1357
+ - Cells touching LEFT or TOP exclusion zones are EXCLUDED
1358
+ - Cells touching RIGHT or BOTTOM edges are INCLUDED
1359
+ - This provides unbiased counting for quantification
1360
+ """)
1361
+
1362
+ excl_preview = gr.Image(
1363
+ type="pil",
1364
+ label="Exclusion Zone Preview (Red = Excluded)",
1365
+ height=500
1366
+ )
1367
+
1368
+ left_excl = gr.Slider(
1369
+ minimum=0,
1370
+ maximum=50,
1371
+ value=10,
1372
+ step=1,
1373
+ label="Left Exclusion Width (%)",
1374
+ info="Width of left exclusion zone"
1375
+ )
1376
+
1377
+ top_excl = gr.Slider(
1378
+ minimum=0,
1379
+ maximum=50,
1380
+ value=10,
1381
+ step=1,
1382
+ label="Top Exclusion Width (%)",
1383
+ info="Width of top exclusion zone"
1384
+ )
1385
+
1386
+ segment_btn = gr.Button("πŸ”¬ Run Segmentation", variant="primary", size="lg")
1387
+
1388
+ with gr.Column():
1389
+ cell_count_out = gr.Number(label="Total Cells Detected", precision=0)
1390
+ confluency_out = gr.Number(label="Confluency (%)", precision=1)
1391
+ overlay_out = gr.Image(type="pil", label="Segmentation Result")
1392
+ info_out = gr.Textbox(label="Processing Info", lines=4)
1393
+
1394
+ with gr.Group(visible=False) as viability_section:
1395
+ gr.Markdown("### Viability Assessment (Trypan Blue)")
1396
+
1397
+ viab_run_btn = gr.Button("Run Viability Analysis", variant="primary")
1398
+
1399
+ with gr.Row():
1400
+ live_count_out = gr.Number(label="Live Cells (Green)", precision=0)
1401
+ dead_count_out = gr.Number(label="Dead Cells (Red)", precision=0)
1402
+
1403
+ viab_overlay = gr.Image(type="pil", label="Viability (Green=Live Β· Red=Dead)")
1404
+ viab_percent_out = gr.Number(label="Viability (%)", precision=1)
1405
+ viab_info = gr.Textbox(label="Analysis Results", lines=4)
1406
+
1407
+ gr.Markdown("### Label Correction & Export")
1408
+ gr.Markdown(
1409
+ "After running viability, click **Build correction grid** to review every cell. "
1410
+ "**Green border = Live, Red border = Dead** (model predictions). "
1411
+ "Tap any thumbnail to flip its label β€” the counts and overlay update instantly. "
1412
+ "Export the corrected CSV for retraining."
1413
+ )
1414
+
1415
+ build_grid_btn = gr.Button("πŸ”² Build correction grid", variant="secondary")
1416
+ labelled_state = gr.State(value=[])
1417
+ label_map_state = gr.State(value={})
1418
+
1419
+ correction_grid = gr.Image(
1420
+ type="pil",
1421
+ label="Tap a cell to flip its label (green=live Β· red=dead)",
1422
+ interactive=True,
1423
+ visible=False,
1424
+ )
1425
+ correction_status = gr.Markdown(visible=False)
1426
+
1427
+ with gr.Row():
1428
+ export_btn = gr.Button("⬇️ Export corrected CSV", variant="secondary")
1429
+ export_info = gr.Textbox(label="Export status", lines=2, interactive=False)
1430
+ export_file = gr.File(label="Download CSV", visible=False)
1431
+
1432
+ # ---- Event handlers ------------------------------------------------
1433
+
1434
+ use_stereo.change(
1435
+ fn=toggle_stereological_mode,
1436
+ inputs=[use_stereo],
1437
+ outputs=[stereo_controls]
1438
+ )
1439
+
1440
+ def on_image_upload(img):
1441
+ if img is None:
1442
+ return None, None, "*Upload an image to enable cropping*"
1443
+ return img, img, "*Image loaded β€” click up to 4 points to define crop region*"
1444
+
1445
+ img_input.change(
1446
+ fn=on_image_upload,
1447
+ inputs=[img_input],
1448
+ outputs=[crop_display, base_image_state, crop_status]
1449
+ ).then(fn=lambda: [], outputs=[crop_points_state])
1450
+
1451
+ # Grey the size sliders out while their filter is disabled, so the
1452
+ # checkbox state is visible rather than silently inferred.
1453
+ use_min_filter.change(
1454
+ fn=lambda on: gr.update(interactive=bool(on)),
1455
+ inputs=[use_min_filter], outputs=[min_size_slider]
1456
+ )
1457
+ use_max_filter.change(
1458
+ fn=lambda on: gr.update(interactive=bool(on)),
1459
+ inputs=[use_max_filter], outputs=[max_size_slider]
1460
+ )
1461
+
1462
+ excl_preview_inputs = [img_input, left_excl, top_excl, crop_points_state]
1463
+ img_input.change(fn=update_exclusion_preview,
1464
+ inputs=excl_preview_inputs, outputs=[excl_preview])
1465
+ left_excl.change(fn=update_exclusion_preview,
1466
+ inputs=excl_preview_inputs, outputs=[excl_preview])
1467
+ top_excl.change(fn=update_exclusion_preview,
1468
+ inputs=excl_preview_inputs, outputs=[excl_preview])
1469
+
1470
+ def on_crop_click(base_img, points, evt: gr.SelectData):
1471
+ updated_img, updated_pts = add_crop_point(base_img, points, evt)
1472
+ n = len(updated_pts)
1473
+ status = (f"*{n} / 4 points set β€” keep clicking*" if n < 4
1474
+ else "*4 points set βœ“ β€” click **βœ• Clear** to redo, or run segmentation*")
1475
+ return updated_img, updated_pts, status
1476
+
1477
+ crop_display.select(fn=on_crop_click,
1478
+ inputs=[base_image_state, crop_points_state],
1479
+ outputs=[crop_display, crop_points_state, crop_status]
1480
+ ).then(fn=update_exclusion_preview,
1481
+ inputs=excl_preview_inputs, outputs=[excl_preview])
1482
+
1483
+ def on_clear_crop(base_img):
1484
+ img, pts = clear_crop_points(base_img)
1485
+ return img, pts, "*Points cleared β€” click to set new vertices*"
1486
+
1487
+ clear_crop_btn.click(fn=on_clear_crop,
1488
+ inputs=[base_image_state],
1489
+ outputs=[crop_display, crop_points_state, crop_status]
1490
+ ).then(fn=update_exclusion_preview,
1491
+ inputs=excl_preview_inputs, outputs=[excl_preview])
1492
+
1493
+ segment_btn.click(
1494
+ fn=run_segmentation,
1495
+ inputs=[img_input, model_dropdown, min_size_slider, max_size_slider,
1496
+ use_stereo, left_excl, top_excl, crop_points_state,
1497
+ use_min_filter, use_max_filter],
1498
+ outputs=[cell_count_out, overlay_out, info_out, viability_section,
1499
+ masks_state, image_state, confluency_out,
1500
+ min_size_recommendation, raw_image_state]
1501
+ )
1502
+
1503
+ # ---- Run Viability button -------------------------------------------
1504
+ def on_run_viability(stored_masks, stored_image):
1505
+ overlay, alive, dead, viab_pct, info, label_map = run_viability(stored_masks, stored_image)
1506
+ return overlay, alive, dead, viab_pct, info, label_map
1507
+
1508
+ viab_run_btn.click(
1509
+ fn=on_run_viability,
1510
+ inputs=[masks_state, image_state],
1511
+ outputs=[viab_overlay, live_count_out, dead_count_out,
1512
+ viab_percent_out, viab_info, label_map_state]
1513
+ ).then(
1514
+ fn=save_tab_result,
1515
+ inputs=[cell_count_out, confluency_out, viab_percent_out],
1516
+ outputs=[result_state]
1517
+ )
1518
+
1519
+ # ---- Build correction grid -----------------------------------------
1520
+ def on_build_grid(stored_masks, stored_image, label_map, stored_raw_image):
1521
+ if stored_masks is None or stored_image is None or not label_map:
1522
+ return (gr.update(visible=False), [],
1523
+ gr.update(value="*Run viability analysis first.*", visible=True))
1524
+ masks = unpack_array(stored_masks)
1525
+ image_np = unpack_array(stored_image)
1526
+ raw_image_np = unpack_array(stored_raw_image) if stored_raw_image is not None else None
1527
+ features = extract_cell_features(image_np, masks)
1528
+ labelled = attach_viability_labels(features, masks, image_np, label_map)
1529
+ if not labelled:
1530
+ return (gr.update(visible=False), [],
1531
+ gr.update(value="*No cells found.*", visible=True))
1532
+ grid = build_correction_grid(image_np, masks, labelled, raw_image_np)
1533
+ n = len(labelled)
1534
+ dead = sum(1 for r in labelled if r["label"] == 1)
1535
+ msg = (f"*{n} cells β€” {n-dead} live (green), {dead} dead (red). "
1536
+ f"Tap any thumbnail to flip its label.*")
1537
+ return gr.update(value=grid, visible=True), labelled, gr.update(value=msg, visible=True)
1538
+
1539
+ build_grid_btn.click(
1540
+ fn=on_build_grid,
1541
+ inputs=[masks_state, image_state, label_map_state, raw_image_state],
1542
+ outputs=[correction_grid, labelled_state, correction_status]
1543
+ )
1544
+
1545
+ # ---- Grid tap β€” flip label, update overlay + counts ----------------
1546
+ def on_grid_tap(labelled, stored_masks, stored_image, stored_raw_image, evt: gr.SelectData):
1547
+ if not labelled or stored_masks is None:
1548
+ return None, labelled, "", 0, 0, 0.0, None, {}
1549
+ masks = unpack_array(stored_masks)
1550
+ image_np = unpack_array(stored_image)
1551
+ raw_image_np = unpack_array(stored_raw_image) if stored_raw_image is not None else None
1552
+ grid, updated, msg = toggle_cell_label(labelled, image_np, masks, raw_image_np, evt)
1553
+
1554
+ # Rebuild label_map from corrected labelled list
1555
+ new_label_map = {int(f["cell_id"]): int(f["label"]) for f in updated}
1556
+ overlay_np = draw_viability_overlay(image_np, masks, new_label_map)
1557
+ dead = sum(1 for f in updated if f["label"] == 1)
1558
+ alive = len(updated) - dead
1559
+ total = alive + dead
1560
+ viab_pct = (alive / total * 100) if total > 0 else 0.0
1561
+
1562
+ return (grid, updated, f"*{msg}*",
1563
+ alive, dead, viab_pct,
1564
+ Image.fromarray(overlay_np), new_label_map)
1565
+
1566
+ correction_grid.select(
1567
+ fn=on_grid_tap,
1568
+ inputs=[labelled_state, masks_state, image_state, raw_image_state],
1569
+ outputs=[correction_grid, labelled_state, correction_status,
1570
+ live_count_out, dead_count_out, viab_percent_out,
1571
+ viab_overlay, label_map_state]
1572
+ )
1573
+
1574
+ # ---- Export --------------------------------------------------------
1575
+ def on_export(stored_masks, stored_image, labelled, label_map):
1576
+ path, msg = prepare_export_corrected(stored_masks, stored_image, labelled, label_map)
1577
+ if path is None:
1578
+ return gr.update(visible=False), msg
1579
+ return gr.update(value=path, visible=True), msg
1580
+
1581
+ export_btn.click(
1582
+ fn=on_export,
1583
+ inputs=[masks_state, image_state, labelled_state, label_map_state],
1584
+ outputs=[export_file, export_info]
1585
+ )
1586
+
1587
+
1588
+
1589
+ # ---------------------------------------------------------------------------
1590
+ # Gradio interface
1591
+ # ---------------------------------------------------------------------------
1592
+ with gr.Blocks(
1593
+ title="CellposeCellCounter",
1594
+ theme=gr.themes.Soft(),
1595
+ ) as demo:
1596
+ gr.Markdown("# CellposeCellCounter")
1597
+ gr.Markdown("For accurate cell confluency, crop the image to display only desired area. Note that some image file types are not yet supported. PNG and JPEG are preferred.")
1598
+
1599
+ # Shared mask/image state (one pair per tab so tabs don't clobber each other)
1600
+ masks_states = [gr.State(value=None) for _ in range(4)]
1601
+ image_states = [gr.State(value=None) for _ in range(4)]
1602
+ result_states = [gr.State(value=None) for _ in range(4)]
1603
+
1604
+ # Build Tabs 1–4 with a loop
1605
+ for i in range(4):
1606
+ build_tab(i + 1, masks_states[i], image_states[i], result_states[i])
1607
+
1608
+ # -------------------------------------------------------------------------
1609
+ # Tab 5 β€” Summary
1610
+ # -------------------------------------------------------------------------
1611
+ with gr.Tab("Tab 5 β€” Summary"):
1612
+ gr.Markdown("## Average Results Across All Tabs")
1613
+ gr.Markdown(
1614
+ "Run segmentation in one or more tabs, "
1615
+ "then click **Refresh Summary** to see the averages."
1616
+ )
1617
+
1618
+ refresh_btn = gr.Button("πŸ”„ Refresh Summary", variant="primary", size="lg")
1619
+
1620
+ with gr.Row():
1621
+ avg_count_out = gr.Number(label="Avg Cell Count", precision=1)
1622
+ avg_conf_out = gr.Number(label="Avg Confluency (%)", precision=1)
1623
+ avg_viab_out = gr.Number(label="Avg Viability (%)", precision=1)
1624
+
1625
+ summary_box = gr.Textbox(label="Per-Tab Breakdown", lines=10)
1626
+
1627
+ refresh_btn.click(
1628
+ fn=compute_summary,
1629
+ inputs=result_states, # list of 4 gr.State components
1630
+ outputs=[avg_count_out, avg_conf_out, avg_viab_out, summary_box]
1631
+ )
1632
+
1633
+
1634
+
1635
+ if __name__ == "__main__":
1636
+ demo.launch()