File size: 2,165 Bytes
16f1f6d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
//load Candle Bert Module wasm module
import init, { Model } from "./build/m.js";

async function fetchArrayBuffer(url, cacheFile = true) {
  if (!cacheFile) return new Uint8Array(await (await fetch(url)).arrayBuffer());
  const cacheName = "blip-candle-cache";
  const cache = await caches.open(cacheName);
  const cachedResponse = await cache.match(url);
  if (cachedResponse) {
    const data = await cachedResponse.arrayBuffer();
    return new Uint8Array(data);
  }
  const res = await fetch(url, { cache: "force-cache" });
  cache.put(url, res.clone());
  return new Uint8Array(await res.arrayBuffer());
}
class Blip {
  static instance = {};

  static async getInstance(
    weightsURL,
    tokenizerURL,
    configURL,
    modelID,
    quantized
  ) {
    if (!this.instance[modelID]) {
      await init();

      self.postMessage({ status: "loading", message: "Loading Model" });
      const [weightsArrayU8, tokenizerArrayU8, configArrayU8] =
        await Promise.all([
          fetchArrayBuffer(weightsURL),
          fetchArrayBuffer(tokenizerURL),
          fetchArrayBuffer(configURL),
        ]);

      this.instance[modelID] = new Model(
        weightsArrayU8,
        tokenizerArrayU8,
        configArrayU8,
        quantized
      );
    } else {
      self.postMessage({ status: "ready", message: "Model Already Loaded" });
    }
    return this.instance[modelID];
  }
}

self.addEventListener("message", async (event) => {
  const { weightsURL, tokenizerURL, configURL, modelID, imageURL, quantized } =
    event.data;
  try {
    self.postMessage({ status: "status", message: "Loading Blip Model..." });
    const model = await Blip.getInstance(
      weightsURL,
      tokenizerURL,
      configURL,
      modelID,
      quantized
    );
    self.postMessage({
      status: "status",
      message: "Running Blip Inference...",
    });
    const imageArrayU8 = await fetchArrayBuffer(imageURL, false);
    const output = model.generate_caption_from_image(imageArrayU8);

    self.postMessage({
      status: "complete",
      message: "complete",
      output: output,
    });
  } catch (e) {
    self.postMessage({ error: e });
  }
});