File size: 36,028 Bytes
f64e380
 
b1e8f11
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f64e380
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
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>OpenAI CLIP Image Search in JavaScript (Using ONNX Web Runtime)</title>
    <script src="enable-threads.js"></script>
    <script src="./vips/vips.js"></script>
  </head>
  <body>
    <style>
      body * {
        font-family: monospace;
      }
    </style>
    <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.12.0/dist/ort.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs@3.17.0/dist/tf.min.js"></script> <!-- NOTE: tfjs is currently only used for image preprocessing stuff. -->
    
    <div>
      <h1 style="font-size:1rem;">Sort/search images using OpenAI's CLIP in your browser</h1>
      <p>This web app sorts/searches through images in a directory on your computer using OpenAI's CLIP model, and the new File System Access API. <a href="https://github.com/josephrocca/clip-image-sorter">Here's the Github repo</a> for this web app, and <a href="https://github.com/josephrocca/openai-clip-js">here's the Github repo</a> for the web-ported CLIP models. Feel free to open an issue or <a href="https://twitter.com/rocca27" target="_blank">DM me on Twitter</a> if you have any questions about this demo.</p>
      <p>All processing happens in your browser, on your device - i.e. your images are <b>not</b> uploaded to a server for processing.</p>
      <p id="browserCompatibilityWarning" style="padding:0.25rem; background:rgb(255, 227, 160); display:none;"><b>Note</b>: This page uses new browser features (File System Access API, and credentialless COEP) that are currently only available in some browsers. As of writing, it works in Chrome, Edge and Brave. Other browsers like Firefox and Safari are often a bit slower in implementing cutting-edge features.</p>
      <script>
        if(Date.now() < 1648725949710+1000*60*60*24*365) { // display until start of April 2023
          browserCompatibilityWarning.style.display = "";
        }
      </script>
      <hr>
      
      <div id="modelNameSelectCtn" style="padding:0.5rem; background:lightgrey; margin:0.5rem;">
        <b>Step 1:</b> Choose model:
        <select onchange="window.MODEL_NAME=this.value;">
          <option value="clip_vit_32">CLIP ViT-B/32 (recommended)</option>
          <option value="clip_vit_32_uint8">CLIP ViT-B/32 (quantized - inaccurate embeddings)</option>
          <option value="lit_b16b">LiT B16B</option>
        </select>
      </div>
      
      <div id="initCtnEl" style="padding:0.5rem; background:lightgrey; margin:0.5rem;">
        <b>Step 2:</b> Download and initialize the models.
        <br>
        Download image model: <progress id="imageModelLoadingProgressBarEl" value="0"></progress> <span id="imageModelLoadingMbEl"></span>
        <br>
        Download text model: <progress id="textModelLoadingProgressBarEl" value="0"></progress> <span id="textModelLoadingMbEl"></span>
        <br>
        Initialize workers: <progress id="workerInitProgressBarEl" value="0"></progress>
        <div style="display:none;"> <!-- more workers (dividing threads between them) doesn't seem to make things faster -->
          Number of image embedding workers/threads: <input id="numThreadsEl" type="range" min="1" max="4" value="1" oninput="numThreadsDisplayEl.textContent=this.value"> <span id="numThreadsDisplayEl"></span> <script>numThreadsEl.max = navigator.hardwareConcurrency; numThreadsDisplayEl.textContent=numThreadsEl.value;</script>
        </div>
        <br>
        <button id="initWorkersBtn" onclick="modelNameSelectCtn.style.pointerEvents='none'; modelNameSelectCtn.style.opacity=0.5; initializeWorkers()">initialize workers</button>
      </div>

      <div id="pickDirCtnEl" style="opacity:0.5; pointer-events:none; padding:0.5rem; background:lightgrey; margin:0.5rem;">
        <b>Step 3:</b> Pick a directory of images (images in subdirectories will be included).
        <br>
        <button id="pickDirectoryBtn" onclick="pickDirectory({source:'local'})">pick directory</button> &nbsp;&nbsp;&nbsp;&nbsp;or&nbsp;&nbsp;&nbsp;&nbsp; <button id="useRedditImagesBtn" onclick="pickDirectory({source:'reddit'})">use ~200k reddit images</button> (remove nsfw:<input id="removeRedditNsfwEl" type="checkbox" checked>)
        <br>
        <div id="redditLoadProgressCtn" style="display:none;">Download progress: <progress id="redditProgressBarEl" value="0"></progress> <span id="redditProgressMbEl"></span></div>
        <div id="existingEmbeddingsProgressCtn" style="display:none;">Loading existing embeddings: <span id="existingEmbeddingsLoadedEl">none</span></div>
      </div>
      
      <div id="computeEmbeddingsCtnEl" style="opacity:0.5; pointer-events:none; padding:0.5rem; background:lightgrey; margin:0.5rem;">
        <b>Step 4:</b> Compute image embeddings. <span style="opacity:0.5;">(they will be saved as &lt;ModelName&gt;_embeddings.tsv in the selected directory)</span>
        <br>
        <button id="computeEmbeddingsBtn" onclick="computeImageEmbeddings(); this.disabled=true;">compute image embeddings</button>
        <br>
        <span id="computeEmbeddingsProgressEl">0</span> images embedded (<span id="computeEmbeddingsSpeedEl">?</span> ms per image) <span id="preexistingEmbeddingsEl"></span>
      </div>

      <div id="existingEmbeddingsFoundCtnEl" style="display:none; padding:0.5rem; background:lightgrey; margin:0.5rem;">
        <b>Step 5:</b> <b>Existing embeddings found.</b>
        <br>
        Only needed if you've added or changed images: <button onclick="existingEmbeddingsFoundCtnEl.style.display='none'; computeEmbeddingsCtnEl.style.display=''; disableCtn(searchCtnEl); computeEmbeddingsBtn.click()">(re)compute image embeddings</button>
        <input id="onlyEmbedNewImagesCheckbox" type="checkbox" checked> Only new images?
      </div>

      <div id="searchCtnEl" style="opacity:0.5; pointer-events:none; padding:0.5rem; background:lightgrey; margin:0.5rem;">
        <b>Step 6:</b> Enter a search term.
        <br>
        <input id="searchTextEl" style="width:300px;" value="" placeholder="Enter search text here..." onkeyup="if(event.which==13) searchSort()">
        <button id="searchBtn" onclick="searchSort()">search</button>
      </div>
    </div>

    <hr>
    <b>Results</b> <span style="opacity:0.5;">(hover for cosine similarities)</span>
    <div id="resultsEl" style="margin-top:1rem; min-height:100vh;"><span style="opacity:0.5;">Click the search button to compute the results.</span></div>
    
    <script>
      /////////////
      //  STEP 1 //
      /////////////
      window.MODEL_NAME = "clip_vit_32";
      window.modelData = {
        clip_vit_32: {
          image: {
            modelUrl: (quantized) => `https://huggingface.co/rocca/openai-clip-js/resolve/main/clip-image-vit-32-${quantized ? "uint8" : "float32"}.onnx`,
            embed: async function(blob, session) {
              let rgbData = await getRgbData(blob);
              const feeds = {input: new ort.Tensor('float32', rgbData, [1,3,224,224])};
              const results = await session.run(feeds);
              const embedVec = results["output"].data; // Float32Array
              return embedVec;
            }
          },
          text: {
            modelUrl: (quantized) => `https://huggingface.co/rocca/openai-clip-js/resolve/main/clip-text-vit-32-${quantized ? "uint8" : "float32-int32"}.onnx`,
            embed: async function(text, session) {
              if(!window.textTokenizerClip) {
                let Tokenizer = (await import("https://deno.land/x/clip_bpe@v0.0.6/mod.js")).default;
                window.textTokenizerClip = new Tokenizer(); 
              }
              let textTokens = window.textTokenizerClip.encodeForCLIP(text);
              textTokens = Int32Array.from(textTokens);
              const feeds = {input: new ort.Tensor('int32', textTokens, [1, 77])};
              const results = await session.run(feeds);
              return [...results["output"].data];
            },
          }
        },
        lit_b16b: {
          image: {
            modelUrl: () => 'https://huggingface.co/rocca/lit-web/resolve/main/embed_images.onnx',
            embed: async function(blob, session) {
              
              // TODO: Maybe remove tf from this code so you can remove the whole tfjs dependency
              blob = await bicubicResizeAndCenterCrop(blob);
              let inputImg = new Image();
              await new Promise(r => inputImg.onload=r, inputImg.src=URL.createObjectURL(blob));
              let img = tf.browser.fromPixels(inputImg);
              img = tf.sub(tf.div(tf.expandDims(img), 127.5), 1);
              let float32RgbData = img.dataSync();
              
              const feeds = {'images': new ort.Tensor('float32', float32RgbData, [1,224,224,3])};
              const results = await session.run(feeds);
              return results["Identity_1:0"].data;
            },
          },
          text: {
            modelUrl: () => 'https://huggingface.co/rocca/lit-web/resolve/main/embed_text_tokens.onnx',
            embed: async function(text, session) {
              if(!window.bertTextTokenizerLit) {
                window.bertTextTokenizerLit = await import("./bert-text-tokenizer.js").then(m => new m.BertTokenizer());
                await window.bertTextTokenizerLit.load();
              }
              let textTokens = window.bertTextTokenizerLit.tokenize(text);
              textTokens.unshift(101); // manually put CLS token at the start
              textTokens.length = 16;
              textTokens = [...textTokens.slice(0, 16)].map(e => e == undefined ? 0 : e); // pad with zeros to length of 16
              textTokens = Int32Array.from(textTokens);
              const feeds = {'text_tokens': new ort.Tensor('int32', textTokens, [1,16])};
              const results = await session.run(feeds);
              return [...results["Identity_1:0"].data];
            }
          }
        },
      };
      let imageWorkers = [];
      let onnxImageSessions = [];
      let onnxTextSession;
      let textTokenizer;
      async function initializeWorkers() {
        initWorkersBtn.disabled = true;
        numThreadsEl.disabled = true;
        
        let useQuantizedModel = false;
        
        if(MODEL_NAME.endsWith("_uint8")) {
          MODEL_NAME = MODEL_NAME.replace(/_uint8$/g, "");
          useQuantizedModel = true;
        }
        
        let imageOnnxBlobPromise = downloadBlobWithProgress(window.modelData[MODEL_NAME].image.modelUrl(useQuantizedModel), function(e) {
          let ratio = e.loaded / e.total;
          imageModelLoadingProgressBarEl.value = ratio;
          imageModelLoadingMbEl.innerHTML = Math.round(ratio*e.total/1e6)+" MB";
        });

        let textOnnxBlobPromise = downloadBlobWithProgress(window.modelData[MODEL_NAME].text.modelUrl(useQuantizedModel), function(e) {
          let ratio = e.loaded / e.total;
          textModelLoadingProgressBarEl.value = ratio;
          textModelLoadingMbEl.innerHTML = Math.round(ratio*e.total/1e6)+" MB";
        });

        let [imageOnnxBlob, textOnnxBlob] = await Promise.all([imageOnnxBlobPromise, textOnnxBlobPromise])

        let imageModelUrl = window.URL.createObjectURL(imageOnnxBlob);
        let textModelUrl = window.URL.createObjectURL(textOnnxBlob);
        
        let numImageWorkers = Number(numThreadsEl.value);
        
        // Inference latency is about 5x faster with wasm threads, but this requires these headers: https://web.dev/coop-coep/ I'm using this as a hack (in enable-threads.js) since Github pages doesn't allow setting headers: https://github.com/gzuidhof/coi-serviceworker
        if(self.crossOriginIsolated) {
          ort.env.wasm.numThreads = Math.ceil(navigator.hardwareConcurrency / numImageWorkers) / 2; // divide by two to utilise only half the CPU's threads because trying to use all the cpu's threads actually makes it slower
        }

        workerInitProgressBarEl.max = numImageWorkers + 2; // +2 because of text model and bpe library
        
        let imageModelExecutionProviders = ["wasm"]; // webgl is not compatible with this model (need to tweak conversion data/op types)

        for(let i = 0; i < numImageWorkers; i++) {
          let session = await ort.InferenceSession.create(imageModelUrl, { executionProviders: imageModelExecutionProviders }); 
          onnxImageSessions.push(session);
          imageWorkers.push({
            session,
            busy: false,
          });
          workerInitProgressBarEl.value = Number(workerInitProgressBarEl.value) + 1;
        }
        console.log("Image model loaded.");

        onnxTextSession = await ort.InferenceSession.create(textModelUrl, { executionProviders: ["wasm"] }); // webgl is not compatible with this model (need to tweak conversion data/op types)
        console.log("Text model loaded.");
        workerInitProgressBarEl.value = Number(workerInitProgressBarEl.value) + 1;

        window.URL.revokeObjectURL(imageModelUrl);
        window.URL.revokeObjectURL(textModelUrl);

        window.vips = await Vips(); // for bicubicly resizing images (since that's what CLIP expects)
        window.vips.EMBIND_AUTOMATIC_DELETELATER = false;

        workerInitProgressBarEl.value = Number(workerInitProgressBarEl.value) + 1;

        disableCtn(initCtnEl);
        enableCtn(pickDirCtnEl);
      }


      /////////////
      //  STEP 2 //
      /////////////
      let directoryHandle;
      let embeddingsFileHandle;
      let embeddings;
      let dataSource;
      async function pickDirectory(opts={}) {
        dataSource = opts.source;
        
        if(dataSource === "local") {
          if(!window.showDirectoryPicker) return alert("Your browser does not support some modern features (specifically, File System Access API) required to use this web app. Please try updating your browser, or switching to Chrome, Edge, or Brave.");
          directoryHandle = await window.showDirectoryPicker();
          embeddingsFileHandle = await directoryHandle.getFileHandle(`${window.MODEL_NAME}_embeddings.tsv`, {create:true});
          
          pickDirectoryBtn.disabled = true;
          useRedditImagesBtn.disabled = true;
          pickDirectoryBtn.textContent = "Loading...";
        }
        
        let redditEmbeddingsBlob;
        if(dataSource === "reddit") {
          if(window.MODEL_NAME !== "clip_vit_32") return alert("Sorry, there are only pre-computed Reddit image embeddings for the CLIP ViT-B/32 model at the moment.");
          if(!removeRedditNsfwEl.checked && !confirm("Are you sure you'd like to see NSFW Reddit images?")) return;
          if(removeRedditNsfwEl.checked) alert("Note that NSFW images are filtered from Reddit using CLIP, and CLIP can make mistakes, so some NSFW images may still be shown.");
            
          pickDirectoryBtn.disabled = true;
          useRedditImagesBtn.disabled = true;
          useRedditImagesBtn.textContent = "Loading...";
          redditLoadProgressCtn.style.display = "";
          
          redditEmbeddingsBlob = await downloadBlobWithProgress("https://huggingface.co/datasets/rocca/top-reddit-posts/resolve/main/clip_embeddings_top_50_images_per_subreddit.tsv.gz", function(e) {
            let ratio = e.loaded / e.total;
            redditProgressBarEl.value = ratio;
            redditProgressMbEl.innerHTML = Math.round(ratio*213)+" MB";
          });
        }
        
        try {
          existingEmbeddingsProgressCtn.style.display = "";
          
          embeddings = {};
          let file, opts;
          if(dataSource === "local") {
            file = await embeddingsFileHandle.getFile();
            opts = {};
          }
          if(dataSource === "reddit") {
            file = redditEmbeddingsBlob;
            opts = {decompress:"gzip"};
          }
          
          let i = 0;
          for await (let line of makeTextFileLineIterator(file, opts)) {
            if(!line || !line.trim()) continue; // <-- to skip final new line (not sure if this is needed)
            let [filePath, embeddingVec] = line.split("\t");
            embeddings[filePath] = JSON.parse(embeddingVec);
            i++;
            if(i % 1000 === 0) {
              existingEmbeddingsLoadedEl.innerHTML = i;
              await sleep(10);
            }
          }
        } catch(e) {
          embeddings = undefined;
          console.log("No existing embedding found, or the embeddings file was corrupted:", e);
          existingEmbeddingsProgressCtn.style.display = "none";
        }
        
        pickDirectoryBtn.textContent = "Done.";
        useRedditImagesBtn.textContent = "Done.";

        disableCtn(pickDirCtnEl);
        enableCtn(computeEmbeddingsCtnEl);
        enableCtn(searchCtnEl);

        if(embeddings && Object.keys(embeddings).length > 0) {
          computeEmbeddingsCtnEl.style.display = "none";
          existingEmbeddingsFoundCtnEl.style.display = "";
        }
        
        if(dataSource === "reddit") {
          disableCtn(existingEmbeddingsFoundCtnEl);
        }
        
      }
      

      /////////////
      //  STEP 3 //
      /////////////
      let totalEmbeddingsCount = 0;
      let imagesEmbedded;
      let recentEmbeddingTimes = []; // how long each embed took in ms, newest at end
      let recomputeAllEmbeddings;
      let imagesBeingProcessedNow = 0;
      let needToSaveEmbeddings = false;
      async function computeImageEmbeddings() {
        imagesEmbedded = 0;
        totalEmbeddingsCount = Object.keys(embeddings).length;

        recomputeAllEmbeddings = !onlyEmbedNewImagesCheckbox.checked;
        let gotSomeExistingEmbeddings = totalEmbeddingsCount > 0;
        
        if(onlyEmbedNewImagesCheckbox.checked && gotSomeExistingEmbeddings) {
          preexistingEmbeddingsEl.innerHTML = `(loaded ${Object.keys(embeddings).length} existing embeddings)`; 
        }

        if(recomputeAllEmbeddings || !gotSomeExistingEmbeddings) {
          embeddings = {}; // <-- maps file path (relative to top/selected directory) to embedding
        }
        
        try {
          await recursivelyProcessImagesInDir(directoryHandle);
          await saveEmbeddings();
        } catch(e) {
          console.error(e);
          alert(e.message);
        }

        disableCtn(computeEmbeddingsCtnEl);
        enableCtn(searchCtnEl);
      }
      async function recursivelyProcessImagesInDir(dirHandle, currentPath="") {
        for await (let [name, handle] of dirHandle) {
          const {kind} = handle;
          let path = `${currentPath}/${name}`;
          if (handle.kind === 'directory') {
            await recursivelyProcessImagesInDir(handle, path);
          } else {
            let isImage = /\.(png|jpg|jpeg|webp)$/.test(path);
            if(!isImage) continue;

            let alreadyGotEmbedding = !!embeddings[path];
            if(alreadyGotEmbedding && !recomputeAllEmbeddings) continue;
            
            if(needToSaveEmbeddings) {
              await saveEmbeddings();
              needToSaveEmbeddings = false;
            }
              
            while(imageWorkers.filter(w => !w.busy).length === 0) await sleep(1);
            
            let worker = imageWorkers.filter(w => !w.busy)[0];
            worker.busy = true;
            imagesBeingProcessedNow++;

            (async function() {
              let startTime = Date.now();
              
              let blob = await handle.getFile();
              const embedVec = await modelData[MODEL_NAME].image.embed(blob, worker.session);

              embeddings[path] = [...embedVec];
              worker.busy = false;

              imagesEmbedded++;
              totalEmbeddingsCount++;
              
              computeEmbeddingsProgressEl.innerHTML = imagesEmbedded;
              
              let saveInterval = totalEmbeddingsCount > 50_000 ? 10_000 : 1000; // since saves take longer if there are lots of embeddings
              if(imagesEmbedded % saveInterval === 0) {
                needToSaveEmbeddings = true;
              }
              
              recentEmbeddingTimes.push(Date.now()-startTime);
              if(recentEmbeddingTimes.length > 100) recentEmbeddingTimes = recentEmbeddingTimes.slice(-50);
              if(recentEmbeddingTimes.length > 10) computeEmbeddingsSpeedEl.innerHTML = Math.round(recentEmbeddingTimes.slice(-20).reduce((a,v) => a+v, 0)/20);

              imagesBeingProcessedNow--;
            })();
          }
        }
        while(imagesBeingProcessedNow > 0) await sleep(10);
      }
      

      /////////////
      //  STEP 4 //
      /////////////
      async function searchSort() {
        searchBtn.disabled = true;
        
        if(dataSource === "local") {
          for(let imgEl of [...document.querySelectorAll("img")]) {
            URL.revokeObjectURL(imgEl.src);
          }
        }
        
        resultsEl.innerHTML = "Loading...";
        await sleep(50);

        let searchTextEmbedding = await modelData[MODEL_NAME].text.embed(searchTextEl.value, onnxTextSession);
        let similarities = {};
        for(let [path, embedding] of Object.entries(embeddings)) {
          similarities[path] = cosineSimilarity(searchTextEmbedding, embedding);
        }
        let similarityEntries = Object.entries(similarities).sort((a,b) => b[1]-a[1]).slice(0, 5000);

        if(dataSource === "reddit" && removeRedditNsfwEl.checked) {
          let nsfwTextEmbedding = await modelData[MODEL_NAME].text.embed(atob('cG9ybiBuYWtlZCBwZW5pcyB2YWdpbmEgbnVkZSBzZXggZGljayBwdXNzeSBzZXh1YWwgcG9ybm9ncmFwaGljIGFzcyBib29icw=='), onnxTextSession); // nsfw words (hidden with `btoa`)
          let nsfwSimilarities = {};
          for(let [path, similarity] of similarityEntries) {
            let embedding = embeddings[path];
            nsfwSimilarities[path] = cosineSimilarity(nsfwTextEmbedding, embedding);
          }
          similarityEntries = similarityEntries.filter(e => nsfwSimilarities[e[0]] < 0.2093);
        }
        
        let resultHtml = "";
        let numResults = 0;
        for(let [path, score] of similarityEntries.slice(0, 500)) {
          if(dataSource === "local") {
            let handle = await getFileHandleByPath(path);
            let url = URL.createObjectURL(await handle.getFile());
            resultHtml += `<img src="${url}" style="max-height:400px;" title="${path}: ${score}" loading="lazy"/>`;
          }
          if(dataSource === "reddit") {
            let imageUrl = `https://i.redd.it/${path.split("__")[1]}`;
            let postUrl = `https://reddit.com/comments/${path.split("__")[0].split("/")[1]}`;
            resultHtml += `<a href="${postUrl}" target="_blank"><img src="${imageUrl}" onload="this.style.height='';this.style.width='';this.style.border='';" style="max-height:400px; height:300px; width:300px; border:1px solid black;" title="${path}: ${score}" loading="lazy"/></a>`;
          }
          numResults++;
        }
        
        if(!resultHtml) {
          resultsEl.innerHTML = "No results found after filtering NSFW.";
        } else {
          resultsEl.innerHTML = resultHtml;
        }
        
        searchBtn.disabled = false;
      }




      /////////////////////////////
      //  FUNCTIONS / UTILITIES  //
      /////////////////////////////

      async function getFileHandleByPath(path) {
        let handle = directoryHandle;
        let chunks = path.split("/").slice(1);
        for(let i = 0; i < chunks.length; i++) {
          let chunk = chunks[i];
          if(i === chunks.length-1) {
            handle = await handle.getFileHandle(chunk);
          } else {
            handle = await handle.getDirectoryHandle(chunk);
          }
        }
        return handle;
      }
      
      async function getRgbData(blob) {
        // let blob = await fetch(imgUrl, {referrer:""}).then(r => r.blob());

        let resizedBlob = await bicubicResizeAndCenterCrop(blob);
        let img = await createImageBitmap(resizedBlob);

        let canvas = new OffscreenCanvas(224, 224);
        let ctx = canvas.getContext("2d");
        ctx.drawImage(img, 0, 0);
        let imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

        let rgbData = [[], [], []]; // [r, g, b]
        // remove alpha and put into correct shape:
        let d = imageData.data;
        for(let i = 0; i < d.length; i += 4) { 
          let x = (i/4) % canvas.width;
          let y = Math.floor((i/4) / canvas.width)
          if(!rgbData[0][y]) rgbData[0][y] = [];
          if(!rgbData[1][y]) rgbData[1][y] = [];
          if(!rgbData[2][y]) rgbData[2][y] = [];
          rgbData[0][y][x] = d[i+0]/255;
          rgbData[1][y][x] = d[i+1]/255;
          rgbData[2][y][x] = d[i+2]/255;
          // From CLIP repo: Normalize(mean=(0.48145466, 0.4578275, 0.40821073), std=(0.26862954, 0.26130258, 0.27577711))
          rgbData[0][y][x] = (rgbData[0][y][x] - 0.48145466) / 0.26862954;
          rgbData[1][y][x] = (rgbData[1][y][x] - 0.4578275) / 0.26130258;
          rgbData[2][y][x] = (rgbData[2][y][x] - 0.40821073) / 0.27577711;
        }
        rgbData = Float32Array.from(rgbData.flat().flat());
        return rgbData;
      }
      
      async function bicubicResizeAndCenterCrop(blob) {
        let im1 = vips.Image.newFromBuffer(await blob.arrayBuffer());

        // Resize so smallest side is 224px:
        const scale = 224 / Math.min(im1.height, im1.width);
        let im2 = im1.resize(scale, { kernel: vips.Kernel.cubic });

        // crop to 224x224:
        let left = (im2.width - 224) / 2;
        let top = (im2.height - 224) / 2;
        let im3 = im2.crop(left, top, 224, 224)

        let outBuffer = new Uint8Array(im3.writeToBuffer('.png'));
        im1.delete(), im2.delete(), im3.delete();
        return new Blob([outBuffer], { type: 'image/png' });
      }


      function downloadBlobWithProgress(url, onProgress) {
        return new Promise((res, rej) => {
          var blob;
          var xhr = new XMLHttpRequest();
          xhr.open('GET', url, true);
          xhr.responseType = 'arraybuffer';
          xhr.onload = function(e) {
            blob = new Blob([this.response]);   
          };
          xhr.onprogress = onProgress;
          xhr.onloadend = function(e){
            res(blob);
          }
          xhr.send();
        });
      }

      async function saveEmbeddings(opts={}) {
        let writable = await embeddingsFileHandle.createWritable();
        let textBatch = "";
        let i = 0;
        for(let [filePath, embeddingVec] of Object.entries(embeddings)) {
          let vecString = opts.compress ? JSON.stringify(embeddingVec.map(n => n.toFixed(3))).replace(/"/g, "") : JSON.stringify(embeddingVec);
          textBatch += `${filePath}\t${vecString}\n`;
          i++;
          if(i % 1000 === 0) {
            await writable.write(textBatch);
            textBatch = "";
          }
        }
        await writable.write(textBatch);
        await writable.close();
      }
      
      // Tweaked version of example from here: https://developer.mozilla.org/en-US/docs/Web/API/ReadableStreamDefaultReader/read
      async function* makeTextFileLineIterator(blob, opts={}) {
        const utf8Decoder = new TextDecoder("utf-8");
        let stream = await blob.stream();
        
        if(opts.decompress === "gzip") stream = stream.pipeThrough(new DecompressionStream("gzip"));
        
        let reader = stream.getReader();
        
        let {value: chunk, done: readerDone} = await reader.read();
        chunk = chunk ? utf8Decoder.decode(chunk, {stream: true}) : "";

        let re = /\r\n|\n|\r/gm;
        let startIndex = 0;

        while (true) {
          let result = re.exec(chunk);
          if (!result) {
            if (readerDone) {
              break;
            }
            let remainder = chunk.substr(startIndex);
            ({value: chunk, done: readerDone} = await reader.read());
            chunk = remainder + (chunk ? utf8Decoder.decode(chunk, {stream: true}) : "");
            startIndex = re.lastIndex = 0;
            continue;
          }
          yield chunk.substring(startIndex, result.index);
          startIndex = re.lastIndex;
        }
        if (startIndex < chunk.length) {
          // last line didn't end in a newline char
          yield chunk.substr(startIndex);
        }
      }

      function cosineSimilarity(A, B) {
        if(A.length !== B.length) throw new Error("A.length !== B.length");
        let dotProduct = 0, mA = 0, mB = 0;
        for(let i = 0; i < A.length; i++){
          dotProduct += A[i] * B[i];
          mA += A[i] * A[i];
          mB += B[i] * B[i];
        }
        mA = Math.sqrt(mA);
        mB = Math.sqrt(mB);
        let similarity = dotProduct / (mA * mB);
        return similarity;
      }

      function sleep(ms) {
        return new Promise(r => setTimeout(r, ms));
      }

      function enableCtn(el) {
        el.style.opacity = 1;
        el.style.pointerEvents = "";
      }
      function disableCtn(el) {
        el.style.opacity = 0.5;
        el.style.pointerEvents = "none";
      }

      // From the PyTorch model running on CUDA:
      // Text: "a portrait of an astronaut with the American flag" 
      // Embedding: [-1.6626e-01,  5.2277e-02, -1.5332e-01,  4.4946e-01,  2.0667e-01, -2.9565e-01,  4.0588e-02, -4.1016e-01, -1.5027e-01,  3.1934e-01, -6.9702e-02, -2.5488e-01,  1.2335e-01, -9.5337e-02,  2.4109e-01, -4.8950e-02,  2.6074e-01,  5.3835e-04,  2.1033e-01,  3.7012e-01, 4.5679e-01,  3.9795e-01,  3.1641e-01,  3.9551e-01,  1.3931e-02, -4.3060e-02,  4.8798e-02,  3.7158e-01,  1.1731e-01, -3.7256e-01, -2.7295e-01,  3.3130e-01,  5.4980e-01, -2.9816e-02, -2.5806e-01, -1.0016e-01,  8.0750e-02, -6.7139e-02, -2.4072e-01,  2.4353e-01, -3.2202e-01, -1.0327e-01,  1.1566e-01,  6.2646e-01,  1.8262e-01, 2.7539e-01, -1.1816e-01,  4.9512e-01,  8.9539e-02,  5.6299e-01, 2.1313e-01, -1.5625e-01,  1.9958e-01, -5.0049e-01, -2.5854e-01, -4.0430e-01, -1.1298e-01, -6.6338e-03,  2.5391e-01, -5.0629e-02, 2.2253e-01, -2.7295e-01, -5.8289e-03, -4.8804e-01, -7.7820e-02, -3.5187e-02, -3.7537e-02,  4.3213e-01,  3.8300e-02,  2.1045e-01, -3.0347e-01, -9.8999e-02, -1.7407e-01,  2.8882e-01,  1.1322e-01, -1.0883e-01,  1.7065e-01, -2.1191e-01,  1.7920e-01, -1.2805e-01, -4.6924e-01,  1.1957e-01, -1.1829e-01, -1.1902e-01, -2.4353e-01, -9.6008e-02,  2.2913e-01, -1.0948e-02, -1.5686e-01, -2.0483e-01, -2.4756e-01,  9.1125e-02, -9.5557e-01, -4.2511e-02,  4.6356e-02, 4.3481e-01,  2.3633e-01, -3.3252e-01,  3.7231e-01, -5.5695e-02, 7.1777e-02, -1.0370e-01, -2.1912e-01, -1.3733e-01,  1.2048e-01, 1.7151e-01, -1.2659e-01,  2.3523e-01,  2.6001e-01, -4.0381e-01, 1.1761e-01, -4.1626e-02,  1.0974e-01, -5.5206e-02,  4.9713e-02, 5.2197e-01,  3.9124e-02,  5.7959e-01,  9.9609e-02, -3.3740e-01, -2.7295e-01, -7.3389e-01,  1.0962e-01, -3.2178e-01,  6.5869e-01, 2.3460e-03,  2.6733e-02,  3.2471e-02, -2.4500e-01,  7.9041e-02, 1.5405e-01, -3.5547e-01, -1.5625e-01,  4.2695e+00, -1.6113e-01, 1.6467e-01, -3.8794e-01,  2.1545e-02,  1.5771e-01,  2.0068e-01, -3.4741e-01,  2.5244e-01,  1.2201e-01, -3.9795e-02,  3.2471e-01, 2.6562e-01,  1.2915e-01,  1.4465e-02, -2.1265e-01, -2.5055e-02, 5.6689e-01, -6.5125e-02,  1.1652e-01, -5.1025e-01,  1.0712e-01, 8.8867e-02,  1.6882e-01, -6.5125e-02,  4.5929e-02,  2.9517e-01, 6.5479e-01, -9.0881e-02, -4.6417e-02, -3.0713e-01, -5.1537e-03, 4.9390e-01,  5.4492e-01, -3.1812e-01, -6.0577e-02,  3.6591e-02, 7.6782e-02, -3.5181e-01,  4.9487e-01, -4.1040e-01,  4.3970e-01, 1.6553e-01, -3.7329e-01,  3.3594e-01, -1.9263e-01, -1.8225e-01, -1.9623e-02, -4.0454e-01,  1.6187e-01,  1.5259e-01,  2.5122e-01, 1.1993e-01, -8.4595e-02, -4.1016e-01, -1.8225e-01,  1.8555e-01, -3.9124e-02,  2.5122e-01, -2.2949e-01,  5.3125e-01, -1.0504e-01, -2.1439e-02, -2.2559e-01,  5.9357e-02, -3.9160e-01, -3.3716e-01, -9.0393e-02, -1.7493e-01, -2.5952e-01,  2.3401e-01,  3.8013e-01, 1.2927e-01,  1.5491e-01,  1.1920e-01, -1.5906e-01,  5.7487e-03, 7.6172e-02,  1.5552e-01,  2.1790e-01,  9.9304e-02, -3.8025e-02, -1.1829e-01, -1.3293e-01, -2.2278e-01, -2.1472e-01,  3.0957e-01, -1.0254e-01, -2.0264e-01, -2.6840e-02,  8.8379e-02, -8.2092e-02, 1.3647e-01, -2.1399e-01, -2.5684e-01,  1.3745e-01,  6.1371e-02, -1.2988e-01,  6.2683e-02,  1.2964e-01, -3.3112e-02,  1.4111e-01, -2.6440e-01,  4.7379e-03, -1.0815e-01, -4.4971e-01, -3.5583e-02, 1.1469e-01,  6.7871e-02, -5.8350e-02,  1.0297e-01, -6.3086e-01, -8.3350e-01,  4.3481e-01, -1.7383e-01, -1.5491e-01, -5.5176e-01, 5.9766e-01, -2.6880e-01,  5.6976e-02, -2.6318e-01, -4.0466e-02, 2.4927e-01, -1.4893e-01, -2.0032e-01, -2.7515e-01, -1.2598e-01, 3.2440e-02, -1.2939e-01,  6.8018e-01, -3.6060e-01, -3.3496e-01, 9.8267e-02, -1.0010e-01,  1.9653e-01, -3.3032e-01, -2.0032e-01, 1.9116e-01,  8.2214e-02,  3.2397e-01,  1.3708e-01,  3.0899e-02, 1.5454e-01,  3.2422e-01,  1.0693e-01,  3.1714e-01,  3.7280e-01, -2.3401e-01, -5.0171e-02,  7.6758e-01,  2.2046e-01,  3.3997e-02, 1.0231e-02, -2.3999e-01, -1.3672e-01,  5.2002e-01, -6.5552e-02, 6.9275e-02,  2.3706e-01, -3.8257e-01,  1.4990e-01, -2.2656e-01, 4.3018e-01, -4.4678e-01,  2.5977e-01,  3.8208e-01,  9.5215e-02, -2.0239e-01, -2.3169e-01, -3.1396e-01,  3.2806e-02, -2.7905e-01, -1.0361e+00,  3.8147e-02, -1.0278e-01,  2.8369e-01, -3.8623e-01, -2.3132e-01,  1.5784e-01,  4.2734e+00, -1.5820e-01, -1.4758e-01, 2.0032e-01, -1.9678e-01, -7.5586e-01,  1.0712e-01, -2.1777e-01, -4.0552e-01, -1.0919e-01,  1.1932e-01,  7.3486e-01, -1.7700e-01, 5.0732e-01, -9.7351e-02, -4.7192e-01,  5.9052e-02, -7.0117e-01, -1.8774e-01,  2.4329e-01,  3.5083e-01, -2.3633e-01,  2.2205e-01, -2.4719e-03,  4.4507e-01, -1.1005e-01,  5.6494e-01, -1.4697e-01, -8.5022e-02, -2.6050e-01, -8.3679e-02,  3.0615e-01,  1.0181e-01, -2.2266e-01, -1.2054e-01,  1.0094e-02, -1.6382e-01,  3.7671e-01, 1.1371e-01,  8.8959e-03, -1.2866e-01,  7.5500e-02, -3.1177e-01, 9.0698e-02,  2.4139e-02,  2.7124e-01,  4.1382e-01,  9.3872e-02, -3.5815e-01, -1.0602e-01, -2.7637e-01,  1.5613e-01,  2.6025e-01, -1.3428e-01, -2.1509e-01, -3.0005e-01,  7.7515e-02, -2.2253e-01, -1.2634e-01,  1.0114e-01,  2.9395e-01,  4.2065e-01, -4.6425e-03, -6.3721e-01, -4.0308e-01, -5.1849e-02, -9.1309e-02,  1.0577e-01, -1.6800e-02, -4.4823e-03,  2.4231e-01, -1.3635e-01,  1.7041e-01, -9.9243e-02, -1.2439e-01,  1.5247e-01,  1.4717e-02, -1.6785e-01, -3.0615e-01,  2.6074e-01,  1.0938e-01,  4.9487e-01,  1.0529e-01, 3.1799e-02,  7.5928e-02, -1.1212e-01, -3.1201e-01,  5.8740e-01, -1.3171e-01, -1.1090e-01,  5.8887e-01, -1.1420e-01, -2.0056e-01, 1.0425e-01,  2.7710e-01, -5.8098e-03,  5.7324e-01, -1.4417e-01, 1.4575e-01, -2.7466e-01, -2.1313e-01, -1.7627e-01,  1.5466e-01, 3.8013e-01, -1.4612e-01, -2.7246e-01, -1.8604e-01,  1.0394e-01, 1.6016e-01, -1.1017e-01,  1.8140e-01, -3.0078e-01,  6.0303e-01, -1.3904e-01,  1.7322e-01,  2.2510e-01,  2.3303e-01, -5.0879e-01, -2.3462e-01, -2.0544e-01, -2.4768e-01, -2.4121e-01, -7.2754e-01, 7.2754e-01, -4.4312e-02, -1.4198e-02, -1.1475e-01, -1.3684e-01, -3.5278e-01,  1.2347e-01, -2.9602e-02,  4.0550e-03,  1.1951e-01, -6.5575e-03, -7.1228e-02, -3.8062e-01,  6.5125e-02, -1.6541e-01, -3.0289e-02,  8.6609e-02, -1.2134e-01, -1.2164e-01,  3.0319e-02, -1.5173e-01, -7.9834e-02,  1.4148e-01,  2.7319e-01, -2.1545e-01, -1.6382e-01, -2.9419e-01, -2.6611e-01, -7.5102e-04,  1.3135e-01, 9.8389e-02,  3.1812e-01,  5.5115e-02, -5.3253e-02,  4.3823e-02, 3.6957e-02, -1.3599e-01,  1.1023e-01,  9.8267e-02,  2.1643e-01, 9.3567e-02,  1.2718e-02,  1.6406e-01, -1.0338e-02,  1.9019e-01, 1.4392e-01,  3.3081e-02,  1.0138e-01, -1.6943e-01,  8.6136e-03, 1.4478e-01,  1.0941e-02,  1.3635e-01, -8.1543e-01, -3.4912e-01, 7.4959e-03,  2.1997e-01, -2.5681e-02,  2.3206e-01,  3.7622e-01, 3.6401e-01, -1.6357e-01, -2.0984e-01, -1.3220e-01, -6.7322e-02, 2.0117e-01, -4.7583e-01,  6.8054e-02,  2.2437e-01,  2.6709e-01, -5.4626e-02, -4.0741e-02,  5.2002e-02, -1.8872e-01,  3.1372e-01, -1.3574e-01, -2.6538e-01];
    </script>
  </body>
</html>