File size: 27,113 Bytes
0663be1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>DINOv3 Web - Interactive Selection</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&display=swap" rel="stylesheet" />
    <style>
      body {
        font-family:
          "Inter",
          -apple-system,
          BlinkMacSystemFont,
          "Segoe UI",
          Roboto,
          Helvetica,
          Arial,
          sans-serif;
      }
      /* Custom styles for the range slider */
      input[type="range"] {
        -webkit-appearance: none;
        appearance: none;
        width: 100%;
        height: 0.5rem;
        background: #4a5568; /* gray-700 */
        border-radius: 0.25rem;
        outline: none;
        opacity: 0.7;
        transition: opacity 0.2s;
      }
      input[type="range"]:hover {
        opacity: 1;
      }
      input[type="range"]::-webkit-slider-thumb {
        -webkit-appearance: none;
        appearance: none;
        width: 1.25rem;
        height: 1.25rem;
        background: #90cdf4; /* blue-300 */
        cursor: pointer;
        border-radius: 50%;
      }
      input[type="range"]::-moz-range-thumb {
        width: 1.25rem;
        height: 1.25rem;
        background: #90cdf4; /* blue-300 */
        cursor: pointer;
        border-radius: 50%;
      }
      /* Additional styles for the toggle switch */
      #modeToggle:checked ~ .dot {
        transform: translateX(1.5rem); /* 24px */
      }
      #modeToggle:checked ~ .block {
        background-color: #3b82f6; /* blue-500 */
      }
    </style>
  </head>
  <body class="bg-gray-900 text-gray-300 flex flex-col items-center justify-center min-h-screen p-4 sm:p-6 lg:p-8">
    <div
      class="w-full max-w-3xl bg-gray-800/50 backdrop-blur-sm rounded-2xl shadow-2xl shadow-black/30 border border-gray-700 p-6 sm:p-8 text-center"
    >
      <h1
        class="text-3xl sm:text-4xl font-bold text-transparent bg-clip-text bg-gradient-to-r from-blue-400 to-purple-500 mb-2"
      >
        DINOv3 Web
      </h1>
      <p class="text-gray-400 mb-8 max-w-xl mx-auto">
        Visualize features locally. Hover to see the heatmap, then click on an object to select it.
      </p>

      <div class="space-y-6">
        <div
          id="dropZone"
          class="relative flex flex-col items-center justify-center bg-gray-900/50 border-2 border-dashed border-gray-600 rounded-xl p-6 text-center group hover:border-blue-500 transition-colors duration-300"
        >
          <svg
            class="w-12 h-12 mb-4 text-gray-500 group-hover:text-blue-500 transition-colors duration-300"
            aria-hidden="true"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 20 16"
          >
            <path
              stroke="currentColor"
              stroke-linecap="round"
              stroke-linejoin="round"
              stroke-width="1.5"
              d="M13 13h3a3 3 0 0 0 0-6h-.025A5.56 5.56 0 0 0 16 6.5 5.5 5.5 0 0 0 5.207 5.021C5.137 5.017 5.071 5 5 5a4 4 0 0 0 0 8h2.167M10 15V6m0 0L8 8m2-2 2 2"
            />
          </svg>
          <p class="font-semibold text-gray-300">Click to upload or drag & drop</p>
          <p class="text-xs text-gray-500 mb-2">PNG, JPG, or other image formats</p>
          <p class="text-sm text-gray-400">
            Or
            <button
              id="exampleBtn"
              class="relative z-10 text-blue-400 hover:text-blue-300 font-semibold underline bg-transparent border-none cursor-pointer p-0"
            >
              try an example</button
            >.
          </p>
          <label for="imageLoader" class="absolute inset-0 cursor-pointer z-0"></label>
          <input type="file" id="imageLoader" accept="image/*" class="hidden" />
        </div>

        <div class="bg-gray-900/50 p-4 rounded-xl border border-gray-700 space-y-4">
          <div class="grid grid-cols-1 sm:grid-cols-2 gap-4 items-center">
            <div class="flex items-center justify-center w-full space-x-3">
              <label for="scaleSlider" class="text-sm font-medium text-gray-400 whitespace-nowrap">Scale:</label>
              <input id="scaleSlider" type="range" min="0.25" max="4" step="0.25" value="1" class="w-full" />
              <span id="scaleValue" class="text-sm font-medium text-gray-400 w-12 text-right">1.00x</span>
            </div>
            <div class="flex items-center justify-center space-x-3">
              <span class="text-sm font-medium text-gray-400">Overlay</span>
              <label for="modeToggle" class="flex items-center cursor-pointer">
                <div class="relative">
                  <input type="checkbox" id="modeToggle" class="sr-only" />
                  <div class="block bg-gray-600 w-14 h-8 rounded-full"></div>
                  <div class="dot absolute left-1 top-1 bg-white w-6 h-6 rounded-full transition transform"></div>
                </div>
              </label>
              <span class="text-sm font-medium text-gray-400">Heatmap</span>
            </div>
          </div>
        </div>

        <div id="status" class="flex items-center justify-center w-full font-medium text-gray-400 h-6">
          <svg
            id="spinner"
            class="animate-spin mr-3 h-5 w-5 text-blue-400 hidden"
            xmlns="http://www.w3.org/2000/svg"
            fill="none"
            viewBox="0 0 24 24"
          >
            <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
            <path
              class="opacity-75"
              fill="currentColor"
              d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"
            ></path>
          </svg>
          <span id="statusText"></span>
        </div>

        <div
          id="canvasContainer"
          class="w-full bg-gray-900/50 rounded-lg border border-gray-700 shadow-inner overflow-hidden min-h-[250px] flex items-center justify-center p-2"
        >
          <canvas id="imageCanvas" class="hidden rounded-lg cursor-crosshair block max-w-full h-auto"></canvas>
          <div id="canvasPlaceholder" class="text-gray-500">Your image will appear here</div>
        </div>
        
        <div id="selectionTools" class="hidden bg-gray-900/50 p-4 rounded-xl border border-gray-700 space-y-4">
            <h2 class="text-lg font-semibold text-gray-300">Selection Tools</h2>
            <div class="flex items-center justify-center w-full space-x-3">
              <label for="thresholdSlider" class="text-sm font-medium text-gray-400 whitespace-nowrap">Threshold:</label>
              <input id="thresholdSlider" type="range" min="0" max="1" step="0.01" value="0.5" class="w-full" />
              <span id="thresholdValue" class="text-sm font-medium text-gray-400 w-12 text-right">0.50</span>
            </div>
            <div id="selectionCanvasContainer" class="w-full bg-gray-900/50 rounded-lg border border-gray-700 shadow-inner overflow-hidden min-h-[250px] flex items-center justify-center p-2">
                <canvas id="selectionCanvas" class="rounded-lg block max-w-full h-auto"></canvas>
            </div>
             <div class="flex justify-center items-center space-x-4 pt-2">
                <button id="saveBtn" class="bg-blue-600 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded-lg transition-colors">
                    Save Selection
                </button>
                 <button id="clearBtn" class="bg-gray-600 hover:bg-gray-700 text-white font-bold py-2 px-4 rounded-lg transition-colors">
                    Clear Selections
                </button>
            </div>
        </div>
        </div>
    </div>

    <script type="module">
      import { pipeline, RawImage, matmul } from "https://cdn.jsdelivr.net/npm/@huggingface/[email protected]";

      // --- 1. Configuration & Global Variables ---
      const MODEL_ID = "onnx-community/dinov3-vits16-pretrain-lvd1689m-ONNX";
      const EXAMPLE_IMAGE_URL =
        "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/cats.png";

      // DOM Elements
      const imageLoader = document.getElementById("imageLoader");
      const exampleBtn = document.getElementById("exampleBtn");
      const imageCanvas = document.getElementById("imageCanvas");
      const ctx = imageCanvas.getContext("2d");
      const spinner = document.getElementById("spinner");
      const statusText = document.getElementById("statusText");
      const canvasContainer = document.getElementById("canvasContainer");
      const canvasPlaceholder = document.getElementById("canvasPlaceholder");
      const dropZone = document.getElementById("dropZone");
      const modeToggle = document.getElementById("modeToggle");
      const scaleSlider = document.getElementById("scaleSlider");
      const scaleValue = document.getElementById("scaleValue");
      
      // New Selection Elements
      const selectionTools = document.getElementById("selectionTools");
      const thresholdSlider = document.getElementById("thresholdSlider");
      const thresholdValue = document.getElementById("thresholdValue");
      const selectionCanvas = document.getElementById("selectionCanvas");
      const selectionCtx = selectionCanvas.getContext("2d");
      const saveBtn = document.getElementById("saveBtn");
      const clearBtn = document.getElementById("clearBtn");

      // Application State
      let extractor = null;
      let similarityScores = null;
      let originalImage = null;
      let currentImageUrl = null;
      let patchSize = null;
      let isOverlayMode = true;
      let lastHoverData = null;
      let imageScale = 1.0;
      let animationFrameId = null;
      let lastMouseEvent = null;
      let maxPixels = null;
      let selectionThreshold = 0.5; // New state for selection
      let selectedPatchesMask = new Set(); // New state for combined selections

      // --- 2. Core Application Logic ---
      function updateStatus(text, isLoading = false) {
        statusText.textContent = text;
        spinner.style.display = isLoading ? "block" : "none";
      }

      async function initialize() {
        const isWebGpuSupported = !!navigator.gpu;
        const isMobile = /Mobi|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
          navigator.userAgent,
        );
        maxPixels = isMobile ? 1048576 : 2097152;

        const device = isWebGpuSupported ? "webgpu" : "wasm";
        const dtype = isWebGpuSupported ? "q4" : "q8";

        let statusMessage = `Loading model (${device.toUpperCase()})`;
        if (isMobile) statusMessage += ". Mobile Detected.";
        updateStatus(statusMessage, true);

        try {
          extractor = await pipeline("image-feature-extraction", MODEL_ID, {
            device,
            dtype,
          });
          extractor.processor.image_processor.do_resize = false;
          patchSize = extractor.model.config.patch_size;
          updateStatus("Ready. Please select an image.");
        } catch (error) {
          updateStatus("Failed to load the model. Please refresh.");
          console.error("Model loading error:", error);
        }

        imageLoader.addEventListener("change", handleImageUpload);
        exampleBtn.addEventListener("click", handleExample);
        imageCanvas.addEventListener("mousemove", handleMouseMove);
        imageCanvas.addEventListener("mouseleave", clearHighlights);
        imageCanvas.addEventListener("touchmove", handleTouchMove);
        imageCanvas.addEventListener("touchend", clearHighlights);
        dropZone.addEventListener("dragover", handleDragOver);
        dropZone.addEventListener("dragleave", handleDragLeave);
        dropZone.addEventListener("drop", handleDrop);
        modeToggle.addEventListener("change", handleModeChange);
        scaleSlider.addEventListener("input", handleSliderInput);
        scaleSlider.addEventListener("change", handleSliderChange);

        // New Event Listeners
        imageCanvas.addEventListener("click", handleCanvasClick);
        thresholdSlider.addEventListener("input", handleThresholdChange);
        saveBtn.addEventListener("click", handleSave);
        clearBtn.addEventListener("click", handleClearSelections);
      }

      async function handleExample() {
        updateStatus("Loading example image...", true);
        try {
          const response = await fetch(EXAMPLE_IMAGE_URL);
          const blob = await response.blob();
          loadImageOntoCanvas(URL.createObjectURL(blob));
        } catch (error) {
          updateStatus("Failed to load example image.");
          console.error("Example load error:", error);
        }
      }

      function handleImageUpload(event) {
        const file = event.target.files[0];
        if (file) loadImageOntoCanvas(URL.createObjectURL(file));
      }

      function handleDragOver(event) {
        event.preventDefault();
        dropZone.classList.add("border-blue-500", "bg-gray-800");
      }

      function handleDragLeave(event) {
        event.preventDefault();
        dropZone.classList.remove("border-blue-500", "bg-gray-800");
      }

      function handleDrop(event) {
        event.preventDefault();
        dropZone.classList.remove("border-blue-500", "bg-gray-800");
        const file = event.dataTransfer.files[0];
        if (file && file.type.startsWith("image/")) {
          if (event.target.id === "exampleBtn") return;
          loadImageOntoCanvas(URL.createObjectURL(file));
        } else {
          updateStatus("Please drop an image file.");
        }
      }

      function handleModeChange(event) {
        isOverlayMode = !event.target.checked;
        if (lastHoverData) {
          drawHighlights(lastHoverData.queryIndex, lastHoverData.allPatches);
        } else {
          clearHighlights();
        }
      }

      function handleSliderInput(event) {
        imageScale = parseFloat(event.target.value);
        scaleValue.textContent = `${imageScale.toFixed(2)}x`;
      }

      function handleSliderChange() {
        if (currentImageUrl) {
          loadImageOntoCanvas(currentImageUrl);
        }
      }

      function loadImageOntoCanvas(imageUrl) {
        currentImageUrl = imageUrl;
        originalImage = new Image();
        originalImage.onload = async () => {
          if (!patchSize) {
            updateStatus("Error: Model not ready, patch size is unknown.");
            return;
          }

          canvasPlaceholder.style.display = "none";
          imageCanvas.style.display = "block";
          selectionTools.style.display = 'block'; // Show selection tools

          let newWidth = originalImage.naturalWidth * imageScale;
          let newHeight = originalImage.naturalHeight * imageScale;

          const numPixels = newWidth * newHeight;
          if (numPixels > maxPixels) {
            const scaleRatio = Math.sqrt(maxPixels / numPixels);
            newWidth *= scaleRatio;
            newHeight *= scaleRatio;
          }

          const croppedWidth = Math.floor(newWidth / patchSize) * patchSize;
          const croppedHeight = Math.floor(newHeight / patchSize) * patchSize;

          if (croppedWidth < patchSize || croppedHeight < patchSize) {
            updateStatus("Scaled image is too small to process.");
            imageCanvas.style.display = "none";
            selectionTools.style.display = 'none';
            canvasPlaceholder.style.display = "block";
            canvasPlaceholder.textContent = "Scaled image is too small.";
            return;
          }

          imageCanvas.width = croppedWidth;
          imageCanvas.height = croppedHeight;
          // Also set the selection canvas size
          selectionCanvas.width = croppedWidth;
          selectionCanvas.height = croppedHeight;

          ctx.drawImage(originalImage, 0, 0, croppedWidth, croppedHeight);
          handleClearSelections(); // Clear previous selections
          await processImage();

          setTimeout(() => {
            canvasContainer.scrollIntoView({ behavior: "smooth", block: "center" });
          }, 100);
        };
        originalImage.onerror = () => {
          updateStatus("Failed to load the selected image.");
          canvasPlaceholder.style.display = "block";
          imageCanvas.style.display = "none";
          selectionTools.style.display = 'none';
        };
        originalImage.src = imageUrl;
      }

      async function processImage() {
        if (!extractor) return;
        updateStatus("Analyzing image... 🧠", true);
        similarityScores = null;
        lastHoverData = null;
        try {
          const imageData = await RawImage.fromCanvas(imageCanvas);
          const features = await extractor(imageData, { pooling: "none" });
          const numRegisterTokens = extractor.model.config.num_register_tokens ?? 0;
          const startIndex = 1 + numRegisterTokens;
          const patchFeatures = features.slice(null, [startIndex, null]);
          const normalizedFeatures = patchFeatures.normalize(2, -1);
          const scores = await matmul(normalizedFeatures, normalizedFeatures.permute(0, 2, 1));
          similarityScores = (await scores.tolist())[0];
          updateStatus(
            `Image processed (${imageCanvas.width}x${imageCanvas.height}). Hover and click to select objects. ✨`,
          );
        } catch (error) {
          updateStatus("An error occurred during image processing.");
          console.error("Processing error:", error);
        }
      }

      function handleTouchMove(event) {
        event.preventDefault();
        if (event.touches.length > 0) {
          handleMouseMove(event.touches[0]);
        }
      }

      function handleMouseMove(event) {
        lastMouseEvent = event;
        if (!animationFrameId) {
          animationFrameId = requestAnimationFrame(drawLoop);
        }
      }

      function drawLoop() {
        if (!lastMouseEvent || !similarityScores || !originalImage) {
          animationFrameId = null;
          return;
        }

        const event = lastMouseEvent;
        const rect = imageCanvas.getBoundingClientRect();
        const scaleX = imageCanvas.width / rect.width;
        const scaleY = imageCanvas.height / rect.height;
        const x = (event.clientX - rect.left) * scaleX;
        const y = (event.clientY - rect.top) * scaleY;

        if (x < 0 || x >= imageCanvas.width || y < 0 || y >= imageCanvas.height) {
          animationFrameId = null;
          return;
        }

        const patchesPerRow = imageCanvas.width / patchSize;
        const patchX = Math.floor(x / patchSize);
        const patchY = Math.floor(y / patchSize);
        const queryPatchIndex = patchY * patchesPerRow + patchX;

        if (queryPatchIndex < 0 || queryPatchIndex >= similarityScores.length || !similarityScores[queryPatchIndex]) {
          animationFrameId = null;
          return;
        }

        const allPatches = Array.from(similarityScores[queryPatchIndex]).map((score, index) => ({ score, index }));

        lastHoverData = { queryIndex: queryPatchIndex, allPatches };
        drawHighlights(queryPatchIndex, allPatches);

        animationFrameId = null;
      }

      const INFERNO_COLORMAP = [
        [0.0, [0, 0, 4]],
        [0.1, [39, 12, 69]],
        [0.2, [84, 15, 104]],
        [0.3, [128, 31, 103]],
        [0.4, [170, 48, 88]],
        [0.5, [209, 70, 68]],
        [0.6, [240, 97, 47]],
        [0.7, [253, 138, 28]],
        [0.8, [252, 185, 26]],
        [0.9, [240, 231, 56]],
        [1.0, [252, 255, 160]],
      ];

      function getInfernoColor(t) {
        for (let i = 1; i < INFERNO_COLORMAP.length; i++) {
          const [t_prev, c_prev] = INFERNO_COLORMAP[i - 1];
          const [t_curr, c_curr] = INFERNO_COLORMAP[i];
          if (t <= t_curr) {
            const t_interp = (t - t_prev) / (t_curr - t_prev);
            const r = c_prev[0] + t_interp * (c_curr[0] - c_prev[0]);
            const g = c_prev[1] + t_interp * (c_curr[1] - c_prev[1]);
            const b = c_prev[2] + t_interp * (c_curr[2] - c_prev[2]);
            return `rgb(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)})`;
          }
        }
        return `rgb(${INFERNO_COLORMAP[INFERNO_COLORMAP.length - 1][1].join(",")})`;
      }

      function drawHighlights(queryIndex, allPatches) {
        const patchesPerRow = imageCanvas.width / patchSize;

        if (isOverlayMode) {
          ctx.drawImage(originalImage, 0, 0, imageCanvas.width, imageCanvas.height);
          ctx.fillStyle = "rgba(0, 0, 0, 0.6)";
          ctx.fillRect(0, 0, imageCanvas.width, imageCanvas.height);
        } else {
          ctx.fillStyle = getInfernoColor(0);
          ctx.fillRect(0, 0, imageCanvas.width, imageCanvas.height);
        }

        if (allPatches.length > 0) {
          const scores = allPatches.map((p) => p.score);
          const minScore = Math.min(...scores);
          const maxScore = Math.max(...scores);
          const scoreRange = maxScore - minScore;

          for (const patch of allPatches) {
            if (patch.index === queryIndex) continue;
            const normalizedScore = scoreRange > 0.0001 ? (patch.score - minScore) / scoreRange : 1;
            const patchY = Math.floor(patch.index / patchesPerRow);
            const patchX = patch.index % patchesPerRow;

            if (isOverlayMode) {
              const brightness = Math.pow(normalizedScore, 2) * 0.8;
              ctx.fillStyle = `rgba(255, 255, 255, ${brightness})`;
            } else {
              ctx.fillStyle = getInfernoColor(normalizedScore);
            }
            ctx.fillRect(patchX * patchSize, patchY * patchSize, patchSize, patchSize);
          }
        }

        const queryY = Math.floor(queryIndex / patchesPerRow);
        const queryX = queryIndex % patchesPerRow;
        ctx.strokeStyle = isOverlayMode ? "rgba(129, 188, 255, 0.9)" : "cyan";
        ctx.lineWidth = 2;
        ctx.strokeRect(queryX * patchSize, queryY * patchSize, patchSize, patchSize);
      }

      function clearHighlights() {
        if (animationFrameId) {
          cancelAnimationFrame(animationFrameId);
          animationFrameId = null;
        }
        lastMouseEvent = null;
        lastHoverData = null;
        if (originalImage) {
          ctx.drawImage(originalImage, 0, 0, imageCanvas.width, imageCanvas.height);
        }
      }
      
      // --- 3. New Selection Logic ---

      function handleThresholdChange(event) {
          selectionThreshold = parseFloat(event.target.value);
          thresholdValue.textContent = selectionThreshold.toFixed(2);
      }

      function handleCanvasClick(event) {
          if (!lastHoverData) {
              updateStatus("Please hover over the image first to generate a heatmap.");
              return;
          }
          
          const { queryIndex, allPatches } = lastHoverData;
          const patchesPerRow = imageCanvas.width / patchSize;
          const numRows = imageCanvas.height / patchSize;

          const selectedInThisClick = floodFillSelect(
              queryIndex,
              allPatches,
              patchesPerRow,
              numRows,
              selectionThreshold
          );

          // Add the new selection to the master mask
          selectedInThisClick.forEach(patchIndex => {
              selectedPatchesMask.add(patchIndex);
          });

          updateSelectionCanvas();
      }
      
      function floodFillSelect(startPatchIndex, allPatches, patchesPerRow, numRows, threshold) {
          const selected = new Set();
          const queue = [startPatchIndex];
          const visited = new Set([startPatchIndex]);
          
          const scores = allPatches.map(p => p.score);
          const minScore = Math.min(...scores);
          const maxScore = Math.max(...scores);
          const scoreRange = maxScore - minScore;
          
          const getNormalizedScore = (index) => {
              if (scoreRange <= 0.0001) return 1;
              return (allPatches[index].score - minScore) / scoreRange;
          };

          while (queue.length > 0) {
              const currentIndex = queue.shift();
              
              if (getNormalizedScore(currentIndex) >= threshold) {
                  selected.add(currentIndex);
                  
                  const currentY = Math.floor(currentIndex / patchesPerRow);
                  const currentX = currentIndex % patchesPerRow;
                  
                  // Check neighbors [top, right, bottom, left]
                  const neighbors = [
                      { x: currentX, y: currentY - 1 },
                      { x: currentX + 1, y: currentY },
                      { x: currentX, y: currentY + 1 },
                      { x: currentX - 1, y: currentY },
                  ];

                  for (const neighbor of neighbors) {
                      if (neighbor.x >= 0 && neighbor.x < patchesPerRow && neighbor.y >= 0 && neighbor.y < numRows) {
                          const neighborIndex = neighbor.y * patchesPerRow + neighbor.x;
                          if (!visited.has(neighborIndex)) {
                              visited.add(neighborIndex);
                              queue.push(neighborIndex);
                          }
                      }
                  }
              }
          }
          return selected;
      }
      
      function updateSelectionCanvas() {
        selectionCtx.clearRect(0, 0, selectionCanvas.width, selectionCanvas.height);
        const patchesPerRow = imageCanvas.width / patchSize;

        for (const patchIndex of selectedPatchesMask) {
            const patchY = Math.floor(patchIndex / patchesPerRow);
            const patchX = patchIndex % patchesPerRow;
            
            const sx = patchX * patchSize;
            const sy = patchY * patchSize;

            selectionCtx.drawImage(
                originalImage,
                sx, sy, patchSize, patchSize, // Source rectangle from original image
                sx, sy, patchSize, patchSize  // Destination rectangle on selection canvas
            );
        }
      }
      
      function handleSave() {
        if (selectedPatchesMask.size === 0) {
            updateStatus("No selection to save.");
            return;
        }
        const link = document.createElement('a');
        link.download = 'selection.png';
        link.href = selectionCanvas.toDataURL('image/png');
        link.click();
        updateStatus("Selection saved.");
      }

      function handleClearSelections() {
        selectedPatchesMask.clear();
        selectionCtx.clearRect(0, 0, selectionCanvas.width, selectionCanvas.height);
        if (originalImage) {
            updateStatus("Selections cleared. Hover and click to select again.");
        }
      }


      initialize();
    </script>
  </body>
</html>