Spaces:
Sleeping
Sleeping
File size: 21,252 Bytes
47cb9bd cf8afa8 47cb9bd 496261a 47cb9bd 496261a 47cb9bd 496261a 47cb9bd 496261a 47cb9bd 496261a 47cb9bd 496261a 47cb9bd 496261a 47cb9bd 3f1b42a | 1 2 3 4 5 6 7 8 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 48 49 50 51 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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 | """
app.py β OWLv2 / SAM2 image labeling UI
Tab 1 β Test: upload one image, pick Detection or Segmentation mode,
tune prompts/threshold/size, see instant annotated results.
Tab 2 β Batch: upload multiple images, run in the chosen mode, download a ZIP
containing resized images + coco_export.json.
All artifacts live in a system temp directory β nothing is written to the project.
"""
from __future__ import annotations
# spaces MUST be imported before torch initialises CUDA (i.e. before any
# autolabel import). Do this first, before everything else.
try:
import spaces as _spaces # type: ignore
_ZERO_GPU = True
except (ImportError, RuntimeError):
_spaces = None
_ZERO_GPU = False
import os
os.environ.setdefault("PYTORCH_ENABLE_MPS_FALLBACK", "1")
import logging
import shutil
import tempfile
import zipfile
from pathlib import Path
from typing import Optional
import gradio as gr
import numpy as np
from dotenv import load_dotenv
from PIL import Image, ImageDraw, ImageFont
load_dotenv()
from autolabel.config import settings
from autolabel.detect import infer as _owlv2_infer
from autolabel.export import build_coco
from autolabel.segment import load_sam2, segment_with_boxes
from autolabel.utils import save_json, setup_logging
setup_logging(logging.INFO)
logger = logging.getLogger(__name__)
# Temp directory for this session β cleaned up by the OS on reboot
_TMPDIR = Path(tempfile.mkdtemp(prefix="autolabel_"))
logger.info("Session temp dir: %s", _TMPDIR)
# ---------------------------------------------------------------------------
# Image sizing
# ---------------------------------------------------------------------------
_SIZE_OPTIONS = {
"As is": None,
"416 Γ 416": (416, 416),
"480 Γ 480": (480, 480),
"512 Γ 512": (512, 512),
"640 Γ 640": (640, 640),
"736 Γ 736": (736, 736),
"896 Γ 896": (896, 896),
"1024 Γ 1024": (1024, 1024),
}
_SIZE_LABELS = list(_SIZE_OPTIONS.keys())
def _resize(pil: Image.Image, size_label: str) -> Image.Image:
target = _SIZE_OPTIONS[size_label]
if target is None:
return pil
return pil.resize(target, Image.LANCZOS)
# ---------------------------------------------------------------------------
# Colours & annotation
# ---------------------------------------------------------------------------
_PALETTE = [
(52, 211, 153), (251, 146, 60), (96, 165, 250), (248, 113, 113),
(167, 139, 250),(250, 204, 21), (34, 211, 238), (244, 114, 182),
(74, 222, 128), (232, 121, 249), (125, 211, 252), (253, 186, 116),
(110, 231, 183),(196, 181, 253), (253, 164, 175), (134, 239, 172),
]
def _colour_for(label: str, prompts: list[str]) -> tuple[int, int, int]:
try:
return _PALETTE[prompts.index(label) % len(_PALETTE)]
except ValueError:
return _PALETTE[hash(label) % len(_PALETTE)]
def _annotate(
pil_image: Image.Image,
detections: list[dict],
prompts: list[str],
mode: str = "Detection",
) -> Image.Image:
"""Draw bounding boxes (+ mask overlays in Segmentation mode) on *pil_image*."""
img = pil_image.copy().convert("RGBA")
# --- Segmentation: paint semi-transparent mask overlays first ---
if mode == "Segmentation":
overlay = Image.new("RGBA", img.size, (0, 0, 0, 0))
for det in detections:
mask = det.get("mask")
if mask is None or not isinstance(mask, np.ndarray):
continue
r, g, b = _colour_for(det["label"], prompts)
mask_rgba = np.zeros((mask.shape[0], mask.shape[1], 4), dtype=np.uint8)
mask_rgba[mask] = [r, g, b, 100] # semi-transparent fill
overlay = Image.alpha_composite(overlay, Image.fromarray(mask_rgba, "RGBA"))
img = Image.alpha_composite(img, overlay)
# --- Bounding boxes and labels (both modes) ---
draw = ImageDraw.Draw(img, "RGBA")
try:
font = ImageFont.truetype("/System/Library/Fonts/Helvetica.ttc", size=18)
except Exception:
font = ImageFont.load_default()
for det in detections:
x1, y1, x2, y2 = det["box_xyxy"]
r, g, b = _colour_for(det["label"], prompts)
draw.rectangle([x1, y1, x2, y2], outline=(r, g, b), width=3)
tag = f"{det['label']} {det['score']:.2f}"
bbox = draw.textbbox((x1, y1), tag, font=font)
draw.rectangle([bbox[0]-3, bbox[1]-3, bbox[2]+3, bbox[3]+3], fill=(r, g, b, 210))
draw.text((x1, y1), tag, fill=(255, 255, 255), font=font)
return img.convert("RGB")
# ---------------------------------------------------------------------------
# OWLv2 model (cached)
# ---------------------------------------------------------------------------
_owlv2_cache: dict = {}
def _get_owlv2():
if settings.model not in _owlv2_cache:
_owlv2_cache.clear()
from transformers import Owlv2ForObjectDetection, Owlv2Processor
logger.info("Loading OWLv2 %s on %s β¦", settings.model, settings.device)
processor = Owlv2Processor.from_pretrained(settings.model)
model = Owlv2ForObjectDetection.from_pretrained(
settings.model, torch_dtype=settings.torch_dtype
).to(settings.device)
model.eval()
_owlv2_cache[settings.model] = (processor, model)
logger.info("OWLv2 ready.")
return _owlv2_cache[settings.model]
# ---------------------------------------------------------------------------
# SAM2 model (cached)
# ---------------------------------------------------------------------------
_sam2_cache: dict = {}
_SAM2_MODEL_ID = "facebook/sam2-hiera-tiny"
def _get_sam2():
if _SAM2_MODEL_ID not in _sam2_cache:
processor, model = load_sam2(settings.device, _SAM2_MODEL_ID)
_sam2_cache[_SAM2_MODEL_ID] = (processor, model)
return _sam2_cache[_SAM2_MODEL_ID]
# ---------------------------------------------------------------------------
# Shared inference helpers
# ---------------------------------------------------------------------------
def _infer_on_device(
pil_image: Image.Image,
prompts: list[str],
threshold: float,
mode: str,
device: str,
dtype,
) -> list[dict]:
"""Run OWLv2 (+ optional SAM2) with explicit device/dtype.
In ZeroGPU mode this is called inside the @spaces.GPU context so CUDA is
available; locally it uses whatever settings.device resolved to.
"""
processor, owlv2 = _get_owlv2()
owlv2.to(device)
try:
detections = _owlv2_infer(
pil_image, processor, owlv2, prompts, threshold, device, dtype,
)
finally:
if _ZERO_GPU:
owlv2.to("cpu") # release VRAM back to ZeroGPU pool
if mode == "Segmentation" and detections:
sam2_processor, sam2_model = _get_sam2()
sam2_model.to(device)
try:
detections = segment_with_boxes(
pil_image, detections, sam2_processor, sam2_model, device
)
finally:
if _ZERO_GPU:
sam2_model.to("cpu")
return detections
if _ZERO_GPU:
@_spaces.GPU
def _run_detection(
pil_image: Image.Image,
prompts: list[str],
threshold: float,
mode: str,
) -> list[dict]:
"""ZeroGPU entry-point: GPU is allocated for the duration of this call."""
import torch
return _infer_on_device(
pil_image, prompts, threshold, mode,
device="cuda", dtype=torch.float16,
)
else:
def _run_detection(
pil_image: Image.Image,
prompts: list[str],
threshold: float,
mode: str,
) -> list[dict]:
return _infer_on_device(
pil_image, prompts, threshold, mode,
device=settings.device, dtype=settings.torch_dtype,
)
def _parse_prompts(text: str) -> list[str]:
return [p.strip() for p in text.split(",") if p.strip()]
# ---------------------------------------------------------------------------
# Object crops
# ---------------------------------------------------------------------------
def _make_crops(
pil_image: Image.Image,
detections: list[dict],
prompts: list[str],
mode: str,
) -> list[tuple[Image.Image, str]]:
"""Return one (cropped PIL image, caption) pair per detection.
Detection mode: plain bounding-box crop with a coloured border.
Segmentation mode: tight crop around the mask's nonzero region; pixels
outside the mask are set to white for a clean cutout.
"""
crops: list[tuple[Image.Image, str]] = []
img_w, img_h = pil_image.size
for det in detections:
x1, y1, x2, y2 = det["box_xyxy"]
x1 = max(0, int(x1)); y1 = max(0, int(y1))
x2 = min(img_w, int(x2)); y2 = min(img_h, int(y2))
if x2 <= x1 or y2 <= y1:
continue
r, g, b = _colour_for(det["label"], prompts)
if mode == "Segmentation":
mask = det.get("mask")
if mask is not None and isinstance(mask, np.ndarray):
# Find the tight bounding box of the mask's nonzero region
rows = np.any(mask, axis=1)
cols = np.any(mask, axis=0)
if rows.any() and cols.any():
r_min, r_max = int(np.where(rows)[0][0]), int(np.where(rows)[0][-1])
c_min, c_max = int(np.where(cols)[0][0]), int(np.where(cols)[0][-1])
mask_tight = mask[r_min:r_max + 1, c_min:c_max + 1]
region = np.array(
pil_image.crop((c_min, r_min, c_max + 1, r_max + 1)).convert("RGB")
)
# White background outside the mask
region[~mask_tight] = [255, 255, 255]
crop_rgb = Image.fromarray(region)
else:
crop_rgb = pil_image.crop((x1, y1, x2, y2)).convert("RGB")
else:
crop_rgb = pil_image.crop((x1, y1, x2, y2)).convert("RGB")
else:
crop_rgb = pil_image.crop((x1, y1, x2, y2)).convert("RGB")
# Coloured border
bordered = Image.new("RGB", (crop_rgb.width + 6, crop_rgb.height + 6), (r, g, b))
bordered.paste(crop_rgb, (3, 3))
caption = f"{det['label']} {det['score']:.2f}"
crops.append((bordered, caption))
return crops
# ---------------------------------------------------------------------------
# Tab 1 β Test
# ---------------------------------------------------------------------------
def run_test(
image_np: Optional[np.ndarray],
prompts_text: str,
threshold: float,
size_label: str,
mode: str,
):
if image_np is None or not prompts_text.strip():
return image_np, [], []
prompts = _parse_prompts(prompts_text)
if not prompts:
return image_np, [], []
pil = _resize(Image.fromarray(image_np), size_label)
detections = _run_detection(pil, prompts, threshold, mode)
table = [
[i + 1, d["label"], f"{d['score']:.3f}",
f"[{d['box_xyxy'][0]:.0f}, {d['box_xyxy'][1]:.0f}, "
f"{d['box_xyxy'][2]:.0f}, {d['box_xyxy'][3]:.0f}]"]
for i, d in enumerate(detections)
]
crops = _make_crops(pil, detections, prompts, mode)
return np.array(_annotate(pil, detections, prompts, mode)), table, crops
# ---------------------------------------------------------------------------
# Tab 2 β Batch
# ---------------------------------------------------------------------------
def run_batch(files, prompts_text: str, threshold: float, size_label: str, mode: str):
if not files or not prompts_text.strip():
return [], "Upload images and enter prompts to get started.", None
prompts = _parse_prompts(prompts_text)
if not prompts:
return [], "No valid prompts.", None
# Fresh temp dir for this run
run_dir = _TMPDIR / "current_run"
if run_dir.exists():
shutil.rmtree(run_dir)
images_dir = run_dir / "images"
images_dir.mkdir(parents=True)
gallery: list[Image.Image] = []
total_dets = 0
for f in files:
try:
src = Path(f.name if hasattr(f, "name") else str(f))
pil = _resize(Image.open(src).convert("RGB"), size_label)
w, h = pil.size
detections = _run_detection(pil, prompts, threshold, mode)
total_dets += len(detections)
# Save resized image (included in the ZIP)
img_name = src.name
pil.save(images_dir / img_name)
# Per-image JSON consumed by build_coco.
# Drop numpy mask arrays β they are not JSON-serialisable.
json_dets = [
{k: v for k, v in det.items() if k != "mask"}
for det in detections
]
save_json(
{"image_path": img_name, "image_width": w,
"image_height": h, "detections": json_dets},
run_dir / (src.stem + ".json"),
)
gallery.append(_annotate(pil, detections, prompts, mode))
except Exception:
logger.exception("Failed to process %s", f)
# Build COCO JSON
coco = build_coco(run_dir)
coco_path = run_dir / "coco_export.json"
if coco:
save_json(coco, coco_path)
# Package everything into a ZIP
zip_path = run_dir / "autolabel_export.zip"
with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zf:
if coco_path.exists():
zf.write(coco_path, "coco_export.json")
for img_file in sorted(images_dir.iterdir()):
zf.write(img_file, f"images/{img_file.name}")
n_ann = len(coco.get("annotations", [])) if coco else 0
size_note = f" Β· resized to {size_label}" if size_label != "As is" else ""
mode_note = f" Β· {mode.lower()}"
stats = (
f"{len(gallery)} image(s) Β· {total_dets} detection(s) Β· "
f"{n_ann} annotations{size_note}{mode_note}"
)
return gallery, stats, str(zip_path)
# ---------------------------------------------------------------------------
# UI
# ---------------------------------------------------------------------------
_DEFAULT_PROMPTS = ", ".join(settings.prompts[:8])
_HOW_IT_WORKS_MD = """\
## How it works
| Mode | Models | Output |
|------|--------|--------|
| **Detection** | OWLv2 | Bounding boxes + class labels |
| **Segmentation** | OWLv2 β SAM2 | Bounding boxes + pixel masks + COCO polygons |
**Detection** uses [OWLv2](https://huggingface.co/google/owlv2-large-patch14-finetuned), an
open-vocabulary detector that converts your text prompts directly into bounding boxes β no
fixed class list required.
**Segmentation** uses the **Grounded SAM2** pattern:
1. **OWLv2** reads your text prompts and produces bounding boxes
2. **SAM2** (`sam2-hiera-tiny`) takes each box as a spatial prompt and refines it into a
pixel-level mask
SAM2 has no concept of text β it only understands spatial prompts (boxes, points, masks).
OWLv2 acts as the *grounding* step, translating words into coordinates that SAM2 can use.
Both models must run in Segmentation mode; Detection mode skips SAM2 entirely.
"""
with gr.Blocks(title="autolabel") as demo:
gr.Markdown("# autolabel β OWLv2 + SAM2")
with gr.Accordion("βΉοΈ How it works", open=False):
gr.Markdown(_HOW_IT_WORKS_MD)
with gr.Tabs():
# ββ Tab 1: Test ββββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Tab("π§ͺ Test"):
with gr.Row():
with gr.Column(scale=1):
t1_image = gr.Image(label="Image β upload, paste, or pick a sample below",
type="numpy", sources=["upload", "clipboard"])
t1_mode = gr.Radio(
["Detection", "Segmentation"],
label="Mode", value="Detection",
info="Detection: OWLv2 β boxes only. "
"Segmentation: OWLv2 β boxes β SAM2 β pixel masks.",
)
t1_prompts = gr.Textbox(label="Prompts (comma-separated)",
value=_DEFAULT_PROMPTS, lines=2)
t1_threshold = gr.Slider(label="Threshold", minimum=0.01,
maximum=0.9, step=0.01, value=settings.threshold)
t1_size = gr.Dropdown(label="Input size", choices=_SIZE_LABELS,
value="As is")
t1_btn = gr.Button("Detect", variant="primary")
with gr.Column(scale=1):
t1_output = gr.Image(label="Result", type="numpy")
t1_table = gr.Dataframe(
headers=["#", "Label", "Score", "Box (xyxy)"],
row_count=(0, "dynamic"), column_count=(4, "fixed"),
)
t1_crops = gr.Gallery(
label="Object crops",
columns=4, height=220,
object_fit="contain", show_label=True,
)
# Sample images β click any thumbnail to load it into the image input
_SAMPLES_DIR = Path(__file__).parent / "samples"
gr.Examples(
label="Sample images (click to load)",
examples=[
[str(_SAMPLES_DIR / "animals.jpg"), "Detection",
"crown, necklace, ball, animal eye", 0.40, "As is"],
[str(_SAMPLES_DIR / "kitchen.jpg"), "Detection",
"apple, banana, orange, broccoli, carrot, bottle, bowl", 0.40, "As is"],
[str(_SAMPLES_DIR / "dog.jpg"), "Detection",
"dog", 0.40, "As is"],
[str(_SAMPLES_DIR / "cat.jpg"), "Detection",
"cat", 0.40, "As is"]
],
inputs=[t1_image, t1_mode, t1_prompts, t1_threshold, t1_size],
examples_per_page=5,
cache_examples=False,
)
t1_btn.click(
run_test,
inputs=[t1_image, t1_prompts, t1_threshold, t1_size, t1_mode],
outputs=[t1_output, t1_table, t1_crops],
)
t1_prompts.submit(
run_test,
inputs=[t1_image, t1_prompts, t1_threshold, t1_size, t1_mode],
outputs=[t1_output, t1_table, t1_crops],
)
# ββ Tab 2: Batch βββββββββββββββββββββββββββββββββββββββββββββββββ
with gr.Tab("π Batch"):
with gr.Row():
with gr.Column(scale=1):
t2_files = gr.File(label="Images", file_count="multiple",
file_types=["image"])
t2_mode = gr.Radio(
["Detection", "Segmentation"],
label="Mode", value="Detection",
info="Detection: OWLv2 β boxes only. "
"Segmentation: OWLv2 β boxes β SAM2 β pixel masks.",
)
t2_prompts = gr.Textbox(label="Prompts (comma-separated)",
value=_DEFAULT_PROMPTS, lines=2)
t2_threshold = gr.Slider(label="Threshold", minimum=0.01,
maximum=0.9, step=0.01, value=settings.threshold)
t2_size = gr.Dropdown(label="Input size", choices=_SIZE_LABELS,
value="640 Γ 640")
t2_btn = gr.Button("Run", variant="primary")
t2_stats = gr.Textbox(label="Stats", interactive=False)
t2_download = gr.DownloadButton(
label="Download ZIP (images + COCO JSON)",
visible=False, variant="secondary", size="sm",
)
with gr.Column(scale=2):
t2_gallery = gr.Gallery(label="Results", columns=3,
height="auto", object_fit="contain")
def _run_and_reveal(files, prompts_text, threshold, size_label, mode):
gallery, stats, zip_path = run_batch(
files, prompts_text, threshold, size_label, mode
)
return gallery, stats, gr.update(value=zip_path, visible=zip_path is not None)
t2_btn.click(
_run_and_reveal,
inputs=[t2_files, t2_prompts, t2_threshold, t2_size, t2_mode],
outputs=[t2_gallery, t2_stats, t2_download],
)
demo.queue(max_size=5)
if __name__ == "__main__":
demo.launch(server_name="0.0.0.0", server_port=7860,
share=False, inbrowser=True, theme=gr.themes.Soft())
|