Added token to app.py
Browse files
app.py
CHANGED
|
@@ -1,622 +1,624 @@
|
|
| 1 |
-
# app.py
|
| 2 |
-
# Gradio UI for interactive DINOv3 patch similarity (single or dual image)
|
| 3 |
-
# - No AutoImageProcessor, no resize (only pad to multiple of patch size)
|
| 4 |
-
# - Single image: click to show self-similarity; selected cell outlined in RED
|
| 5 |
-
# - Two images: click on one side -> self overlay on source, cross overlay on target; best match on target outlined in YELLOW
|
| 6 |
-
# - Red selection rectangle is hidden on the non-active image
|
| 7 |
-
# - Patch size inferred from model (no override). Patch indices are not annotated.
|
| 8 |
-
# - Dataset selector (LVD-1689M / SAT-493M); model dropdown shows only the short name between "dinov3-" and "-pretrain".
|
| 9 |
-
# - Sample URL dropdowns switch between LVD (COCO/Picsum) and SAT (satellite imagery) and auto-fill / clear uploads.
|
| 10 |
-
|
| 11 |
-
import io
|
| 12 |
-
import math
|
| 13 |
-
import urllib.request
|
| 14 |
-
from functools import lru_cache
|
| 15 |
-
from typing import Optional, Tuple, Dict, List
|
| 16 |
-
|
| 17 |
-
import gradio as gr
|
| 18 |
-
import numpy as np
|
| 19 |
-
from PIL import Image, ImageDraw
|
| 20 |
-
import torch
|
| 21 |
-
from torchvision import transforms
|
| 22 |
-
from transformers import AutoModel
|
| 23 |
-
from matplotlib import colormaps as cm
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
"facebook/dinov3-
|
| 30 |
-
"facebook/dinov3-
|
| 31 |
-
"facebook/dinov3-
|
| 32 |
-
"facebook/dinov3-
|
| 33 |
-
"facebook/dinov3-
|
| 34 |
-
"facebook/dinov3-
|
| 35 |
-
"facebook/dinov3-convnext-
|
| 36 |
-
"facebook/dinov3-convnext-
|
| 37 |
-
"facebook/dinov3-
|
| 38 |
-
"facebook/dinov3-
|
| 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 |
-
("COCO:
|
| 90 |
-
("
|
| 91 |
-
("
|
| 92 |
-
("Picsum:
|
| 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 |
-
return
|
| 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 |
-
ps
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
self.
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
self.
|
| 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 |
-
# Update
|
| 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 |
-
|
| 550 |
-
|
| 551 |
-
|
| 552 |
-
|
| 553 |
-
|
| 554 |
-
|
| 555 |
-
|
| 556 |
-
|
| 557 |
-
|
| 558 |
-
|
| 559 |
-
|
| 560 |
-
|
| 561 |
-
|
| 562 |
-
|
| 563 |
-
|
| 564 |
-
|
| 565 |
-
|
| 566 |
-
|
| 567 |
-
|
| 568 |
-
|
| 569 |
-
|
| 570 |
-
|
| 571 |
-
|
| 572 |
-
|
| 573 |
-
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
-
|
| 578 |
-
|
| 579 |
-
|
| 580 |
-
|
| 581 |
-
|
| 582 |
-
|
| 583 |
-
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
| 587 |
-
|
| 588 |
-
|
| 589 |
-
|
| 590 |
-
|
| 591 |
-
|
| 592 |
-
|
| 593 |
-
|
| 594 |
-
|
| 595 |
-
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
| 601 |
-
|
| 602 |
-
|
| 603 |
-
|
| 604 |
-
|
| 605 |
-
|
| 606 |
-
|
| 607 |
-
|
| 608 |
-
|
| 609 |
-
|
| 610 |
-
|
| 611 |
-
|
| 612 |
-
|
| 613 |
-
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py
|
| 2 |
+
# Gradio UI for interactive DINOv3 patch similarity (single or dual image)
|
| 3 |
+
# - No AutoImageProcessor, no resize (only pad to multiple of patch size)
|
| 4 |
+
# - Single image: click to show self-similarity; selected cell outlined in RED
|
| 5 |
+
# - Two images: click on one side -> self overlay on source, cross overlay on target; best match on target outlined in YELLOW
|
| 6 |
+
# - Red selection rectangle is hidden on the non-active image
|
| 7 |
+
# - Patch size inferred from model (no override). Patch indices are not annotated.
|
| 8 |
+
# - Dataset selector (LVD-1689M / SAT-493M); model dropdown shows only the short name between "dinov3-" and "-pretrain".
|
| 9 |
+
# - Sample URL dropdowns switch between LVD (COCO/Picsum) and SAT (satellite imagery) and auto-fill / clear uploads.
|
| 10 |
+
|
| 11 |
+
import io
|
| 12 |
+
import math
|
| 13 |
+
import urllib.request
|
| 14 |
+
from functools import lru_cache
|
| 15 |
+
from typing import Optional, Tuple, Dict, List
|
| 16 |
+
|
| 17 |
+
import gradio as gr
|
| 18 |
+
import numpy as np
|
| 19 |
+
from PIL import Image, ImageDraw
|
| 20 |
+
import torch
|
| 21 |
+
from torchvision import transforms
|
| 22 |
+
from transformers import AutoModel
|
| 23 |
+
from matplotlib import colormaps as cm
|
| 24 |
+
|
| 25 |
+
token = os.environ.get("HF_TOKEN")
|
| 26 |
+
|
| 27 |
+
# ---------- Provided model IDs (ground truth list) ----------
|
| 28 |
+
MODEL_ID_LIST = [
|
| 29 |
+
"facebook/dinov3-vits16-pretrain-lvd1689m",
|
| 30 |
+
"facebook/dinov3-vits16plus-pretrain-lvd1689m",
|
| 31 |
+
"facebook/dinov3-vitb16-pretrain-lvd1689m",
|
| 32 |
+
"facebook/dinov3-vitl16-pretrain-lvd1689m",
|
| 33 |
+
"facebook/dinov3-vith16plus-pretrain-lvd1689m",
|
| 34 |
+
"facebook/dinov3-vit7b16-pretrain-lvd1689m",
|
| 35 |
+
"facebook/dinov3-convnext-tiny-pretrain-lvd1689m",
|
| 36 |
+
"facebook/dinov3-convnext-small-pretrain-lvd1689m",
|
| 37 |
+
"facebook/dinov3-convnext-base-pretrain-lvd1689m",
|
| 38 |
+
"facebook/dinov3-convnext-large-pretrain-lvd1689m",
|
| 39 |
+
"facebook/dinov3-vitl16-pretrain-sat493m",
|
| 40 |
+
"facebook/dinov3-vit7b16-pretrain-sat493m",
|
| 41 |
+
]
|
| 42 |
+
|
| 43 |
+
DATASET_LABELS = {
|
| 44 |
+
"LVD-1689M": "lvd1689m",
|
| 45 |
+
"SAT-493M": "sat493m",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
def build_model_maps(model_ids: List[str]):
|
| 49 |
+
"""
|
| 50 |
+
Returns:
|
| 51 |
+
valid_map[(dataset_key, short_name)] -> full_model_id
|
| 52 |
+
options_by_dataset[dataset_key] -> [short_name,...] (display order preserved)
|
| 53 |
+
"""
|
| 54 |
+
valid_map: Dict[Tuple[str, str], str] = {}
|
| 55 |
+
options_by_dataset: Dict[str, List[str]] = {"lvd1689m": [], "sat493m": []}
|
| 56 |
+
|
| 57 |
+
for mid in model_ids:
|
| 58 |
+
# Expect pattern: "facebook/dinov3-<short>-pretrain-<dataset>"
|
| 59 |
+
try:
|
| 60 |
+
prefix = "facebook/dinov3-"
|
| 61 |
+
start = mid.index(prefix) + len(prefix)
|
| 62 |
+
pre_idx = mid.index("-pretrain", start)
|
| 63 |
+
short = mid[start:pre_idx]
|
| 64 |
+
dataset = mid.split("-pretrain-")[-1].strip()
|
| 65 |
+
except Exception:
|
| 66 |
+
# Skip anything that doesn't match the expected pattern
|
| 67 |
+
continue
|
| 68 |
+
|
| 69 |
+
key = (dataset, short)
|
| 70 |
+
valid_map[key] = mid
|
| 71 |
+
if dataset in options_by_dataset and short not in options_by_dataset[dataset]:
|
| 72 |
+
options_by_dataset[dataset].append(short)
|
| 73 |
+
|
| 74 |
+
return valid_map, options_by_dataset
|
| 75 |
+
|
| 76 |
+
VALID_MODEL_MAP, MODEL_OPTIONS_BY_DATASET = build_model_maps(MODEL_ID_LIST)
|
| 77 |
+
|
| 78 |
+
# ---------- Defaults / knobs ----------
|
| 79 |
+
DEFAULT_URL = "http://images.cocodataset.org/val2017/000000039769.jpg"
|
| 80 |
+
DEFAULT_DATASET_LABEL = "LVD-1689M" # initial radio
|
| 81 |
+
DEFAULT_OVERLAY_ALPHA = 0.55
|
| 82 |
+
DEFAULT_SHOW_GRID = True
|
| 83 |
+
|
| 84 |
+
# ---------- Sample image URLs (dependent on dataset) ----------
|
| 85 |
+
SAMPLE_URL_CHOICES: Dict[str, List[Tuple[str, str]]] = {
|
| 86 |
+
# LVD: current ones
|
| 87 |
+
"lvd1689m": [
|
| 88 |
+
("– choose a sample –", ""),
|
| 89 |
+
("COCO: 2 Cats on sofa (039769)", "http://images.cocodataset.org/val2017/000000039769.jpg"),
|
| 90 |
+
("COCO: Person skiing (000785)", "http://images.cocodataset.org/val2017/000000000785.jpg"),
|
| 91 |
+
("COCO: People running (000872)", "http://images.cocodataset.org/val2017/000000000872.jpg"),
|
| 92 |
+
("Picsum: Mountain (ID=1000)", "https://picsum.photos/id/1000/800/600"),
|
| 93 |
+
("Picsum: Kayak (ID=1011)", "https://picsum.photos/id/1011/800/600"),
|
| 94 |
+
("Picsum: Man and dog (ID=1012)", "https://picsum.photos/id/1012/800/600"),
|
| 95 |
+
],
|
| 96 |
+
# SAT: satellite imagery examples
|
| 97 |
+
"sat493m": [
|
| 98 |
+
("– choose a satellite sample –", ""),
|
| 99 |
+
("Blue Marble (NASA)", "https://upload.wikimedia.org/wikipedia/commons/9/9d/The_Blue_Marble_%28remastered%29.jpg"),
|
| 100 |
+
("GOES-16 Hurricane Florence (2018)", "https://upload.wikimedia.org/wikipedia/commons/5/5e/Hurricane_Florence_GOES-16_2018-09-12_1510Z.jpg"),
|
| 101 |
+
("NASA Earth Observatory: Philippines", "https://eoimages.gsfc.nasa.gov/images/imagerecords/151000/151639/philippines_tmo_2020118_lrg.jpg"),
|
| 102 |
+
],
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
def _sample_labels_for(dataset_label: str):
|
| 106 |
+
key = DATASET_LABELS.get(dataset_label, "lvd1689m")
|
| 107 |
+
return [label for label, _ in SAMPLE_URL_CHOICES.get(key, [])]
|
| 108 |
+
|
| 109 |
+
def _apply_sample(dataset_label: str, sample_label: str):
|
| 110 |
+
"""Fill textbox with chosen sample URL and clear any uploaded image."""
|
| 111 |
+
key = DATASET_LABELS.get(dataset_label, "lvd1689m")
|
| 112 |
+
sample_map = dict(SAMPLE_URL_CHOICES.get(key, []))
|
| 113 |
+
url = sample_map.get(sample_label, "")
|
| 114 |
+
return gr.update(value=url), None # (textbox update, clear upload)
|
| 115 |
+
|
| 116 |
+
# ---------- Utility ----------
|
| 117 |
+
def load_image_from_any(src: Optional[Image.Image], url: Optional[str]) -> Optional[Image.Image]:
|
| 118 |
+
# Prefer URL if present
|
| 119 |
+
if url and str(url).strip().lower().startswith(("http://", "https://")):
|
| 120 |
+
with urllib.request.urlopen(url) as resp:
|
| 121 |
+
data = resp.read()
|
| 122 |
+
return Image.open(io.BytesIO(data)).convert("RGB")
|
| 123 |
+
if isinstance(src, Image.Image):
|
| 124 |
+
return src.convert("RGB")
|
| 125 |
+
return None
|
| 126 |
+
|
| 127 |
+
def pad_to_multiple(pil_img: Image.Image, multiple: int = 16) -> Tuple[Image.Image, Tuple[int, int, int, int]]:
|
| 128 |
+
W, H = pil_img.size
|
| 129 |
+
H_pad = int(math.ceil(H / multiple) * multiple)
|
| 130 |
+
W_pad = int(math.ceil(W / multiple) * multiple)
|
| 131 |
+
if (H_pad, W_pad) == (H, W):
|
| 132 |
+
return pil_img, (0, 0, 0, 0)
|
| 133 |
+
canvas = Image.new("RGB", (W_pad, H_pad), (0, 0, 0))
|
| 134 |
+
canvas.paste(pil_img, (0, 0))
|
| 135 |
+
return canvas, (0, 0, W_pad - W, H_pad - H)
|
| 136 |
+
|
| 137 |
+
def preprocess_no_resize(pil_img: Image.Image, multiple: int = 16):
|
| 138 |
+
img_padded, pad_box = pad_to_multiple(pil_img, multiple=multiple)
|
| 139 |
+
transform = transforms.Compose([
|
| 140 |
+
transforms.ToTensor(),
|
| 141 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406],
|
| 142 |
+
std =[0.229, 0.224, 0.225]),
|
| 143 |
+
])
|
| 144 |
+
pixel_tensor = transform(img_padded).unsqueeze(0) # (1,3,H,W)
|
| 145 |
+
disp_np = np.array(img_padded, dtype=np.uint8)
|
| 146 |
+
return {"pixel_values": pixel_tensor}, disp_np, pad_box
|
| 147 |
+
|
| 148 |
+
def upsample_nearest(arr: np.ndarray, H: int, W: int, ps: int) -> np.ndarray:
|
| 149 |
+
if arr.ndim == 2:
|
| 150 |
+
return arr.repeat(ps, 0).repeat(ps, 1)
|
| 151 |
+
elif arr.ndim == 3:
|
| 152 |
+
rows, cols, ch = arr.shape
|
| 153 |
+
arr2 = arr.repeat(ps, 0).repeat(ps, 1)
|
| 154 |
+
return arr2.reshape(rows * ps, cols * ps, ch)
|
| 155 |
+
raise ValueError("upsample_nearest expects (rows,cols) or (rows,cols,channels)")
|
| 156 |
+
|
| 157 |
+
def blend_overlay(base_uint8: np.ndarray, overlay_rgb_float: np.ndarray, alpha: float) -> np.ndarray:
|
| 158 |
+
base = base_uint8.astype(np.float32)
|
| 159 |
+
over = (overlay_rgb_float * 255.0).astype(np.float32)
|
| 160 |
+
out = (1.0 - alpha) * base + alpha * over
|
| 161 |
+
return np.clip(out, 0, 255).astype(np.uint8)
|
| 162 |
+
|
| 163 |
+
def draw_grid(img: Image.Image, rows: int, cols: int, ps: int):
|
| 164 |
+
d = ImageDraw.Draw(img)
|
| 165 |
+
W, H = img.size
|
| 166 |
+
for r in range(1, rows):
|
| 167 |
+
y = r * ps
|
| 168 |
+
d.line([(0, y), (W, y)], fill=(255, 255, 255), width=1)
|
| 169 |
+
for c in range(1, cols):
|
| 170 |
+
x = c * ps
|
| 171 |
+
d.line([(x, 0), (x, H)], fill=(255, 255, 255), width=1)
|
| 172 |
+
|
| 173 |
+
def rc_to_idx(r: int, c: int, cols: int) -> int:
|
| 174 |
+
return int(r) * cols + int(c)
|
| 175 |
+
|
| 176 |
+
def idx_to_rc(i: int, cols: int) -> Tuple[int, int]:
|
| 177 |
+
return int(i) // cols, int(i) % cols
|
| 178 |
+
|
| 179 |
+
# ---------- Model cache ----------
|
| 180 |
+
@lru_cache(maxsize=3)
|
| 181 |
+
def load_model_cached(full_model_id: str, device_str: str):
|
| 182 |
+
device = torch.device(device_str)
|
| 183 |
+
model = AutoModel.from_pretrained(full_model_id).to(device)
|
| 184 |
+
model.eval()
|
| 185 |
+
return model
|
| 186 |
+
|
| 187 |
+
def infer_patch_size(model, default: int = 16) -> int:
|
| 188 |
+
if hasattr(model, "config") and hasattr(model.config, "patch_size"):
|
| 189 |
+
ps = model.config.patch_size
|
| 190 |
+
if isinstance(ps, (tuple, list)): return int(ps[0])
|
| 191 |
+
return int(ps)
|
| 192 |
+
if hasattr(model, "patch_size"):
|
| 193 |
+
ps = model.patch_size
|
| 194 |
+
if isinstance(ps, (tuple, list)): return int(ps[0])
|
| 195 |
+
return int(ps)
|
| 196 |
+
return default
|
| 197 |
+
|
| 198 |
+
# ---------- Per-image state ----------
|
| 199 |
+
class PatchImageState:
|
| 200 |
+
def __init__(self, pil_img: Image.Image, model, device_str: str, ps: int):
|
| 201 |
+
self.pil = pil_img
|
| 202 |
+
self.ps = ps
|
| 203 |
+
inputs, disp_np, _ = preprocess_no_resize(pil_img, multiple=ps)
|
| 204 |
+
self.disp = disp_np
|
| 205 |
+
pv = inputs["pixel_values"].to(device_str) # (1,3,H,W)
|
| 206 |
+
_, _, H, W = pv.shape
|
| 207 |
+
self.H, self.W = int(H), int(W)
|
| 208 |
+
self.rows, self.cols = self.H // ps, self.W // ps
|
| 209 |
+
|
| 210 |
+
with torch.no_grad():
|
| 211 |
+
out = model(pixel_values=pv)
|
| 212 |
+
hs = out.last_hidden_state.squeeze(0).detach().cpu().numpy() # (T,D)
|
| 213 |
+
|
| 214 |
+
T, D = hs.shape
|
| 215 |
+
n_patches = self.rows * self.cols
|
| 216 |
+
n_special = T - n_patches # class + maybe registers
|
| 217 |
+
if n_special < 1:
|
| 218 |
+
raise RuntimeError(
|
| 219 |
+
f"Token mismatch: T={T}, rows*cols={n_patches}, HxW={self.H}x{self.W}, ps={ps}"
|
| 220 |
+
)
|
| 221 |
+
self.D = D
|
| 222 |
+
patches = hs[n_special:, :].reshape(self.rows, self.cols, D)
|
| 223 |
+
self.X = patches.reshape(-1, D)
|
| 224 |
+
self.Xn = self.X / (np.linalg.norm(self.X, axis=1, keepdims=True) + 1e-8)
|
| 225 |
+
|
| 226 |
+
# ---------- Rendering / compute ----------
|
| 227 |
+
def render_with_cosmap(
|
| 228 |
+
st: PatchImageState,
|
| 229 |
+
cos_map: Optional[np.ndarray],
|
| 230 |
+
overlay_alpha: float,
|
| 231 |
+
show_grid_flag: bool,
|
| 232 |
+
select_idx: Optional[int] = None,
|
| 233 |
+
best_idx: Optional[int] = None,
|
| 234 |
+
) -> Image.Image:
|
| 235 |
+
H, W, ps = st.H, st.W, st.ps
|
| 236 |
+
rows, cols = st.rows, st.cols
|
| 237 |
+
|
| 238 |
+
if cos_map is None:
|
| 239 |
+
disp = np.full((rows, cols), 0.5, dtype=np.float32)
|
| 240 |
+
else:
|
| 241 |
+
vmin, vmax = float(cos_map.min()), float(cos_map.max())
|
| 242 |
+
rng = vmax - vmin if vmax > vmin else 1e-8
|
| 243 |
+
disp = (cos_map - vmin) / rng
|
| 244 |
+
|
| 245 |
+
cmap = cm.get_cmap("magma")
|
| 246 |
+
rgba = cmap(disp)
|
| 247 |
+
rgb = rgba[..., :3]
|
| 248 |
+
|
| 249 |
+
if select_idx is not None:
|
| 250 |
+
rs, cs = idx_to_rc(select_idx, cols)
|
| 251 |
+
rgb[rs, cs, :] = np.array([1.0, 0.0, 0.0], dtype=np.float32)
|
| 252 |
+
|
| 253 |
+
over_rgb_up = upsample_nearest(rgb, H, W, ps)
|
| 254 |
+
blended = blend_overlay(st.disp, over_rgb_up, float(overlay_alpha))
|
| 255 |
+
pil = Image.fromarray(blended)
|
| 256 |
+
|
| 257 |
+
draw = ImageDraw.Draw(pil)
|
| 258 |
+
if show_grid_flag:
|
| 259 |
+
draw_grid(pil, rows, cols, ps)
|
| 260 |
+
|
| 261 |
+
if select_idx is not None:
|
| 262 |
+
r, c = idx_to_rc(select_idx, cols)
|
| 263 |
+
x0, y0 = c * ps, r * ps
|
| 264 |
+
x1, y1 = x0 + ps - 1, y0 + ps - 1
|
| 265 |
+
draw.rectangle([(x0, y0), (x1, y1)], outline=(255, 0, 0), width=2)
|
| 266 |
+
|
| 267 |
+
if best_idx is not None:
|
| 268 |
+
r, c = idx_to_rc(best_idx, cols)
|
| 269 |
+
x0, y0 = c * ps, r * ps
|
| 270 |
+
x1, y1 = x0 + ps - 1, y0 + ps - 1
|
| 271 |
+
draw.rectangle([(x0, y0), (x1, y1)], outline=(255, 255, 0), width=2)
|
| 272 |
+
|
| 273 |
+
return pil
|
| 274 |
+
|
| 275 |
+
def compute_self_and_cross(
|
| 276 |
+
src: PatchImageState,
|
| 277 |
+
tgt: Optional[PatchImageState],
|
| 278 |
+
q_idx: int,
|
| 279 |
+
):
|
| 280 |
+
q = src.X[q_idx]
|
| 281 |
+
qn = q / (np.linalg.norm(q) + 1e-8)
|
| 282 |
+
|
| 283 |
+
cos_self = src.Xn @ qn
|
| 284 |
+
cos_map_self = cos_self.reshape(src.rows, src.cols)
|
| 285 |
+
self_stats = (float(cos_map_self.min()), float(cos_map_self.max()))
|
| 286 |
+
|
| 287 |
+
cross_result = None
|
| 288 |
+
cos_map_cross = None
|
| 289 |
+
if tgt is not None:
|
| 290 |
+
cos_cross = tgt.Xn @ qn
|
| 291 |
+
cos_map_cross = cos_cross.reshape(tgt.rows, tgt.cols)
|
| 292 |
+
cross_min, cross_max = float(cos_map_cross.min()), float(cos_map_cross.max())
|
| 293 |
+
best_idx = int(np.argmax(cos_cross))
|
| 294 |
+
cross_result = (cross_min, cross_max, best_idx)
|
| 295 |
+
|
| 296 |
+
return cos_map_self, cos_map_cross, self_stats, cross_result
|
| 297 |
+
|
| 298 |
+
# ---------- Gradio helpers for model & samples ----------
|
| 299 |
+
def dataset_label_to_key(label: str) -> str:
|
| 300 |
+
return DATASET_LABELS.get(label, "lvd1689m")
|
| 301 |
+
|
| 302 |
+
def update_model_dropdown(dataset_label: str):
|
| 303 |
+
key = dataset_label_to_key(dataset_label)
|
| 304 |
+
opts = MODEL_OPTIONS_BY_DATASET.get(key, [])
|
| 305 |
+
default_val = opts[0] if opts else None
|
| 306 |
+
return gr.update(choices=opts, value=default_val)
|
| 307 |
+
|
| 308 |
+
def update_model_and_samples(dataset_label: str):
|
| 309 |
+
# Update model dropdown
|
| 310 |
+
model_update = update_model_dropdown(dataset_label)
|
| 311 |
+
# Update both sample dropdowns to dataset-specific options
|
| 312 |
+
labels = _sample_labels_for(dataset_label)
|
| 313 |
+
sample_update = gr.update(choices=labels, value=(labels[0] if labels else None))
|
| 314 |
+
return model_update, sample_update, sample_update
|
| 315 |
+
|
| 316 |
+
def resolve_full_model_id(dataset_label: str, short_name: str) -> Optional[str]:
|
| 317 |
+
key = (dataset_label_to_key(dataset_label), short_name)
|
| 318 |
+
return VALID_MODEL_MAP.get(key)
|
| 319 |
+
|
| 320 |
+
# ---------- Gradio callbacks ----------
|
| 321 |
+
def init_states(
|
| 322 |
+
left_img_in: Optional[Image.Image],
|
| 323 |
+
left_url: str,
|
| 324 |
+
right_img_in: Optional[Image.Image],
|
| 325 |
+
right_url: str,
|
| 326 |
+
dataset_label: str,
|
| 327 |
+
short_model: str,
|
| 328 |
+
show_grid_flag: bool,
|
| 329 |
+
overlay_alpha: float,
|
| 330 |
+
):
|
| 331 |
+
# Resolve images
|
| 332 |
+
left_img = load_image_from_any(left_img_in, left_url)
|
| 333 |
+
right_img = load_image_from_any(right_img_in, right_url)
|
| 334 |
+
if left_img is None and right_img is None:
|
| 335 |
+
left_img = load_image_from_any(None, DEFAULT_URL)
|
| 336 |
+
|
| 337 |
+
# Resolve model
|
| 338 |
+
full_model_id = resolve_full_model_id(dataset_label, short_model)
|
| 339 |
+
if not full_model_id:
|
| 340 |
+
return (gr.update(), gr.update(), None, None, 0, -1, -1, 16,
|
| 341 |
+
f"❌ Model not available: {dataset_label} / {short_model}")
|
| 342 |
+
|
| 343 |
+
device_str = "cuda" if torch.cuda.is_available() else "cpu"
|
| 344 |
+
model = load_model_cached(full_model_id, device_str)
|
| 345 |
+
ps = infer_patch_size(model, 16)
|
| 346 |
+
|
| 347 |
+
left_state = PatchImageState(left_img, model, device_str, ps) if left_img is not None else None
|
| 348 |
+
right_state = PatchImageState(right_img, model, device_str, ps) if right_img is not None else None
|
| 349 |
+
|
| 350 |
+
active_side = 0 if left_state is not None else 1
|
| 351 |
+
|
| 352 |
+
status = f"✔ Loaded: {full_model_id} | ps={ps}"
|
| 353 |
+
out_left, out_right = None, None
|
| 354 |
+
|
| 355 |
+
if left_state is not None and right_state is not None:
|
| 356 |
+
q_idx = (left_state.rows // 2) * left_state.cols + (left_state.cols // 2)
|
| 357 |
+
cos_self, cos_cross, (smin, smax), cross_info = compute_self_and_cross(left_state, right_state, q_idx)
|
| 358 |
+
best_idx = cross_info[2] if cross_info else None
|
| 359 |
+
out_left = render_with_cosmap(left_state, cos_self, overlay_alpha, show_grid_flag,
|
| 360 |
+
select_idx=q_idx, best_idx=None)
|
| 361 |
+
out_right = render_with_cosmap(right_state, cos_cross, overlay_alpha, show_grid_flag,
|
| 362 |
+
select_idx=None, best_idx=best_idx)
|
| 363 |
+
status += (f" | LEFT {left_state.rows}x{left_state.cols} self∈[{smin:.3f},{smax:.3f}] "
|
| 364 |
+
f"| RIGHT cross best={best_idx}")
|
| 365 |
+
left_idx, right_idx = q_idx, (right_state.rows // 2) * right_state.cols + (right_state.cols // 2)
|
| 366 |
+
elif left_state is not None:
|
| 367 |
+
q_idx = (left_state.rows // 2) * left_state.cols + (left_state.cols // 2)
|
| 368 |
+
cos_self, _, (smin, smax), _ = compute_self_and_cross(left_state, None, q_idx)
|
| 369 |
+
out_left = render_with_cosmap(left_state, cos_self, overlay_alpha, show_grid_flag,
|
| 370 |
+
select_idx=q_idx, best_idx=None)
|
| 371 |
+
status += f" | Single LEFT {left_state.rows}x{left_state.cols} self∈[{smin:.3f},{smax:.3f}]"
|
| 372 |
+
left_idx, right_idx = q_idx, -1
|
| 373 |
+
else:
|
| 374 |
+
q_idx = (right_state.rows // 2) * right_state.cols + (right_state.cols // 2)
|
| 375 |
+
cos_self, _, (smin, smax), _ = compute_self_and_cross(right_state, None, q_idx)
|
| 376 |
+
out_right = render_with_cosmap(right_state, cos_self, overlay_alpha, show_grid_flag,
|
| 377 |
+
select_idx=q_idx, best_idx=None)
|
| 378 |
+
status += f" | Single RIGHT {right_state.rows}x{right_state.cols} self∈[{smin:.3f},{smax:.3f}]"
|
| 379 |
+
left_idx, right_idx = -1, q_idx
|
| 380 |
+
|
| 381 |
+
return (
|
| 382 |
+
out_left, out_right,
|
| 383 |
+
left_state, right_state,
|
| 384 |
+
active_side,
|
| 385 |
+
left_idx, right_idx,
|
| 386 |
+
ps,
|
| 387 |
+
status
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
def _coords_to_idx(x: int, y: int, st: PatchImageState) -> int:
|
| 391 |
+
r = int(np.clip(y // st.ps, 0, st.rows - 1))
|
| 392 |
+
c = int(np.clip(x // st.ps, 0, st.cols - 1))
|
| 393 |
+
return rc_to_idx(r, c, st.cols)
|
| 394 |
+
|
| 395 |
+
def on_select_left(
|
| 396 |
+
evt: gr.SelectData,
|
| 397 |
+
left_state: Optional[PatchImageState],
|
| 398 |
+
right_state: Optional[PatchImageState],
|
| 399 |
+
show_grid_flag: bool,
|
| 400 |
+
overlay_alpha: float,
|
| 401 |
+
ps: int,
|
| 402 |
+
):
|
| 403 |
+
if left_state is None:
|
| 404 |
+
return gr.update(), gr.update(), 0, -1, -1, "Upload/Load a LEFT image first."
|
| 405 |
+
|
| 406 |
+
x, y = evt.index
|
| 407 |
+
q_idx = _coords_to_idx(x, y, left_state)
|
| 408 |
+
|
| 409 |
+
if right_state is not None:
|
| 410 |
+
cos_self, cos_cross, (smin, smax), cross_info = compute_self_and_cross(left_state, right_state, q_idx)
|
| 411 |
+
best_idx = cross_info[2]
|
| 412 |
+
out_left = render_with_cosmap(left_state, cos_self, overlay_alpha, show_grid_flag,
|
| 413 |
+
select_idx=q_idx, best_idx=None)
|
| 414 |
+
out_right = render_with_cosmap(right_state, cos_cross, overlay_alpha, show_grid_flag,
|
| 415 |
+
select_idx=None, best_idx=best_idx)
|
| 416 |
+
status = (f"LEFT {left_state.rows}x{left_state.cols} self∈[{smin:.3f},{smax:.3f}] | "
|
| 417 |
+
f"RIGHT cross best idx={best_idx}")
|
| 418 |
+
return out_left, out_right, 0, q_idx, -1, status
|
| 419 |
+
else:
|
| 420 |
+
cos_self, _, (smin, smax), _ = compute_self_and_cross(left_state, None, q_idx)
|
| 421 |
+
out_left = render_with_cosmap(left_state, cos_self, overlay_alpha, show_grid_flag,
|
| 422 |
+
select_idx=q_idx, best_idx=None)
|
| 423 |
+
status = f"Single LEFT • idx={q_idx} • self∈[{smin:.3f},{smax:.3f}]"
|
| 424 |
+
return out_left, gr.update(), 0, q_idx, -1, status
|
| 425 |
+
|
| 426 |
+
def on_select_right(
|
| 427 |
+
evt: gr.SelectData,
|
| 428 |
+
left_state: Optional[PatchImageState],
|
| 429 |
+
right_state: Optional[PatchImageState],
|
| 430 |
+
show_grid_flag: bool,
|
| 431 |
+
overlay_alpha: float,
|
| 432 |
+
ps: int,
|
| 433 |
+
):
|
| 434 |
+
if right_state is None:
|
| 435 |
+
return gr.update(), gr.update(), 1, -1, -1, "Upload/Load a RIGHT image first."
|
| 436 |
+
|
| 437 |
+
x, y = evt.index
|
| 438 |
+
q_idx = _coords_to_idx(x, y, right_state)
|
| 439 |
+
|
| 440 |
+
if left_state is not None:
|
| 441 |
+
cos_self, cos_cross, (smin, smax), cross_info = compute_self_and_cross(right_state, left_state, q_idx)
|
| 442 |
+
best_idx = cross_info[2]
|
| 443 |
+
out_right = render_with_cosmap(right_state, cos_self, overlay_alpha, show_grid_flag,
|
| 444 |
+
select_idx=q_idx, best_idx=None)
|
| 445 |
+
out_left = render_with_cosmap(left_state, cos_cross, overlay_alpha, show_grid_flag,
|
| 446 |
+
select_idx=None, best_idx=best_idx)
|
| 447 |
+
status = (f"RIGHT {right_state.rows}x{right_state.cols} self∈[{smin:.3f},{smax:.3f}] | "
|
| 448 |
+
f"LEFT cross best idx={best_idx}")
|
| 449 |
+
return out_left, out_right, 1, -1, q_idx, status
|
| 450 |
+
else:
|
| 451 |
+
cos_self, _, (smin, smax), _ = compute_self_and_cross(right_state, None, q_idx)
|
| 452 |
+
out_right = render_with_cosmap(right_state, cos_self, overlay_alpha, show_grid_flag,
|
| 453 |
+
select_idx=q_idx, best_idx=None)
|
| 454 |
+
status = f"Single RIGHT • idx={q_idx} • self∈[{smin:.3f},{smax:.3f}]"
|
| 455 |
+
return gr.update(), out_right, 1, -1, q_idx, status
|
| 456 |
+
|
| 457 |
+
def rebuild_with_settings(
|
| 458 |
+
left_state: Optional[PatchImageState],
|
| 459 |
+
right_state: Optional[PatchImageState],
|
| 460 |
+
active_side: int,
|
| 461 |
+
left_idx: int,
|
| 462 |
+
right_idx: int,
|
| 463 |
+
show_grid_flag: bool,
|
| 464 |
+
overlay_alpha: float,
|
| 465 |
+
ps: int,
|
| 466 |
+
):
|
| 467 |
+
if left_state is None and right_state is None:
|
| 468 |
+
return gr.update(), gr.update(), "Load an image first."
|
| 469 |
+
|
| 470 |
+
if left_state is not None and right_state is not None:
|
| 471 |
+
if active_side == 0:
|
| 472 |
+
q_idx = left_idx if left_idx >= 0 else (left_state.rows//2)*left_state.cols + (left_state.cols//2)
|
| 473 |
+
cos_self, cos_cross, _, cross_info = compute_self_and_cross(left_state, right_state, q_idx)
|
| 474 |
+
best_idx = cross_info[2]
|
| 475 |
+
out_left = render_with_cosmap(left_state, cos_self, overlay_alpha, show_grid_flag,
|
| 476 |
+
select_idx=q_idx, best_idx=None)
|
| 477 |
+
out_right = render_with_cosmap(right_state, cos_cross, overlay_alpha, show_grid_flag,
|
| 478 |
+
select_idx=None, best_idx=best_idx)
|
| 479 |
+
else:
|
| 480 |
+
q_idx = right_idx if right_idx >= 0 else (right_state.rows//2)*right_state.cols + (right_state.cols//2)
|
| 481 |
+
cos_self, cos_cross, _, cross_info = compute_self_and_cross(right_state, left_state, q_idx)
|
| 482 |
+
best_idx = cross_info[2]
|
| 483 |
+
out_right = render_with_cosmap(right_state, cos_self, overlay_alpha, show_grid_flag,
|
| 484 |
+
select_idx=q_idx, best_idx=None)
|
| 485 |
+
out_left = render_with_cosmap(left_state, cos_cross, overlay_alpha, show_grid_flag,
|
| 486 |
+
select_idx=None, best_idx=best_idx)
|
| 487 |
+
return out_left, out_right, "Updated overlays."
|
| 488 |
+
elif left_state is not None:
|
| 489 |
+
q_idx = left_idx if left_idx >= 0 else (left_state.rows//2)*left_state.cols + (left_state.cols//2)
|
| 490 |
+
cos_self, _, _, _ = compute_self_and_cross(left_state, None, q_idx)
|
| 491 |
+
out_left = render_with_cosmap(left_state, cos_self, overlay_alpha, show_grid_flag,
|
| 492 |
+
select_idx=q_idx, best_idx=None)
|
| 493 |
+
return out_left, gr.update(), "Updated overlays."
|
| 494 |
+
else:
|
| 495 |
+
q_idx = right_idx if right_idx >= 0 else (right_state.rows//2)*right_state.cols + (right_state.cols//2)
|
| 496 |
+
cos_self, _, _, _ = compute_self_and_cross(right_state, None, q_idx)
|
| 497 |
+
out_right = render_with_cosmap(right_state, cos_self, overlay_alpha, show_grid_flag,
|
| 498 |
+
select_idx=q_idx, best_idx=None)
|
| 499 |
+
return gr.update(), out_right, "Updated overlays."
|
| 500 |
+
|
| 501 |
+
# ---------- Gradio UI ----------
|
| 502 |
+
with gr.Blocks(title="DINOv3 Patch Similarity (Self & Cross)") as demo:
|
| 503 |
+
gr.Markdown(
|
| 504 |
+
"""
|
| 505 |
+
# DINOv3 Patch Similarity (Self & Cross)
|
| 506 |
+
1) Pick **Dataset** (LVD-1689M / SAT-493M).
|
| 507 |
+
2) Pick **Model**.
|
| 508 |
+
3) Upload one or two images (or paste URLs) and press **Initialize / Update**.
|
| 509 |
+
- Click on a patch to update overlays.
|
| 510 |
+
- In two-image mode, the non-active image hides the red selection and shows **yellow** best match.
|
| 511 |
+
"""
|
| 512 |
+
)
|
| 513 |
+
|
| 514 |
+
with gr.Row():
|
| 515 |
+
dataset_radio = gr.Radio(
|
| 516 |
+
label="Dataset",
|
| 517 |
+
choices=list(DATASET_LABELS.keys()),
|
| 518 |
+
value=DEFAULT_DATASET_LABEL,
|
| 519 |
+
interactive=True
|
| 520 |
+
)
|
| 521 |
+
initial_key = DATASET_LABELS[DEFAULT_DATASET_LABEL]
|
| 522 |
+
initial_models = MODEL_OPTIONS_BY_DATASET.get(initial_key, [])
|
| 523 |
+
model_dropdown = gr.Dropdown(
|
| 524 |
+
label="Model name",
|
| 525 |
+
choices=initial_models,
|
| 526 |
+
value=(initial_models[0] if initial_models else None),
|
| 527 |
+
interactive=True
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
# initial sample labels based on default dataset
|
| 531 |
+
initial_sample_labels = [label for label, _ in SAMPLE_URL_CHOICES.get(initial_key, [])]
|
| 532 |
+
|
| 533 |
+
with gr.Row():
|
| 534 |
+
with gr.Column():
|
| 535 |
+
left_input = gr.Image(label="Left Image (upload)", type="pil",
|
| 536 |
+
sources=["upload", "clipboard", "webcam"], interactive=True)
|
| 537 |
+
left_url = gr.Textbox(label="Left Image URL (optional)", placeholder="https://...")
|
| 538 |
+
left_sample = gr.Dropdown(label="Use a sample URL",
|
| 539 |
+
choices=initial_sample_labels,
|
| 540 |
+
value=(initial_sample_labels[0] if initial_sample_labels else None),
|
| 541 |
+
interactive=True)
|
| 542 |
+
with gr.Column():
|
| 543 |
+
right_input = gr.Image(label="Right Image (upload)", type="pil",
|
| 544 |
+
sources=["upload", "clipboard", "webcam"], interactive=True)
|
| 545 |
+
right_url = gr.Textbox(label="Right Image URL (optional)", placeholder="https://...")
|
| 546 |
+
right_sample = gr.Dropdown(label="Use a sample URL",
|
| 547 |
+
choices=initial_sample_labels,
|
| 548 |
+
value=(initial_sample_labels[0] if initial_sample_labels else None),
|
| 549 |
+
interactive=True)
|
| 550 |
+
|
| 551 |
+
with gr.Accordion("Overlay Settings", open=True):
|
| 552 |
+
show_grid = gr.Checkbox(label="Show patch grid", value=DEFAULT_SHOW_GRID)
|
| 553 |
+
overlay_alpha = gr.Slider(label="Overlay alpha", minimum=0.0, maximum=1.0,
|
| 554 |
+
value=DEFAULT_OVERLAY_ALPHA, step=0.01)
|
| 555 |
+
|
| 556 |
+
init_btn = gr.Button("Initialize / Update", variant="primary")
|
| 557 |
+
|
| 558 |
+
with gr.Row():
|
| 559 |
+
left_view = gr.Image(label="LEFT (click to select patch)", interactive=True)
|
| 560 |
+
right_view = gr.Image(label="RIGHT (click to select patch)", interactive=True)
|
| 561 |
+
|
| 562 |
+
status = gr.Markdown("")
|
| 563 |
+
|
| 564 |
+
# Hidden states
|
| 565 |
+
left_state = gr.State(None)
|
| 566 |
+
right_state = gr.State(None)
|
| 567 |
+
active_side = gr.State(0)
|
| 568 |
+
left_idx = gr.State(-1)
|
| 569 |
+
right_idx = gr.State(-1)
|
| 570 |
+
ps_state = gr.State(16)
|
| 571 |
+
|
| 572 |
+
# Update model dropdown and sample lists when dataset changes
|
| 573 |
+
dataset_radio.change(
|
| 574 |
+
fn=update_model_and_samples,
|
| 575 |
+
inputs=[dataset_radio],
|
| 576 |
+
outputs=[model_dropdown, left_sample, right_sample]
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
# When a sample is chosen, set URL and clear any uploaded image (prefer URL)
|
| 580 |
+
left_sample.change(
|
| 581 |
+
fn=_apply_sample,
|
| 582 |
+
inputs=[dataset_radio, left_sample],
|
| 583 |
+
outputs=[left_url, left_input]
|
| 584 |
+
)
|
| 585 |
+
right_sample.change(
|
| 586 |
+
fn=_apply_sample,
|
| 587 |
+
inputs=[dataset_radio, right_sample],
|
| 588 |
+
outputs=[right_url, right_input]
|
| 589 |
+
)
|
| 590 |
+
|
| 591 |
+
# Initialize / reload model + overlays
|
| 592 |
+
init_btn.click(
|
| 593 |
+
fn=init_states,
|
| 594 |
+
inputs=[left_input, left_url, right_input, right_url, dataset_radio, model_dropdown, show_grid, overlay_alpha],
|
| 595 |
+
outputs=[left_view, right_view, left_state, right_state, active_side, left_idx, right_idx, ps_state, status],
|
| 596 |
+
show_progress=True
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
# Click handlers
|
| 600 |
+
left_view.select(
|
| 601 |
+
fn=on_select_left,
|
| 602 |
+
inputs=[left_state, right_state, show_grid, overlay_alpha, ps_state],
|
| 603 |
+
outputs=[left_view, right_view, active_side, left_idx, right_idx, status]
|
| 604 |
+
)
|
| 605 |
+
right_view.select(
|
| 606 |
+
fn=on_select_right,
|
| 607 |
+
inputs=[left_state, right_state, show_grid, overlay_alpha, ps_state],
|
| 608 |
+
outputs=[left_view, right_view, active_side, left_idx, right_idx, status]
|
| 609 |
+
)
|
| 610 |
+
|
| 611 |
+
# Live re-render on setting changes
|
| 612 |
+
show_grid.change(
|
| 613 |
+
fn=rebuild_with_settings,
|
| 614 |
+
inputs=[left_state, right_state, active_side, left_idx, right_idx, show_grid, overlay_alpha, ps_state],
|
| 615 |
+
outputs=[left_view, right_view, status]
|
| 616 |
+
)
|
| 617 |
+
overlay_alpha.change(
|
| 618 |
+
fn=rebuild_with_settings,
|
| 619 |
+
inputs=[left_state, right_state, active_side, left_idx, right_idx, show_grid, overlay_alpha, ps_state],
|
| 620 |
+
outputs=[left_view, right_view, status]
|
| 621 |
+
)
|
| 622 |
+
|
| 623 |
+
if __name__ == "__main__":
|
| 624 |
+
demo.queue().launch()
|