Download engine-worker.js from budijuarto/chat-pgvector-cloud-services: direct link, hf CLI and curl.
- Browser
- Download file 5.05 kB
-
https://huggingface.co/spaces/budijuarto/chat-pgvector-cloud-services/resolve/main/engine-worker.js
- Command line
-
hf download hf://spaces/budijuarto/chat-pgvector-cloud-services/engine-worker.js
-
curl -L -o engine-worker.js https://huggingface.co/spaces/budijuarto/chat-pgvector-cloud-services/resolve/main/engine-worker.js
5.05 kB
| const dimensions = 384; | |
| const model = 'Xenova/paraphrase-multilingual-MiniLM-L12-v2'; | |
| const modelRevision = '2c4055b12046f11709e9df2c122e59ffbdc2f900'; | |
| const pgliteUrl = 'https://cdn.jsdelivr.net/npm/@electric-sql/pglite@0.3.15/dist/'; | |
| const transformersUrl = 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@4.3.2/dist/transformers.min.js'; | |
| let databasePromise; | |
| let extractorPromise; | |
| const downloadListeners = new Set(); | |
| function vectorLiteral(values) { | |
| if (!Array.isArray(values) || values.length !== dimensions | |
| || !values.every(value => typeof value === 'number' && Number.isFinite(Math.fround(value))) | |
| || !values.some(value => Math.fround(value) !== 0)) { | |
| throw new Error('Embedding harus berisi 384 angka hingga dan memiliki setidaknya satu angka bukan nol.'); | |
| } | |
| return JSON.stringify(values); | |
| } | |
| async function openDatabase() { | |
| const [response, { PGlite }, { vector }] = await Promise.all([ | |
| fetch(new URL('./data.json', import.meta.url)), | |
| import(`${pgliteUrl}index.js`), | |
| import(`${pgliteUrl}vector/index.js`), | |
| ]); | |
| if (!response.ok) throw new Error(`Gagal memuat data latihan (HTTP ${response.status}).`); | |
| const { documents, presets } = await response.json(); | |
| const database = await PGlite.create({ extensions: { vector } }); | |
| try { | |
| await database.exec(` | |
| CREATE EXTENSION vector; | |
| CREATE TABLE documents ( | |
| id text PRIMARY KEY, | |
| title text NOT NULL, | |
| body text NOT NULL, | |
| topic text NOT NULL, | |
| embedding vector(384) NOT NULL | |
| ); | |
| `); | |
| await database.transaction(async tx => { | |
| for (const { id, title, body, topic, embedding } of documents) { | |
| await tx.query( | |
| 'INSERT INTO documents (id, title, body, topic, embedding) VALUES ($1, $2, $3, $4, $5::vector)', | |
| [id, title, body, topic, vectorLiteral(embedding)], | |
| ); | |
| } | |
| }); | |
| const { rows: [{ extversion }] } = await database.query( | |
| 'SELECT extversion FROM pg_extension WHERE extname = $1', | |
| ['vector'], | |
| ); | |
| return { | |
| database, | |
| extversion, | |
| count: documents.length, | |
| presets: new Map(presets.map(({ query, embedding }) => [query.trim(), embedding])), | |
| }; | |
| } catch (error) { | |
| await database.close(); | |
| throw error; | |
| } | |
| } | |
| function getDatabase() { | |
| databasePromise ??= openDatabase().catch(error => { | |
| databasePromise = undefined; | |
| throw error; | |
| }); | |
| return databasePromise; | |
| } | |
| async function loadExtractor() { | |
| const { env, pipeline } = await import(transformersUrl); | |
| env.allowLocalModels = false; | |
| env.useBrowserCache = true; | |
| env.backends.onnx.wasm.numThreads = 1; | |
| env.backends.onnx.wasm.proxy = false; | |
| let lastReported = -1; | |
| return pipeline('feature-extraction', model, { | |
| revision: modelRevision, | |
| device: 'wasm', | |
| dtype: 'q8', | |
| progress_callback(event) { | |
| if (event.status !== 'progress' || event.file !== 'onnx/model_quantized.onnx') return; | |
| const percent = Math.floor(event.progress); | |
| if (percent < lastReported + 5 && percent !== 100) return; | |
| lastReported = percent; | |
| for (const notify of downloadListeners) notify(`Mengunduh model embedding… ${percent}%`); | |
| }, | |
| }); | |
| } | |
| async function embed(query, notify) { | |
| notify('Menyiapkan model embedding. Unduhan pertama sekitar 135 MB untuk model dan tokenizer.'); | |
| downloadListeners.add(notify); | |
| try { | |
| extractorPromise ??= loadExtractor().catch(error => { | |
| extractorPromise = undefined; | |
| throw error; | |
| }); | |
| const extractor = await extractorPromise; | |
| notify('Mengubah pertanyaan menjadi embedding…'); | |
| const vector = await extractor(query, { pooling: 'mean', normalize: true }); | |
| return vector.tolist()[0]; | |
| } finally { | |
| downloadListeners.delete(notify); | |
| } | |
| } | |
| async function search({ database, presets }, query, notify) { | |
| if (typeof query !== 'string' || !query.trim() || query.length > 600) { | |
| throw new Error('Masukkan pertanyaan sepanjang 1–600 karakter.'); | |
| } | |
| const question = query.trim(); | |
| const preset = presets.has(question); | |
| const embedding = preset ? presets.get(question) : await embed(question, notify); | |
| const { rows } = await database.query(` | |
| SELECT id, title, body, topic, embedding <=> $1::vector AS distance | |
| FROM documents | |
| ORDER BY distance, id | |
| LIMIT $2::integer | |
| `, [vectorLiteral(embedding), 3]); | |
| return { rows, preset }; | |
| } | |
| self.addEventListener('message', async ({ data: { id, type, query } }) => { | |
| const notify = message => self.postMessage({ id, type: 'progress', message }); | |
| try { | |
| if (type !== 'init' && type !== 'search') throw new Error('Perintah tidak dikenal.'); | |
| if (type === 'init') notify('Menyiapkan PostgreSQL dan pgvector…'); | |
| const state = await getDatabase(); | |
| const data = type === 'init' | |
| ? { extversion: state.extversion, count: state.count } | |
| : await search(state, query, notify); | |
| self.postMessage({ id, type: 'done', data }); | |
| } catch (error) { | |
| self.postMessage({ id, type: 'error', message: error.message }); | |
| } | |
| }); | |