Update app.py
Browse files
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
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
slicer = sv.InferenceSlicer(
|
| 48 |
callback=callback,
|
| 49 |
-
slice_wh=(
|
| 50 |
-
overlap_wh=(
|
| 51 |
-
overlap_ratio_wh=None
|
| 52 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 59 |
|
| 60 |
-
|
| 61 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 62 |
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
-
|
| 67 |
-
|
|
|
|
| 68 |
|
| 69 |
-
|
| 70 |
-
|
|
|
|
|
|
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
#
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
|
| 81 |
-
gr.Markdown("<h1>Interstitial Cell of Cajal Detection and Quantification Tool</h1>")
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
|
| 95 |
with gr.Row():
|
| 96 |
-
with gr.Column():
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
output_img = gr.Image(label="Detection Result", interactive=False)
|
| 102 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 103 |
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 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 |
|
|
|
|
|
|