edeler commited on
Commit
a0ac02e
·
verified ·
1 Parent(s): e0162a2

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +314 -84
app.py CHANGED
@@ -1,109 +1,339 @@
1
  import os
 
2
  import cv2
 
 
 
3
  import torch
4
  import gradio as gr
5
  import numpy as np
 
 
 
 
6
  from ultralytics import YOLO
7
  import supervision as sv
8
- from PIL import Image
9
- from huggingface_hub import snapshot_download
10
- import spaces # Import spaces for ZeroGPU compatibility
11
-
12
- # Adjustable parameters for detection
13
- CONFIDENCE_THRESHOLD = 0.1 # Confidence threshold for detections
14
- NMS_THRESHOLD = 0 # IoU threshold for non-maximum suppression
15
- SLICE_WIDTH = 1024 # Width of each slice
16
- SLICE_HEIGHT = 1024 # Height of each slice
17
- OVERLAP_WIDTH = 0 # Overlap width between slices
18
- OVERLAP_HEIGHT = 0 # Overlap height between slices
19
- ANNOTATION_COLOR = sv.Color.RED # Red in BGR format for OpenCV
20
- ANNOTATION_THICKNESS = 4 # Thickness of bounding box lines
21
-
22
- device = 'cuda' if torch.cuda.is_available() else 'cpu'
23
-
24
- # Download YOLO model weights from Hugging Face Hub
25
- repo_id = 'edeler/ICC' # Replace with your Hugging Face repository ID
26
- model_dir = snapshot_download(repo_id, local_dir='./models/ICC')
27
- model_path = os.path.join(model_dir, "best.pt") # Adjust if filename differs
28
- model = YOLO(model_path).to(device)
29
-
30
- # Define the detection function for Gradio
31
- @spaces.GPU # Decorator to allocate GPU for ZeroGPU-enabled Spaces
32
- def detect_objects(image: np.ndarray) -> (Image.Image, str):
33
- # Ensure the image is in BGR format if provided by PIL (Gradio gives us an RGB image)
34
- if image.shape[-1] == 3:
35
- image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
36
-
37
- # Define callback function for slice-based inference
38
- def callback(image_slice: np.ndarray) -> sv.Detections:
39
- # Run inference on each slice
40
- result = model(image_slice)[0]
41
- # Convert detections to `sv.Detections` format for further processing
42
- detections = sv.Detections.from_ultralytics(result)
43
- # Filter detections based on confidence threshold
44
- return detections[detections.confidence >= CONFIDENCE_THRESHOLD]
45
-
46
- # Initialize InferenceSlicer with adjustable slice dimensions and overlap settings
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
  slicer = sv.InferenceSlicer(
48
  callback=callback,
49
- slice_wh=(SLICE_WIDTH, SLICE_HEIGHT),
50
- overlap_wh=(OVERLAP_WIDTH, OVERLAP_HEIGHT),
51
- overlap_ratio_wh=None
52
  )
 
 
 
 
53
 
54
- # Perform slicing-based inference on the entire image
55
- detections = slicer(image)
 
 
 
 
 
 
 
 
 
56
 
57
- # Apply Non-Maximum Suppression (NMS) to the detections to avoid duplicate boxes
58
- detections = detections.with_nms(threshold=NMS_THRESHOLD, class_agnostic=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
- # Count total detections after NMS
61
- total_detections = len(detections)
 
 
 
 
 
62
 
63
- # Initialize an annotator for bounding boxes with specified color and thickness
64
- box_annotator = sv.OrientedBoxAnnotator(color=ANNOTATION_COLOR, thickness=ANNOTATION_THICKNESS)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
- # Annotate the image with bounding boxes after NMS
67
- annotated_img = box_annotator.annotate(scene=image.copy(), detections=detections)
 
68
 
69
- # Convert annotated image to RGB for Gradio display (PIL expects RGB)
70
- annotated_img_rgb = cv2.cvtColor(annotated_img, cv2.COLOR_BGR2RGB)
 
 
71
 
72
- # Return the annotated image and the total count of detections
73
- return Image.fromarray(annotated_img_rgb), f"Total Detections: {total_detections}"
 
 
 
 
 
 
 
 
 
 
 
 
74
 
75
- # Reset function for Gradio UI
76
- def gradio_reset():
77
- return gr.update(value=None), gr.update(value=None), gr.update(value="")
 
 
 
78
 
79
- # Set up Gradio interface
80
- with gr.Blocks() as demo:
81
- gr.Markdown("<h1>Interstitial Cell of Cajal Detection and Quantification Tool</h1>")
82
 
83
- # Define input image before using it in the Examples section
84
- input_img = gr.Image(label="Upload an Image", type="numpy", interactive=True)
85
-
86
- # Move the Examples section here, right after the title
87
- with gr.Accordion("Select an Example Image"):
88
- example_root = os.path.dirname(__file__) # Root directory
89
- example_images = [os.path.join(example_root, file) for file in os.listdir(example_root) if file.endswith(".jpg")]
90
- gr.Examples(
91
- examples=example_images,
92
- inputs=[input_img],
93
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
95
  with gr.Row():
96
- with gr.Column():
97
- clear = gr.Button(value="Clear")
98
- predict = gr.Button(value="Detect", variant="primary")
99
-
100
- with gr.Column():
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
101
  output_img = gr.Image(label="Detection Result", interactive=False)
102
- detection_count = gr.Textbox(label="Detection Summary", interactive=False)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
103
 
104
- # Define button actions
105
- clear.click(gradio_reset, inputs=None, outputs=[input_img, output_img, detection_count])
106
- predict.click(detect_objects, inputs=[input_img], outputs=[output_img, detection_count])
107
 
108
- # Launch Gradio app
109
- demo.launch(server_name="0.0.0.0", server_port=7860, debug=True)
 
1
  import os
2
+ import io
3
  import cv2
4
+ import sys
5
+ import math
6
+ import json
7
  import torch
8
  import gradio as gr
9
  import numpy as np
10
+ import pandas as pd
11
+ from PIL import Image
12
+ from typing import List, Tuple, Optional, Dict
13
+
14
  from ultralytics import YOLO
15
  import supervision as sv
16
+ from huggingface_hub import hf_hub_download
17
+ import spaces # ZeroGPU-compatible decorator
18
+
19
+ # -----------------------------
20
+ # Defaults / configuration
21
+ # -----------------------------
22
+ REPO_ID = "edeler/ICC" # <- your HF repo with weights
23
+ WEIGHTS_FILENAME = "best.pt" # <- adjust if different
24
+ LOCAL_MODEL_DIR = "./models/ICC"
25
+ EXAMPLES_DIR = "." # scan current repo root for demo images
26
+
27
+ # Reasonable defaults (tunable in UI)
28
+ DEFAULT_CONF = 0.25
29
+ DEFAULT_IOU = 0.50 # for both model-level and global cross-slice NMS
30
+ DEFAULT_SLICE_WH = 1024
31
+ DEFAULT_OVERLAP = 128 # helps stitching at tile borders
32
+ DEFAULT_THICKNESS = 3
33
+ DEFAULT_LONG_EDGE = 4096 # optional downscale for very large WSIs/crops
34
+
35
+ # -----------------------------
36
+ # Torch / device helpers
37
+ # -----------------------------
38
+ def get_device() -> str:
39
+ if torch.cuda.is_available():
40
+ return "cuda"
41
+ if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
42
+ return "mps"
43
+ return "cpu"
44
+
45
+ def half_precision_available(dev: str) -> bool:
46
+ return dev == "cuda"
47
+
48
+ # -----------------------------
49
+ # Model loading (lazy, cached)
50
+ # -----------------------------
51
+ _MODEL: Optional[YOLO] = None
52
+ _CLASS_NAMES: Optional[Dict[int, str]] = None
53
+
54
+ def load_model() -> Tuple[YOLO, Dict[int, str]]:
55
+ global _MODEL, _CLASS_NAMES
56
+ if _MODEL is not None and _CLASS_NAMES is not None:
57
+ return _MODEL, _CLASS_NAMES
58
+
59
+ os.makedirs(LOCAL_MODEL_DIR, exist_ok=True)
60
+ weights_path = hf_hub_download(
61
+ repo_id=REPO_ID,
62
+ filename=WEIGHTS_FILENAME,
63
+ local_dir=LOCAL_MODEL_DIR,
64
+ local_dir_use_symlinks=False, # safer in Spaces
65
+ )
66
+ model = YOLO(weights_path)
67
+ class_names = model.model.names if hasattr(model, "model") else model.names
68
+ _MODEL, _CLASS_NAMES = model, class_names
69
+ return _MODEL, _CLASS_NAMES
70
+
71
+ # -----------------------------
72
+ # Image utilities
73
+ # -----------------------------
74
+ def ensure_bgr(img: np.ndarray) -> np.ndarray:
75
+ # Gradio provides RGB; OpenCV expects BGR
76
+ if img.ndim == 3 and img.shape[2] == 3:
77
+ return cv2.cvtColor(img, cv2.COLOR_RGB2BGR)
78
+ return img
79
+
80
+ def maybe_downscale_long_edge(img: np.ndarray, target_long_edge: int) -> Tuple[np.ndarray, float]:
81
+ h, w = img.shape[:2]
82
+ long_edge = max(h, w)
83
+ if long_edge <= target_long_edge:
84
+ return img, 1.0
85
+ scale = target_long_edge / float(long_edge)
86
+ new_w = max(1, int(round(w * scale)))
87
+ new_h = max(1, int(round(h * scale)))
88
+ resized = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
89
+ return resized, scale
90
+
91
+ # -----------------------------
92
+ # Inference (sliced + global NMS)
93
+ # -----------------------------
94
+ def run_sliced_inference(
95
+ image_bgr: np.ndarray,
96
+ model: YOLO,
97
+ conf: float,
98
+ iou: float,
99
+ slice_w: int,
100
+ slice_h: int,
101
+ overlap_w: int,
102
+ overlap_h: int,
103
+ device: str,
104
+ ) -> sv.Detections:
105
+ """
106
+ Uses supervision.InferenceSlicer to run model across tiles,
107
+ then returns all detections (to be merged via cross-slice NMS).
108
+ """
109
+ # inner callback called by slicer
110
+ @torch.inference_mode()
111
+ def callback(tile_bgr: np.ndarray) -> sv.Detections:
112
+ # Ultralytics expects RGB
113
+ tile_rgb = cv2.cvtColor(tile_bgr, cv2.COLOR_BGR2RGB)
114
+ # Predict with thresholds at model level (faster than filtering post-hoc)
115
+ results = model.predict(
116
+ source=tile_rgb,
117
+ conf=conf,
118
+ iou=iou,
119
+ device=device,
120
+ verbose=False,
121
+ half=half_precision_available(device),
122
+ )
123
+ res = results[0]
124
+ det = sv.Detections.from_ultralytics(res)
125
+ return det
126
+
127
  slicer = sv.InferenceSlicer(
128
  callback=callback,
129
+ slice_wh=(slice_w, slice_h),
130
+ overlap_wh=(overlap_w, overlap_h),
131
+ overlap_ratio_wh=None,
132
  )
133
+ detections = slicer(image_bgr)
134
+ # Cross-slice NMS to merge duplicates at tile seams
135
+ detections = detections.with_nms(threshold=iou, class_agnostic=False)
136
+ return detections
137
 
138
+ # -----------------------------
139
+ # Annotation + tabular export
140
+ # -----------------------------
141
+ def make_labels(det: sv.Detections, names: Dict[int, str], show_labels: bool) -> Optional[List[str]]:
142
+ if not show_labels:
143
+ return None
144
+ labels = []
145
+ for cls, conf in zip(det.class_id, det.confidence):
146
+ cname = names.get(int(cls), str(cls))
147
+ labels.append(f"{cname} {conf:.2f}")
148
+ return labels
149
 
150
+ def detections_to_dataframe(det: sv.Detections, names: Dict[int, str]) -> pd.DataFrame:
151
+ if len(det) == 0:
152
+ return pd.DataFrame(columns=["class_id", "class_name", "confidence", "x_min", "y_min", "x_max", "y_max"])
153
+ xyxy = det.xyxy # (N,4)
154
+ data = []
155
+ for i in range(len(det)):
156
+ cls = int(det.class_id[i])
157
+ data.append({
158
+ "class_id": cls,
159
+ "class_name": names.get(cls, str(cls)),
160
+ "confidence": float(det.confidence[i]),
161
+ "x_min": float(xyxy[i, 0]),
162
+ "y_min": float(xyxy[i, 1]),
163
+ "x_max": float(xyxy[i, 2]),
164
+ "y_max": float(xyxy[i, 3]),
165
+ })
166
+ return pd.DataFrame(data)
167
 
168
+ def per_class_summary(df: pd.DataFrame) -> str:
169
+ if df.empty:
170
+ return "No detections."
171
+ counts = df.groupby("class_name").size().sort_values(ascending=False)
172
+ parts = [f"{k}: {v}" for k, v in counts.items()]
173
+ total = int(counts.sum())
174
+ return f"Total detections: {total} | " + " | ".join(parts)
175
 
176
+ # -----------------------------
177
+ # Gradio inference function
178
+ # -----------------------------
179
+ @spaces.GPU # ensures ZeroGPU allocation during this call
180
+ def detect_objects(
181
+ image: np.ndarray,
182
+ conf: float,
183
+ iou: float,
184
+ slice_w: int,
185
+ slice_h: int,
186
+ overlap_w: int,
187
+ overlap_h: int,
188
+ thickness: int,
189
+ show_labels: bool,
190
+ selected_classes: List[str],
191
+ long_edge: int,
192
+ progress=gr.Progress(track_tqdm=True),
193
+ ) -> tuple:
194
+ try:
195
+ if image is None:
196
+ raise ValueError("Please upload or select an image.")
197
 
198
+ # Prepare image (BGR) and optional downscale
199
+ image_bgr = ensure_bgr(image)
200
+ image_bgr, scale = maybe_downscale_long_edge(image_bgr, long_edge)
201
 
202
+ # Load model + names lazily
203
+ progress(0.05, desc="Loading model…")
204
+ model, names = load_model()
205
+ device = get_device()
206
 
207
+ # Inference (sliced)
208
+ progress(0.35, desc="Running sliced inference…")
209
+ with torch.inference_mode():
210
+ detections = run_sliced_inference(
211
+ image_bgr=image_bgr,
212
+ model=model,
213
+ conf=conf,
214
+ iou=iou,
215
+ slice_w=slice_w,
216
+ slice_h=slice_h,
217
+ overlap_w=overlap_w,
218
+ overlap_h=overlap_h,
219
+ device=device,
220
+ )
221
 
222
+ # Optional class filtering (by names)
223
+ if selected_classes:
224
+ allow_ids = {cid for cid, cname in names.items() if cname in set(selected_classes)}
225
+ if len(detections) > 0:
226
+ mask = np.array([int(c) in allow_ids for c in detections.class_id], dtype=bool)
227
+ detections = detections[mask]
228
 
229
+ # Create labels (optional)
230
+ labels = make_labels(detections, names, show_labels)
 
231
 
232
+ # Annotate
233
+ progress(0.65, desc="Annotating…")
234
+ annotator = sv.BoxAnnotator(thickness=thickness)
235
+ annotated = annotator.annotate(scene=image_bgr.copy(), detections=detections, labels=labels)
236
+
237
+ # Convert to RGB for display
238
+ annotated_rgb = cv2.cvtColor(annotated, cv2.COLOR_BGR2RGB)
239
+ annotated_pil = Image.fromarray(annotated_rgb)
240
+
241
+ # Tabular output + downloadable CSV
242
+ df = detections_to_dataframe(detections, names)
243
+ csv_bytes = df.to_csv(index=False).encode("utf-8")
244
+ summary = per_class_summary(df)
245
+
246
+ progress(1.0, desc="Done.")
247
+ return annotated_pil, summary, df, csv_bytes
248
+
249
+ except Exception as e:
250
+ # Return clean error in summary field
251
+ empty_img = None
252
+ empty_df = pd.DataFrame(columns=["class_id", "class_name", "confidence", "x_min", "y_min", "x_max", "y_max"])
253
+ return empty_img, f"Error: {repr(e)}", empty_df, b""
254
+
255
+ # -----------------------------
256
+ # UI / App
257
+ # -----------------------------
258
+ def discover_examples(root: str) -> List[str]:
259
+ exts = {".jpg", ".jpeg", ".png"}
260
+ paths = []
261
+ try:
262
+ for fname in os.listdir(root):
263
+ if os.path.splitext(fname.lower())[1] in exts:
264
+ paths.append(os.path.join(root, fname))
265
+ except Exception:
266
+ pass
267
+ # Keep at most a handful to keep UI tidy
268
+ return sorted(paths)[:8]
269
+
270
+ def reset_all():
271
+ # image, output_img, summary, table, download
272
+ return gr.update(value=None), gr.update(value=None), gr.update(value=""), pd.DataFrame(), None
273
+
274
+ with gr.Blocks(title="Interstitial Cell of Cajal Detection and Quantification Tool", fill_height=True) as demo:
275
+ gr.Markdown("<h1>Interstitial Cell of Cajal (ICC) Detection and Quantification</h1>"
276
+ "<p>YOLO-based tiled inference with cross-slice NMS. Adjust parameters under <em>Advanced Settings</em>.</p>")
277
 
278
  with gr.Row():
279
+ with gr.Column(scale=1):
280
+ input_img = gr.Image(label="Upload an Image", type="numpy", interactive=True)
281
+
282
+ with gr.Accordion("Examples", open=False):
283
+ examples = discover_examples(EXAMPLES_DIR)
284
+ if examples:
285
+ gr.Examples(examples=examples, inputs=[input_img])
286
+ else:
287
+ gr.Markdown("_No example images found in repository root._")
288
+
289
+ with gr.Accordion("Advanced Settings", open=False):
290
+ conf = gr.Slider(0.0, 1.0, value=DEFAULT_CONF, step=0.01, label="Confidence threshold (conf)")
291
+ iou = gr.Slider(0.0, 1.0, value=DEFAULT_IOU, step=0.01, label="IoU threshold (NMS)")
292
+ slice_w = gr.Slider(256, 2048, value=DEFAULT_SLICE_WH, step=64, label="Slice width (px)")
293
+ slice_h = gr.Slider(256, 2048, value=DEFAULT_SLICE_WH, step=64, label="Slice height (px)")
294
+ overlap_w = gr.Slider(0, 512, value=DEFAULT_OVERLAP, step=16, label="Horizontal overlap (px)")
295
+ overlap_h = gr.Slider(0, 512, value=DEFAULT_OVERLAP, step=16, label="Vertical overlap (px)")
296
+ thickness = gr.Slider(1, 8, value=DEFAULT_THICKNESS, step=1, label="Bounding box thickness")
297
+ show_labels = gr.Checkbox(value=True, label="Show class + confidence labels")
298
+ long_edge = gr.Slider(512, 8192, value=DEFAULT_LONG_EDGE, step=64, label="Optional downscale — max long edge (px)")
299
+ # Dynamic class list (populated on load)
300
+ # We attempt to load names now; if it fails (cold start), we show an empty multiselect.
301
+ try:
302
+ _, _names = load_model()
303
+ class_list = [v for _, v in sorted(_names.items())]
304
+ except Exception:
305
+ class_list = []
306
+ selected_classes = gr.CheckboxGroup(choices=class_list, label="Filter by class (optional)")
307
+
308
+ with gr.Row():
309
+ predict = gr.Button(value="Detect", variant="primary")
310
+ clear = gr.Button(value="Clear")
311
+
312
+ with gr.Column(scale=1):
313
  output_img = gr.Image(label="Detection Result", interactive=False)
314
+ detection_summary = gr.Textbox(label="Detection Summary", interactive=False)
315
+ detections_table = gr.Dataframe(
316
+ headers=["class_id", "class_name", "confidence", "x_min", "y_min", "x_max", "y_max"],
317
+ label="Detections (table)",
318
+ interactive=False,
319
+ wrap=True,
320
+ height=240,
321
+ )
322
+ download_csv = gr.DownloadButton(label="Download detections as CSV", value=None, file_name="detections.csv")
323
+
324
+ # Wire buttons
325
+ predict.click(
326
+ detect_objects,
327
+ inputs=[input_img, conf, iou, slice_w, slice_h, overlap_w, overlap_h, thickness, show_labels, selected_classes, long_edge],
328
+ outputs=[output_img, detection_summary, detections_table, download_csv],
329
+ )
330
+ clear.click(
331
+ reset_all,
332
+ inputs=None,
333
+ outputs=[input_img, output_img, detection_summary, detections_table, download_csv],
334
+ )
335
 
336
+ # Recommended for Spaces stability / concurrency
337
+ demo.queue(max_size=16, concurrency_count=1)
338
+ demo.launch(server_name="0.0.0.0", server_port=7860, debug=False)
339