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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
import os
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
import gradio as gr
|
6 |
+
import numpy as np
|
7 |
+
from PIL import Image, ImageDraw
|
8 |
+
import torchvision.transforms.functional as TF
|
9 |
+
from matplotlib import colormaps
|
10 |
+
from transformers import AutoModel # π‘ Import AutoModel
|
11 |
+
|
12 |
+
# ----------------------------
|
13 |
+
# Configuration
|
14 |
+
# ----------------------------
|
15 |
+
# π‘ Use the full, correct model ID from the Hugging Face Hub
|
16 |
+
MODEL_ID = "facebook/dinov3-vith16plus-pretrain-lvd1689m"
|
17 |
+
PATCH_SIZE = 16
|
18 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
19 |
+
|
20 |
+
# Normalization constants (standard for ImageNet)
|
21 |
+
IMAGENET_MEAN = (0.485, 0.456, 0.406)
|
22 |
+
IMAGENET_STD = (0.229, 0.224, 0.225)
|
23 |
+
|
24 |
+
# ----------------------------
|
25 |
+
# Model Loading (Hugging Face Hub)
|
26 |
+
# ----------------------------
|
27 |
+
def load_model_from_hub():
|
28 |
+
"""Loads the DINOv3 model from the Hugging Face Hub."""
|
29 |
+
print(f"Loading model '{MODEL_ID}' from Hugging Face Hub...")
|
30 |
+
try:
|
31 |
+
# This will use the HF_TOKEN secret if you set it in your Space settings.
|
32 |
+
token = os.environ.get("HF_TOKEN")
|
33 |
+
# trust_remote_code is necessary for DINOv3
|
34 |
+
model = AutoModel.from_pretrained(MODEL_ID, token=token, trust_remote_code=True)
|
35 |
+
model.to(DEVICE).eval()
|
36 |
+
print(f"β
Model loaded successfully on device: {DEVICE}")
|
37 |
+
return model
|
38 |
+
except Exception as e:
|
39 |
+
print(f"β Failed to load model: {e}")
|
40 |
+
# This will display a clear error message in the Gradio interface
|
41 |
+
raise gr.Error(
|
42 |
+
f"Could not load model '{MODEL_ID}'. "
|
43 |
+
"This is a gated model. Please ensure you have accepted the terms on its Hugging Face page "
|
44 |
+
"and set your HF_TOKEN as a secret in your Space settings. "
|
45 |
+
f"Original error: {e}"
|
46 |
+
)
|
47 |
+
|
48 |
+
# Load the model globally when the app starts
|
49 |
+
model = load_model_from_hub()
|
50 |
+
|
51 |
+
# ----------------------------
|
52 |
+
# Helper Functions (resize, viz)
|
53 |
+
# ----------------------------
|
54 |
+
def resize_to_grid(img: Image.Image, long_side: int, patch: int) -> torch.Tensor:
|
55 |
+
"""
|
56 |
+
Resizes so max(h,w)=long_side (keeping aspect), then rounds each side UP to a multiple of 'patch'.
|
57 |
+
Returns CHW float tensor in [0,1].
|
58 |
+
"""
|
59 |
+
w, h = img.size
|
60 |
+
scale = long_side / max(h, w)
|
61 |
+
new_h = max(patch, int(round(h * scale)))
|
62 |
+
new_w = max(patch, int(round(w * scale)))
|
63 |
+
new_h = ((new_h + patch - 1) // patch) * patch
|
64 |
+
new_w = ((new_w + patch - 1) // patch) * patch
|
65 |
+
return TF.to_tensor(TF.resize(img.convert("RGB"), (new_h, new_w)))
|
66 |
+
|
67 |
+
def colorize(sim_map_up: np.ndarray, cmap_name: str = "viridis") -> Image.Image:
|
68 |
+
x = sim_map_up.astype(np.float32)
|
69 |
+
x = (x - x.min()) / (x.max() - x.min() + 1e-6)
|
70 |
+
rgb = (colormaps[cmap_name](x)[..., :3] * 255).astype(np.uint8)
|
71 |
+
return Image.fromarray(rgb)
|
72 |
+
|
73 |
+
def blend(base: Image.Image, heat: Image.Image, alpha: float = 0.55) -> Image.Image:
|
74 |
+
base = base.convert("RGBA")
|
75 |
+
heat = heat.convert("RGBA")
|
76 |
+
a = Image.new("L", heat.size, int(255 * alpha))
|
77 |
+
heat.putalpha(a)
|
78 |
+
out = Image.alpha_composite(base, heat)
|
79 |
+
return out.convert("RGB")
|
80 |
+
|
81 |
+
def draw_crosshair(img: Image.Image, x: int, y: int, radius: int = None) -> Image.Image:
|
82 |
+
r = radius if radius is not None else max(2, PATCH_SIZE // 2)
|
83 |
+
out = img.copy()
|
84 |
+
draw = ImageDraw.Draw(out)
|
85 |
+
draw.line([(x - r, y), (x + r, y)], fill="red", width=3)
|
86 |
+
draw.line([(x, y - r), (x, y + r)], fill="red", width=3)
|
87 |
+
return out
|
88 |
+
|
89 |
+
def draw_boxes(img: Image.Image, boxes, outline="yellow", width=3, labels=True):
|
90 |
+
out = img.copy()
|
91 |
+
draw = ImageDraw.Draw(out)
|
92 |
+
for i, (x0, y0, x1, y1) in enumerate(boxes, start=1):
|
93 |
+
draw.rectangle([x0, y0, x1, y1], outline=outline, width=width)
|
94 |
+
if labels:
|
95 |
+
tx, ty = x0 + 2, y0 + 2
|
96 |
+
draw.text((tx, ty), str(i), fill=outline)
|
97 |
+
return out
|
98 |
+
|
99 |
+
def patch_neighborhood_box(r: int, c: int, Hp: int, Wp: int, rad: int, patch: int = PATCH_SIZE):
|
100 |
+
r0 = max(0, r - rad)
|
101 |
+
r1 = min(Hp - 1, r + rad)
|
102 |
+
c0 = max(0, c - rad)
|
103 |
+
c1 = min(Wp - 1, c + rad)
|
104 |
+
x0 = int(c0 * patch)
|
105 |
+
y0 = int(r0 * patch)
|
106 |
+
x1 = int((c1 + 1) * patch) - 1
|
107 |
+
y1 = int((r1 + 1) * patch) - 1
|
108 |
+
return (x0, y0, x1, y1)
|
109 |
+
|
110 |
+
# ----------------------------
|
111 |
+
# Feature Extraction (using transformers)
|
112 |
+
# ----------------------------
|
113 |
+
@torch.inference_mode()
|
114 |
+
def extract_image_features(image_pil: Image.Image, target_long_side: int):
|
115 |
+
"""
|
116 |
+
Extracts patch features from an image using the loaded Hugging Face model.
|
117 |
+
"""
|
118 |
+
t = resize_to_grid(image_pil, target_long_side, PATCH_SIZE)
|
119 |
+
t_norm = TF.normalize(t, IMAGENET_MEAN, IMAGENET_STD).unsqueeze(0).to(DEVICE)
|
120 |
+
_, _, H, W = t_norm.shape
|
121 |
+
Hp, Wp = H // PATCH_SIZE, W // PATCH_SIZE
|
122 |
+
|
123 |
+
# π‘ Use the standard forward pass of the transformers model
|
124 |
+
outputs = model(t_norm)
|
125 |
+
|
126 |
+
# π‘ The model output includes a [CLS] token AND 4 register tokens.
|
127 |
+
# We must skip all 5 to get only the patch embeddings.
|
128 |
+
n_special_tokens = 5
|
129 |
+
patch_embeddings = outputs.last_hidden_state.squeeze(0)[n_special_tokens:, :]
|
130 |
+
|
131 |
+
# L2-normalize the features to prepare for cosine similarity
|
132 |
+
X = F.normalize(patch_embeddings, p=2, dim=-1)
|
133 |
+
|
134 |
+
img_resized = TF.to_pil_image(t)
|
135 |
+
return {"X": X, "Hp": Hp, "Wp": Wp, "img": img_resized}
|
136 |
+
|
137 |
+
# ----------------------------
|
138 |
+
# Similarity inside the same image (No changes needed here)
|
139 |
+
# ----------------------------
|
140 |
+
def click_to_similarity_in_same_image(
|
141 |
+
state: dict,
|
142 |
+
click_xy: tuple[int, int],
|
143 |
+
exclude_radius_patches: int = 1,
|
144 |
+
topk: int = 10,
|
145 |
+
alpha: float = 0.55,
|
146 |
+
cmap_name: str = "viridis",
|
147 |
+
box_radius_patches: int = 4,
|
148 |
+
):
|
149 |
+
if not state:
|
150 |
+
return None, None, None, None
|
151 |
+
|
152 |
+
X = state["X"]
|
153 |
+
Hp, Wp = state["Hp"], state["Wp"]
|
154 |
+
base_img = state["img"]
|
155 |
+
img_w, img_h = base_img.size
|
156 |
+
|
157 |
+
x_pix, y_pix = click_xy
|
158 |
+
col = int(np.clip(x_pix // PATCH_SIZE, 0, Wp - 1))
|
159 |
+
row = int(np.clip(y_pix // PATCH_SIZE, 0, Hp - 1))
|
160 |
+
idx = row * Wp + col
|
161 |
+
|
162 |
+
q = X[idx]
|
163 |
+
sims = torch.matmul(X, q)
|
164 |
+
sim_map = sims.view(Hp, Wp)
|
165 |
+
|
166 |
+
if exclude_radius_patches > 0:
|
167 |
+
rr, cc = torch.meshgrid(
|
168 |
+
torch.arange(Hp, device=sims.device),
|
169 |
+
torch.arange(Wp, device=sims.device),
|
170 |
+
indexing="ij",
|
171 |
+
)
|
172 |
+
mask = (torch.abs(rr - row) <= exclude_radius_patches) & (torch.abs(cc - col) <= exclude_radius_patches)
|
173 |
+
sim_map = sim_map.masked_fill(mask, float("-inf"))
|
174 |
+
|
175 |
+
sim_up = F.interpolate(
|
176 |
+
sim_map.unsqueeze(0).unsqueeze(0),
|
177 |
+
size=(img_h, img_w),
|
178 |
+
mode="bicubic",
|
179 |
+
align_corners=False,
|
180 |
+
).squeeze().detach().cpu().numpy()
|
181 |
+
|
182 |
+
heatmap_pil = colorize(sim_up, cmap_name)
|
183 |
+
overlay_pil = blend(base_img, heatmap_pil, alpha=alpha)
|
184 |
+
|
185 |
+
overlay_boxes_pil = overlay_pil
|
186 |
+
if topk and topk > 0:
|
187 |
+
flat = sim_map.view(-1)
|
188 |
+
valid = torch.isfinite(flat)
|
189 |
+
if valid.any():
|
190 |
+
vals = flat.clone()
|
191 |
+
vals[~valid] = -1e9
|
192 |
+
k = min(topk, int(valid.sum().item()))
|
193 |
+
_, top_idx = torch.topk(vals, k=k, largest=True, sorted=True)
|
194 |
+
boxes = [
|
195 |
+
patch_neighborhood_box(
|
196 |
+
r, c, Hp, Wp, rad=int(box_radius_patches), patch=PATCH_SIZE
|
197 |
+
)
|
198 |
+
for r, c in [divmod(j.item(), Wp) for j in top_idx]
|
199 |
+
]
|
200 |
+
overlay_boxes_pil = draw_boxes(overlay_pil, boxes, outline="yellow", width=3, labels=True)
|
201 |
+
|
202 |
+
marked_ref = draw_crosshair(base_img, x_pix, y_pix, radius=PATCH_SIZE // 2)
|
203 |
+
return marked_ref, heatmap_pil, overlay_pil, overlay_boxes_pil
|
204 |
+
|
205 |
+
# ----------------------------
|
206 |
+
# Gradio UI (No changes needed here)
|
207 |
+
# ----------------------------
|
208 |
+
with gr.Blocks(theme=gr.themes.Soft(), title="DINOv3 Single-Image Patch Similarity") as demo:
|
209 |
+
gr.Markdown("# π¦ DINOv3 Single-Image Patch Similarity")
|
210 |
+
gr.Markdown("Upload one image, then **click anywhere** to highlight the most similar regions in the *same* image.")
|
211 |
+
|
212 |
+
app_state = gr.State()
|
213 |
+
|
214 |
+
with gr.Row():
|
215 |
+
with gr.Column(scale=1):
|
216 |
+
input_image = gr.Image(
|
217 |
+
label="Image (click anywhere)",
|
218 |
+
type="pil",
|
219 |
+
value="https://images.squarespace-cdn.com/content/v1/607f89e638219e13eee71b1e/1684821560422-SD5V37BAG28BURTLIXUQ/michael-sum-LEpfefQf4rU-unsplash.jpg"
|
220 |
+
)
|
221 |
+
target_long_side = gr.Slider(
|
222 |
+
minimum=224, maximum=1024, value=768, step=16,
|
223 |
+
label="Processing Resolution",
|
224 |
+
info="Higher values = more detail but slower processing",
|
225 |
+
)
|
226 |
+
with gr.Row():
|
227 |
+
alpha = gr.Slider(0.0, 1.0, value=0.55, step=0.05, label="Overlay opacity")
|
228 |
+
cmap = gr.Dropdown(
|
229 |
+
["viridis", "magma", "plasma", "inferno", "turbo", "cividis"],
|
230 |
+
value="viridis", label="Colormap",
|
231 |
+
)
|
232 |
+
with gr.Column(scale=1):
|
233 |
+
exclude_r = gr.Slider(0, 10, value=0, step=1, label="Exclude radius (patches)")
|
234 |
+
topk = gr.Slider(0, 200, value=20, step=1, label="Top-K boxes")
|
235 |
+
box_radius = gr.Slider(0, 10, value=4, step=1, label="Box radius (patches)")
|
236 |
+
|
237 |
+
with gr.Row():
|
238 |
+
marked_image = gr.Image(label="Click marker", interactive=False)
|
239 |
+
heatmap_output = gr.Image(label="Similarity heatmap", interactive=False)
|
240 |
+
with gr.Row():
|
241 |
+
overlay_output = gr.Image(label="Overlay (image β heatmap)", interactive=False)
|
242 |
+
overlay_boxes_output = gr.Image(label="Overlay + top-K similar patch boxes", interactive=False)
|
243 |
+
|
244 |
+
def _on_upload_or_slider_change(img: Image.Image, long_side: int, progress=gr.Progress(track_tqdm=True)):
|
245 |
+
if img is None:
|
246 |
+
return None, None
|
247 |
+
progress(0, desc="Extracting features...")
|
248 |
+
st = extract_image_features(img, int(long_side))
|
249 |
+
progress(1, desc="Done!")
|
250 |
+
return st["img"], st
|
251 |
+
|
252 |
+
def _on_click(st, a: float, m: str, excl: int, k: int, box_rad: int, evt: gr.SelectData):
|
253 |
+
if not st or evt is None:
|
254 |
+
return None, None, None, None
|
255 |
+
return click_to_similarity_in_same_image(
|
256 |
+
st, click_xy=evt.index, exclude_radius_patches=int(excl),
|
257 |
+
topk=int(k), alpha=float(a), cmap_name=m,
|
258 |
+
box_radius_patches=int(box_rad),
|
259 |
+
)
|
260 |
+
|
261 |
+
# Wire events
|
262 |
+
inputs_for_update = [input_image, target_long_side]
|
263 |
+
outputs_for_update = [marked_image, app_state]
|
264 |
+
|
265 |
+
input_image.upload(_on_upload_or_slider_change, inputs=inputs_for_update, outputs=outputs_for_update)
|
266 |
+
target_long_side.change(_on_upload_or_slider_change, inputs=inputs_for_update, outputs=outputs_for_update)
|
267 |
+
demo.load(_on_upload_or_slider_change, inputs=inputs_for_update, outputs=outputs_for_update) # Process default image on load
|
268 |
+
|
269 |
+
marked_image.select(
|
270 |
+
_on_click,
|
271 |
+
inputs=[app_state, alpha, cmap, exclude_r, topk, box_radius],
|
272 |
+
outputs=[marked_image, heatmap_output, overlay_output, overlay_boxes_output],
|
273 |
+
)
|
274 |
+
|
275 |
+
if __name__ == "__main__":
|
276 |
+
demo.launch()
|