| 1 | import path from "node:path"; |
| 2 | import { parentPort } from "node:worker_threads"; |
| 3 | |
| 4 | import { |
| 5 | env, |
| 6 | pipeline, |
| 7 | } from "../../vendor/node_modules/@xenova/transformers/types/transformers"; |
| 8 | |
| 9 | import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider"; |
| 10 | |
| 11 | env.allowLocalModels = true; |
| 12 | env.allowRemoteModels = false; |
| 13 | if (typeof window === "undefined") { |
| 14 | // The embeddings provider should just never be called in the browser |
| 15 | env.localModelPath = path.join(__dirname, "..", "models"); |
| 16 | } |
| 17 | |
| 18 | class EmbeddingsPipeline { |
| 19 | static task = "feature-extraction"; |
| 20 | static model = TransformersJsEmbeddingsProvider.ModelName; |
| 21 | static instance = null; |
| 22 | |
| 23 | static async getInstance() { |
| 24 | if (EmbeddingsPipeline.instance === null) { |
| 25 | EmbeddingsPipeline.instance = await pipeline( |
| 26 | EmbeddingsPipeline.task, |
| 27 | EmbeddingsPipeline.model, |
| 28 | ); |
| 29 | } |
| 30 | |
| 31 | return EmbeddingsPipeline.instance; |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | parentPort.on("message", async (chunks) => { |
| 36 | try { |
| 37 | const extractor = await EmbeddingsPipeline.getInstance(); |
| 38 | |
| 39 | if (!extractor) { |
| 40 | throw new Error("TransformerJS embeddings pipeline is not initialized"); |
| 41 | } |
| 42 | |
| 43 | const outputs = []; |
| 44 | for ( |
| 45 | let i = 0; |
| 46 | i < chunks.length; |
| 47 | i += TransformersJsEmbeddingsProvider.maxGroupSize |
| 48 | ) { |
| 49 | const chunkGroup = chunks.slice( |
| 50 | i, |
| 51 | i + TransformersJsEmbeddingsProvider.maxGroupSize, |
| 52 | ); |
| 53 | const output = await extractor(chunkGroup, { |
| 54 | pooling: "mean", |
| 55 | normalize: true, |
| 56 | }); |
| 57 | outputs.push(...output.tolist()); |
| 58 | } |
| 59 | |
| 60 | parentPort.postMessage(outputs); |
| 61 | } catch (error) { |
| 62 | parentPort.postMessage({ error: error.message }); |
| 63 | } |
| 64 | }); |