Spaces:
Running
on
Zero
Running
on
Zero
Update app.py
Browse files
app.py
CHANGED
|
@@ -2,17 +2,17 @@ import os
|
|
| 2 |
import io
|
| 3 |
import time
|
| 4 |
import json
|
|
|
|
| 5 |
import tempfile
|
| 6 |
from uuid import uuid4
|
| 7 |
-
from typing import List, Tuple
|
| 8 |
|
| 9 |
import gradio as gr
|
| 10 |
from PIL import Image
|
| 11 |
import numpy as np
|
| 12 |
import torch
|
| 13 |
from transformers import AutoImageProcessor, AutoModel
|
| 14 |
-
import spaces
|
| 15 |
-
|
| 16 |
|
| 17 |
# ---------------------------
|
| 18 |
# Models and config
|
|
@@ -27,7 +27,6 @@ DEFAULT_MODEL = "ViT-B/16 LVD-1689M"
|
|
| 27 |
|
| 28 |
HF_TOKEN = os.getenv("HF_TOKEN", None) # set in Space Secrets after requesting gated access
|
| 29 |
|
| 30 |
-
|
| 31 |
# ---------------------------
|
| 32 |
# ZeroGPU booking helpers
|
| 33 |
# ---------------------------
|
|
@@ -40,6 +39,9 @@ def _gpu_duration_gallery(files: List[str], *_args, **_kwargs) -> int:
|
|
| 40 |
n = max(1, len(files) if files else 1)
|
| 41 |
return min(600, 35 * n + 30)
|
| 42 |
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
# ---------------------------
|
| 45 |
# Model loading and core logic
|
|
@@ -47,9 +49,7 @@ def _gpu_duration_gallery(files: List[str], *_args, **_kwargs) -> int:
|
|
| 47 |
def _load(model_id: str):
|
| 48 |
# Use token for gated checkpoints
|
| 49 |
processor = AutoImageProcessor.from_pretrained(
|
| 50 |
-
model_id,
|
| 51 |
-
use_fast=True,
|
| 52 |
-
token=HF_TOKEN if HF_TOKEN else None,
|
| 53 |
)
|
| 54 |
model = AutoModel.from_pretrained(
|
| 55 |
model_id,
|
|
@@ -60,6 +60,11 @@ def _load(model_id: str):
|
|
| 60 |
model.to("cuda").eval()
|
| 61 |
return processor, model
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
def _extract_core(image: Image.Image, model_id: str, pooling: str, want_overlay: bool):
|
| 65 |
"""
|
|
@@ -68,50 +73,43 @@ def _extract_core(image: Image.Image, model_id: str, pooling: str, want_overlay:
|
|
| 68 |
t0 = time.time()
|
| 69 |
processor, model = _load(model_id)
|
| 70 |
|
| 71 |
-
# Keep BatchFeature when possible, but handle dict too
|
| 72 |
bf = processor(images=image, return_tensors="pt")
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
pixel_values = bf["pixel_values"]
|
| 76 |
-
else:
|
| 77 |
-
bf = {k: v.to("cuda") for k, v in bf.items()}
|
| 78 |
-
pixel_values = bf["pixel_values"]
|
| 79 |
|
| 80 |
with torch.amp.autocast("cuda", dtype=torch.float16), torch.inference_mode():
|
| 81 |
out = model(**bf)
|
| 82 |
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
|
|
|
|
|
|
| 87 |
else:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
emb = feat.mean(dim=(1, 2))
|
| 98 |
emb = emb.float().cpu().numpy()
|
| 99 |
|
| 100 |
# Optional simple heat overlay for ViT
|
| 101 |
overlay = None
|
| 102 |
-
if want_overlay and out.last_hidden_state.ndim == 3:
|
| 103 |
num_regs = getattr(model.config, "num_register_tokens", 0)
|
| 104 |
-
patch_tokens = out.last_hidden_state[0, 1 + num_regs :]
|
| 105 |
num_patches = patch_tokens.shape[0]
|
| 106 |
-
|
| 107 |
-
# Prefer square grid from token count, else fall back to pixel/patch size
|
| 108 |
h = int(num_patches ** 0.5)
|
| 109 |
w = h
|
| 110 |
if h * w != num_patches:
|
| 111 |
patch = getattr(model.config, "patch_size", 16)
|
| 112 |
h = int(pixel_values.shape[-2] // patch)
|
| 113 |
w = int(pixel_values.shape[-1] // patch)
|
| 114 |
-
|
| 115 |
mags = patch_tokens.norm(dim=1).reshape(h, w)
|
| 116 |
mags = (mags - mags.min()) / max(1e-8, (mags.max() - mags.min()))
|
| 117 |
m = (mags.cpu().numpy() * 255).astype(np.uint8)
|
|
@@ -126,32 +124,8 @@ def _extract_core(image: Image.Image, model_id: str, pooling: str, want_overlay:
|
|
| 126 |
}
|
| 127 |
return emb, overlay, meta
|
| 128 |
|
| 129 |
-
|
| 130 |
# ---------------------------
|
| 131 |
-
#
|
| 132 |
-
# ---------------------------
|
| 133 |
-
@spaces.GPU(duration=_gpu_duration_single)
|
| 134 |
-
def extract_embedding(image: Image.Image, model_name: str, pooling: str, want_overlay: bool):
|
| 135 |
-
if image is None:
|
| 136 |
-
return None, "[]", {"error": "No image"}, None
|
| 137 |
-
if not torch.cuda.is_available():
|
| 138 |
-
raise RuntimeError("CUDA not available. Ensure Space hardware is ZeroGPU.")
|
| 139 |
-
|
| 140 |
-
model_id = MODELS[model_name]
|
| 141 |
-
emb, overlay, meta = _extract_core(image, model_id, pooling, want_overlay)
|
| 142 |
-
|
| 143 |
-
# Preview + file save for gr.File
|
| 144 |
-
head = ", ".join(f"{x:.4f}" for x in emb[:16])
|
| 145 |
-
preview = f"[{head}{', ...' if emb.size > 16 else ''}]"
|
| 146 |
-
out_path = os.path.join(tempfile.gettempdir(), f"embedding_{uuid4().hex}.npy")
|
| 147 |
-
np.save(out_path, emb.astype(np.float32), allow_pickle=False)
|
| 148 |
-
|
| 149 |
-
# Return: gr.Image, gr.Textbox, gr.JSON, gr.File
|
| 150 |
-
return overlay if overlay else image, preview, meta, out_path
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
# ---------------------------
|
| 154 |
-
# Multi image similarity (ZeroGPU)
|
| 155 |
# ---------------------------
|
| 156 |
def _open_images_from_paths(paths: List[str]) -> List[Image.Image]:
|
| 157 |
imgs: List[Image.Image] = []
|
|
@@ -166,7 +140,9 @@ def _open_images_from_paths(paths: List[str]) -> List[Image.Image]:
|
|
| 166 |
def _to_html_table(S: np.ndarray, names: List[str]) -> str:
|
| 167 |
# simple accessible HTML table render
|
| 168 |
names_safe = [os.path.basename(n) for n in names]
|
| 169 |
-
header = "<tr><th></th>" + "".join(
|
|
|
|
|
|
|
| 170 |
rows = []
|
| 171 |
for i, r in enumerate(S):
|
| 172 |
cells = "".join(f"<td style='padding:6px 8px;text-align:center'>{v:.3f}</td>" for v in r)
|
|
@@ -181,7 +157,32 @@ def _to_html_table(S: np.ndarray, names: List[str]) -> str:
|
|
| 181 |
"""
|
| 182 |
return table
|
| 183 |
|
|
|
|
|
|
|
|
|
|
| 184 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 185 |
@spaces.GPU(duration=_gpu_duration_gallery)
|
| 186 |
def batch_similarity(files: List[str], model_name: str, pooling: str):
|
| 187 |
paths = files or []
|
|
@@ -189,33 +190,136 @@ def batch_similarity(files: List[str], model_name: str, pooling: str):
|
|
| 189 |
return "<em>Upload at least 2 images</em>", None
|
| 190 |
if not torch.cuda.is_available():
|
| 191 |
raise RuntimeError("CUDA not available. Ensure ZeroGPU is selected.")
|
| 192 |
-
|
| 193 |
model_id = MODELS[model_name]
|
| 194 |
imgs = _open_images_from_paths(paths)
|
| 195 |
embs = []
|
| 196 |
for img in imgs:
|
| 197 |
e, _, _ = _extract_core(img, model_id, pooling, want_overlay=False)
|
| 198 |
embs.append(e)
|
| 199 |
-
|
| 200 |
if len(embs) < 2:
|
| 201 |
return "<em>Failed to read or embed images</em>", None
|
| 202 |
-
|
| 203 |
X = np.vstack(embs).astype(np.float32)
|
| 204 |
-
Xn =
|
| 205 |
S = Xn @ Xn.T
|
| 206 |
-
|
| 207 |
# save CSV and build HTML table
|
| 208 |
csv_path = os.path.join(tempfile.gettempdir(), f"cosine_{uuid4().hex}.csv")
|
| 209 |
np.savetxt(csv_path, S, delimiter=",", fmt="%.6f")
|
| 210 |
html = _to_html_table(S, paths)
|
| 211 |
return html, csv_path
|
| 212 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
|
| 214 |
# ---------------------------
|
| 215 |
# UI
|
| 216 |
# ---------------------------
|
| 217 |
with gr.Blocks() as app:
|
| 218 |
-
gr.Markdown("# DINOv3
|
| 219 |
|
| 220 |
with gr.Accordion("Paper and Citation", open=False):
|
| 221 |
gr.Markdown("""
|
|
@@ -234,7 +338,8 @@ with gr.Blocks() as app:
|
|
| 234 |
url={[https://arxiv.org/abs/2508.10104}](https://arxiv.org/abs/2508.10104}),
|
| 235 |
}
|
| 236 |
``` """)
|
| 237 |
-
|
|
|
|
| 238 |
with gr.Tab("Single"):
|
| 239 |
with gr.Row():
|
| 240 |
with gr.Column():
|
|
@@ -248,19 +353,31 @@ with gr.Blocks() as app:
|
|
| 248 |
preview = gr.Textbox(label="Embedding head", max_lines=2)
|
| 249 |
meta = gr.JSON(label="Meta")
|
| 250 |
download = gr.File(label="embedding.npy")
|
|
|
|
| 251 |
run_btn.click(extract_embedding, [img, model_dd, pooling, overlay], [out_img, preview, meta, download])
|
| 252 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 253 |
with gr.Tab("Cosine Sim"):
|
| 254 |
gr.Markdown("Upload multiple images. We compute a cosine similarity matrix on GPU and return a CSV.")
|
| 255 |
-
# Input as Files so you can multi-upload, plus a Gallery preview
|
| 256 |
files_in = gr.Files(label="Upload images", file_types=["image"], file_count="multiple", type="filepath")
|
| 257 |
gallery_preview = gr.Gallery(label="Preview", columns=4, height=300)
|
| 258 |
model_dd2 = gr.Dropdown(choices=list(MODELS.keys()), value=DEFAULT_MODEL, label="Backbone")
|
| 259 |
pooling2 = gr.Radio(["CLS", "Mean of patch tokens"], value="CLS", label="Pooling")
|
| 260 |
go = gr.Button("Compute cosine on GPU")
|
| 261 |
-
table = gr.HTML(label="Cosine similarity")
|
| 262 |
csv = gr.File(label="cosine_similarity_matrix.csv")
|
| 263 |
-
|
| 264 |
def _preview(paths):
|
| 265 |
if not paths:
|
| 266 |
return []
|
|
@@ -271,11 +388,57 @@ with gr.Blocks() as app:
|
|
| 271 |
except Exception:
|
| 272 |
pass
|
| 273 |
return imgs
|
| 274 |
-
|
| 275 |
files_in.change(_preview, inputs=files_in, outputs=gallery_preview)
|
| 276 |
go.click(batch_similarity, [files_in, model_dd2, pooling2], [table, csv])
|
| 277 |
|
|
|
|
|
|
|
|
|
|
| 278 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 279 |
|
| 280 |
if __name__ == "__main__":
|
| 281 |
app.queue().launch()
|
|
|
|
| 2 |
import io
|
| 3 |
import time
|
| 4 |
import json
|
| 5 |
+
import glob
|
| 6 |
import tempfile
|
| 7 |
from uuid import uuid4
|
| 8 |
+
from typing import List, Tuple, Dict
|
| 9 |
|
| 10 |
import gradio as gr
|
| 11 |
from PIL import Image
|
| 12 |
import numpy as np
|
| 13 |
import torch
|
| 14 |
from transformers import AutoImageProcessor, AutoModel
|
| 15 |
+
import spaces
|
|
|
|
| 16 |
|
| 17 |
# ---------------------------
|
| 18 |
# Models and config
|
|
|
|
| 27 |
|
| 28 |
HF_TOKEN = os.getenv("HF_TOKEN", None) # set in Space Secrets after requesting gated access
|
| 29 |
|
|
|
|
| 30 |
# ---------------------------
|
| 31 |
# ZeroGPU booking helpers
|
| 32 |
# ---------------------------
|
|
|
|
| 39 |
n = max(1, len(files) if files else 1)
|
| 40 |
return min(600, 35 * n + 30)
|
| 41 |
|
| 42 |
+
def _gpu_duration_classify(*_args, **_kwargs) -> int:
|
| 43 |
+
# small buffer for 1 query plus a handful of centroids
|
| 44 |
+
return 90
|
| 45 |
|
| 46 |
# ---------------------------
|
| 47 |
# Model loading and core logic
|
|
|
|
| 49 |
def _load(model_id: str):
|
| 50 |
# Use token for gated checkpoints
|
| 51 |
processor = AutoImageProcessor.from_pretrained(
|
| 52 |
+
model_id, use_fast=True, token=HF_TOKEN if HF_TOKEN else None,
|
|
|
|
|
|
|
| 53 |
)
|
| 54 |
model = AutoModel.from_pretrained(
|
| 55 |
model_id,
|
|
|
|
| 60 |
model.to("cuda").eval()
|
| 61 |
return processor, model
|
| 62 |
|
| 63 |
+
def _to_cuda_batchfeature(bf):
|
| 64 |
+
# Keep BatchFeature when possible, but handle dict too
|
| 65 |
+
if hasattr(bf, "to"):
|
| 66 |
+
return bf.to("cuda")
|
| 67 |
+
return {k: v.to("cuda") for k, v in bf.items()}
|
| 68 |
|
| 69 |
def _extract_core(image: Image.Image, model_id: str, pooling: str, want_overlay: bool):
|
| 70 |
"""
|
|
|
|
| 73 |
t0 = time.time()
|
| 74 |
processor, model = _load(model_id)
|
| 75 |
|
|
|
|
| 76 |
bf = processor(images=image, return_tensors="pt")
|
| 77 |
+
bf = _to_cuda_batchfeature(bf)
|
| 78 |
+
pixel_values = bf["pixel_values"]
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
|
| 80 |
with torch.amp.autocast("cuda", dtype=torch.float16), torch.inference_mode():
|
| 81 |
out = model(**bf)
|
| 82 |
|
| 83 |
+
# Embedding pooling
|
| 84 |
+
if pooling == "CLS":
|
| 85 |
+
if getattr(out, "pooler_output", None) is not None:
|
| 86 |
+
emb = out.pooler_output[0]
|
| 87 |
+
else:
|
| 88 |
+
emb = out.last_hidden_state[0, 0]
|
| 89 |
else:
|
| 90 |
+
# mean of patch tokens or mean over H W for conv features
|
| 91 |
+
if out.last_hidden_state.ndim == 3:
|
| 92 |
+
num_regs = getattr(model.config, "num_register_tokens", 0)
|
| 93 |
+
patch_tokens = out.last_hidden_state[0, 1 + num_regs :]
|
| 94 |
+
emb = patch_tokens.mean(dim=0)
|
| 95 |
+
else:
|
| 96 |
+
feat = out.last_hidden_state[0] # [C,H,W]
|
| 97 |
+
emb = feat.mean(dim=(1, 2))
|
| 98 |
+
|
|
|
|
| 99 |
emb = emb.float().cpu().numpy()
|
| 100 |
|
| 101 |
# Optional simple heat overlay for ViT
|
| 102 |
overlay = None
|
| 103 |
+
if want_overlay and getattr(out, "last_hidden_state", None) is not None and out.last_hidden_state.ndim == 3:
|
| 104 |
num_regs = getattr(model.config, "num_register_tokens", 0)
|
| 105 |
+
patch_tokens = out.last_hidden_state[0, 1 + num_regs :] # [N_patches, D]
|
| 106 |
num_patches = patch_tokens.shape[0]
|
|
|
|
|
|
|
| 107 |
h = int(num_patches ** 0.5)
|
| 108 |
w = h
|
| 109 |
if h * w != num_patches:
|
| 110 |
patch = getattr(model.config, "patch_size", 16)
|
| 111 |
h = int(pixel_values.shape[-2] // patch)
|
| 112 |
w = int(pixel_values.shape[-1] // patch)
|
|
|
|
| 113 |
mags = patch_tokens.norm(dim=1).reshape(h, w)
|
| 114 |
mags = (mags - mags.min()) / max(1e-8, (mags.max() - mags.min()))
|
| 115 |
m = (mags.cpu().numpy() * 255).astype(np.uint8)
|
|
|
|
| 124 |
}
|
| 125 |
return emb, overlay, meta
|
| 126 |
|
|
|
|
| 127 |
# ---------------------------
|
| 128 |
+
# Utilities
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 129 |
# ---------------------------
|
| 130 |
def _open_images_from_paths(paths: List[str]) -> List[Image.Image]:
|
| 131 |
imgs: List[Image.Image] = []
|
|
|
|
| 140 |
def _to_html_table(S: np.ndarray, names: List[str]) -> str:
|
| 141 |
# simple accessible HTML table render
|
| 142 |
names_safe = [os.path.basename(n) for n in names]
|
| 143 |
+
header = "<tr><th></th>" + "".join(
|
| 144 |
+
f"<th style='padding:6px 8px;text-align:center'>{n}</th>" for n in names_safe
|
| 145 |
+
) + "</tr>"
|
| 146 |
rows = []
|
| 147 |
for i, r in enumerate(S):
|
| 148 |
cells = "".join(f"<td style='padding:6px 8px;text-align:center'>{v:.3f}</td>" for v in r)
|
|
|
|
| 157 |
"""
|
| 158 |
return table
|
| 159 |
|
| 160 |
+
def _normalize_rows(X: np.ndarray) -> np.ndarray:
|
| 161 |
+
n = np.linalg.norm(X, axis=1, keepdims=True)
|
| 162 |
+
return X / np.clip(n, 1e-8, None)
|
| 163 |
|
| 164 |
+
# ---------------------------
|
| 165 |
+
# Single image API ZeroGPU
|
| 166 |
+
# ---------------------------
|
| 167 |
+
@spaces.GPU(duration=_gpu_duration_single)
|
| 168 |
+
def extract_embedding(image: Image.Image, model_name: str, pooling: str, want_overlay: bool):
|
| 169 |
+
if image is None:
|
| 170 |
+
return None, "[]", {"error": "No image"}, None
|
| 171 |
+
if not torch.cuda.is_available():
|
| 172 |
+
raise RuntimeError("CUDA not available. Ensure Space hardware is ZeroGPU.")
|
| 173 |
+
model_id = MODELS[model_name]
|
| 174 |
+
emb, overlay, meta = _extract_core(image, model_id, pooling, want_overlay)
|
| 175 |
+
# Preview + file save for gr.File
|
| 176 |
+
head = ", ".join(f"{x:.4f}" for x in emb[:16])
|
| 177 |
+
preview = f"[{head}{', ...' if emb.size > 16 else ''}]"
|
| 178 |
+
out_path = os.path.join(tempfile.gettempdir(), f"embedding_{uuid4().hex}.npy")
|
| 179 |
+
np.save(out_path, emb.astype(np.float32), allow_pickle=False)
|
| 180 |
+
# Return: gr.Image, gr.Textbox, gr.JSON, gr.File
|
| 181 |
+
return overlay if overlay else image, preview, meta, out_path
|
| 182 |
+
|
| 183 |
+
# ---------------------------
|
| 184 |
+
# Multi image similarity ZeroGPU
|
| 185 |
+
# ---------------------------
|
| 186 |
@spaces.GPU(duration=_gpu_duration_gallery)
|
| 187 |
def batch_similarity(files: List[str], model_name: str, pooling: str):
|
| 188 |
paths = files or []
|
|
|
|
| 190 |
return "<em>Upload at least 2 images</em>", None
|
| 191 |
if not torch.cuda.is_available():
|
| 192 |
raise RuntimeError("CUDA not available. Ensure ZeroGPU is selected.")
|
|
|
|
| 193 |
model_id = MODELS[model_name]
|
| 194 |
imgs = _open_images_from_paths(paths)
|
| 195 |
embs = []
|
| 196 |
for img in imgs:
|
| 197 |
e, _, _ = _extract_core(img, model_id, pooling, want_overlay=False)
|
| 198 |
embs.append(e)
|
|
|
|
| 199 |
if len(embs) < 2:
|
| 200 |
return "<em>Failed to read or embed images</em>", None
|
|
|
|
| 201 |
X = np.vstack(embs).astype(np.float32)
|
| 202 |
+
Xn = _normalize_rows(X)
|
| 203 |
S = Xn @ Xn.T
|
|
|
|
| 204 |
# save CSV and build HTML table
|
| 205 |
csv_path = os.path.join(tempfile.gettempdir(), f"cosine_{uuid4().hex}.csv")
|
| 206 |
np.savetxt(csv_path, S, delimiter=",", fmt="%.6f")
|
| 207 |
html = _to_html_table(S, paths)
|
| 208 |
return html, csv_path
|
| 209 |
|
| 210 |
+
# ---------------------------
|
| 211 |
+
# Image Classification using DINOv3 embeddings
|
| 212 |
+
# Few shot nearest centroid on GPU
|
| 213 |
+
# ---------------------------
|
| 214 |
+
# State format:
|
| 215 |
+
# state = {
|
| 216 |
+
# "model_id": str,
|
| 217 |
+
# "pooling": str,
|
| 218 |
+
# "classes": { "cat": {"embs": np.ndarray[Nc, D], "count": int}, ... }
|
| 219 |
+
# }
|
| 220 |
+
def _init_state() -> Dict:
|
| 221 |
+
return {"model_id": "", "pooling": "", "classes": {}}
|
| 222 |
+
|
| 223 |
+
def _summarize_state(state: Dict) -> Dict:
|
| 224 |
+
return {
|
| 225 |
+
"model_id": state.get("model_id", ""),
|
| 226 |
+
"pooling": state.get("pooling", ""),
|
| 227 |
+
"class_counts": {k: v.get("count", 0) for k, v in state.get("classes", {}).items()},
|
| 228 |
+
"num_classes": len(state.get("classes", {})),
|
| 229 |
+
"total_examples": int(sum(v.get("count", 0) for v in state.get("classes", {}).values())),
|
| 230 |
+
}
|
| 231 |
+
|
| 232 |
+
@spaces.GPU(duration=_gpu_duration_gallery)
|
| 233 |
+
def add_class(class_name: str, files: List[str], model_name: str, pooling: str, state: Dict):
|
| 234 |
+
if not torch.cuda.is_available():
|
| 235 |
+
raise RuntimeError("CUDA not available. Ensure ZeroGPU is selected.")
|
| 236 |
+
if not class_name.strip():
|
| 237 |
+
return {"error": "Class name is empty"}, state
|
| 238 |
+
if not files:
|
| 239 |
+
return {"error": "No images uploaded for this class"}, state
|
| 240 |
+
|
| 241 |
+
model_id = MODELS[model_name]
|
| 242 |
+
# Reset state if model settings changed
|
| 243 |
+
if state.get("model_id") and (state["model_id"] != model_id or state.get("pooling") != pooling):
|
| 244 |
+
state = _init_state()
|
| 245 |
+
state["model_id"] = model_id
|
| 246 |
+
state["pooling"] = pooling
|
| 247 |
+
|
| 248 |
+
imgs = _open_images_from_paths(files)
|
| 249 |
+
if not imgs:
|
| 250 |
+
return {"error": "Could not read uploaded images"}, state
|
| 251 |
+
|
| 252 |
+
embs = []
|
| 253 |
+
for im in imgs:
|
| 254 |
+
e, _, _ = _extract_core(im, model_id, pooling, want_overlay=False)
|
| 255 |
+
embs.append(e.astype(np.float32))
|
| 256 |
+
X = np.vstack(embs)
|
| 257 |
+
if class_name not in state["classes"]:
|
| 258 |
+
state["classes"][class_name] = {"embs": X, "count": X.shape[0]}
|
| 259 |
+
else:
|
| 260 |
+
old = state["classes"][class_name]["embs"]
|
| 261 |
+
new = np.concatenate([old, X], axis=0)
|
| 262 |
+
state["classes"][class_name]["embs"] = new
|
| 263 |
+
state["classes"][class_name]["count"] = new.shape[0]
|
| 264 |
+
|
| 265 |
+
return _summarize_state(state), state
|
| 266 |
+
|
| 267 |
+
@spaces.GPU(duration=_gpu_duration_classify)
|
| 268 |
+
def predict_class(image: Image.Image, model_name: str, pooling: str, state: Dict, top_k: int):
|
| 269 |
+
if image is None:
|
| 270 |
+
return {"error": "Upload a query image"}, {}, None
|
| 271 |
+
if not torch.cuda.is_available():
|
| 272 |
+
raise RuntimeError("CUDA not available. Ensure ZeroGPU is selected.")
|
| 273 |
+
if not state or not state.get("classes"):
|
| 274 |
+
return {"error": "No classes have been added yet"}, {}, None
|
| 275 |
+
|
| 276 |
+
model_id = MODELS[model_name]
|
| 277 |
+
if state.get("model_id") != model_id or state.get("pooling") != pooling:
|
| 278 |
+
return {"error": "Model or pooling changed after building classes. Clear and rebuild."}, {}, None
|
| 279 |
+
|
| 280 |
+
# Compute query embedding
|
| 281 |
+
q, _, _ = _extract_core(image, model_id, pooling, want_overlay=False)
|
| 282 |
+
q = q.astype(np.float32)[None, :]
|
| 283 |
+
qn = _normalize_rows(q) # [1, D]
|
| 284 |
+
|
| 285 |
+
# Build centroids per class
|
| 286 |
+
names = []
|
| 287 |
+
cents = []
|
| 288 |
+
for cname, bundle in state["classes"].items():
|
| 289 |
+
X = bundle["embs"].astype(np.float32)
|
| 290 |
+
Xn = _normalize_rows(X)
|
| 291 |
+
c = Xn.mean(axis=0, keepdims=True) # centroid in cosine space
|
| 292 |
+
c = _normalize_rows(c)
|
| 293 |
+
names.append(cname)
|
| 294 |
+
cents.append(c)
|
| 295 |
+
C = np.vstack(cents) # [K, D]
|
| 296 |
+
|
| 297 |
+
sims = (qn @ C.T).flatten() # cosine similarity
|
| 298 |
+
# Stable softmax over a temperature
|
| 299 |
+
temp = 0.05
|
| 300 |
+
logits = sims / max(temp, 1e-6)
|
| 301 |
+
logits = logits - logits.max()
|
| 302 |
+
probs = np.exp(logits)
|
| 303 |
+
probs = probs / probs.sum()
|
| 304 |
+
|
| 305 |
+
order = np.argsort(-probs)[: max(1, min(top_k, len(names)))]
|
| 306 |
+
result_dict = {names[i]: float(probs[i]) for i in order}
|
| 307 |
+
# Full table for display
|
| 308 |
+
full_table = "<ol>" + "".join(
|
| 309 |
+
f"<li>{names[i]} score {float(probs[i]):.4f}</li>" for i in order
|
| 310 |
+
) + "</ol>"
|
| 311 |
+
|
| 312 |
+
# gr.Label expects a dict of class to score for visualization
|
| 313 |
+
return {"top_k": top_k, "prediction": names[order[0]]}, result_dict, full_table
|
| 314 |
+
|
| 315 |
+
def clear_classes(_state: Dict):
|
| 316 |
+
return _init_state(), _summarize_state(_init_state())
|
| 317 |
|
| 318 |
# ---------------------------
|
| 319 |
# UI
|
| 320 |
# ---------------------------
|
| 321 |
with gr.Blocks() as app:
|
| 322 |
+
gr.Markdown("# DINOv3 - Embeddings, Similarity, Classification")
|
| 323 |
|
| 324 |
with gr.Accordion("Paper and Citation", open=False):
|
| 325 |
gr.Markdown("""
|
|
|
|
| 338 |
url={[https://arxiv.org/abs/2508.10104}](https://arxiv.org/abs/2508.10104}),
|
| 339 |
}
|
| 340 |
``` """)
|
| 341 |
+
|
| 342 |
+
# ------------- Single -------------
|
| 343 |
with gr.Tab("Single"):
|
| 344 |
with gr.Row():
|
| 345 |
with gr.Column():
|
|
|
|
| 353 |
preview = gr.Textbox(label="Embedding head", max_lines=2)
|
| 354 |
meta = gr.JSON(label="Meta")
|
| 355 |
download = gr.File(label="embedding.npy")
|
| 356 |
+
|
| 357 |
run_btn.click(extract_embedding, [img, model_dd, pooling, overlay], [out_img, preview, meta, download])
|
| 358 |
|
| 359 |
+
# Optional examples if you add files under ./examples
|
| 360 |
+
ex_single = []
|
| 361 |
+
for p in sorted(glob.glob("examples/*.*"))[:6]:
|
| 362 |
+
ex_single.append([p, DEFAULT_MODEL, "CLS", False])
|
| 363 |
+
if ex_single:
|
| 364 |
+
gr.Examples(
|
| 365 |
+
label="Examples",
|
| 366 |
+
examples=ex_single,
|
| 367 |
+
inputs=[img, model_dd, pooling, overlay],
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
# ------------- Cosine Sim -------------
|
| 371 |
with gr.Tab("Cosine Sim"):
|
| 372 |
gr.Markdown("Upload multiple images. We compute a cosine similarity matrix on GPU and return a CSV.")
|
|
|
|
| 373 |
files_in = gr.Files(label="Upload images", file_types=["image"], file_count="multiple", type="filepath")
|
| 374 |
gallery_preview = gr.Gallery(label="Preview", columns=4, height=300)
|
| 375 |
model_dd2 = gr.Dropdown(choices=list(MODELS.keys()), value=DEFAULT_MODEL, label="Backbone")
|
| 376 |
pooling2 = gr.Radio(["CLS", "Mean of patch tokens"], value="CLS", label="Pooling")
|
| 377 |
go = gr.Button("Compute cosine on GPU")
|
| 378 |
+
table = gr.HTML(label="Cosine similarity")
|
| 379 |
csv = gr.File(label="cosine_similarity_matrix.csv")
|
| 380 |
+
|
| 381 |
def _preview(paths):
|
| 382 |
if not paths:
|
| 383 |
return []
|
|
|
|
| 388 |
except Exception:
|
| 389 |
pass
|
| 390 |
return imgs
|
| 391 |
+
|
| 392 |
files_in.change(_preview, inputs=files_in, outputs=gallery_preview)
|
| 393 |
go.click(batch_similarity, [files_in, model_dd2, pooling2], [table, csv])
|
| 394 |
|
| 395 |
+
# ------------- Image Classification -------------
|
| 396 |
+
with gr.Tab("Image Classification"):
|
| 397 |
+
st = gr.State(_init_state())
|
| 398 |
|
| 399 |
+
with gr.Row():
|
| 400 |
+
with gr.Column():
|
| 401 |
+
model_dd3 = gr.Dropdown(choices=list(MODELS.keys()), value=DEFAULT_MODEL, label="Backbone")
|
| 402 |
+
pooling3 = gr.Radio(["CLS", "Mean of patch tokens"], value="CLS", label="Pooling")
|
| 403 |
+
gr.Markdown("Build your labeled set by adding a few images per class.")
|
| 404 |
+
class_name = gr.Textbox(label="Class name")
|
| 405 |
+
class_files = gr.Files(label="Upload images for this class", file_types=["image"], type="filepath", file_count="multiple")
|
| 406 |
+
add_btn = gr.Button("Add class on GPU")
|
| 407 |
+
clear_btn = gr.Button("Clear classes")
|
| 408 |
+
state_view = gr.JSON(label="Classifier state")
|
| 409 |
+
with gr.Column():
|
| 410 |
+
query_img = gr.Image(type="pil", label="Query image", height=360)
|
| 411 |
+
topk = gr.Slider(1, 10, value=3, step=1, label="Top K")
|
| 412 |
+
predict_btn = gr.Button("Predict on GPU")
|
| 413 |
+
predicted = gr.Label(num_top_classes=3, label="Prediction")
|
| 414 |
+
scores_html = gr.HTML(label="Scores")
|
| 415 |
+
|
| 416 |
+
add_btn.click(
|
| 417 |
+
add_class,
|
| 418 |
+
[class_name, class_files, model_dd3, pooling3, st],
|
| 419 |
+
[state_view, st],
|
| 420 |
+
)
|
| 421 |
+
clear_btn.click(
|
| 422 |
+
clear_classes,
|
| 423 |
+
[st],
|
| 424 |
+
[st, state_view],
|
| 425 |
+
)
|
| 426 |
+
predict_btn.click(
|
| 427 |
+
predict_class,
|
| 428 |
+
[query_img, model_dd3, pooling3, st, topk],
|
| 429 |
+
[gr.JSON(label="Info"), predicted, scores_html],
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
# Optional sample query examples from ./examples
|
| 433 |
+
ex_cls = []
|
| 434 |
+
for p in sorted(glob.glob("examples/classify_*.*"))[:8]:
|
| 435 |
+
ex_cls.append([p, topk.value if hasattr(topk, "value") else 3])
|
| 436 |
+
if ex_cls:
|
| 437 |
+
gr.Examples(
|
| 438 |
+
label="Query examples",
|
| 439 |
+
examples=ex_cls,
|
| 440 |
+
inputs=[query_img, topk],
|
| 441 |
+
)
|
| 442 |
|
| 443 |
if __name__ == "__main__":
|
| 444 |
app.queue().launch()
|