Spaces:
Running
Running
Download source/src/main.js from Segizu/buscador-visual: direct link, hf CLI and curl.
- Browser
- Download file 10.1 kB
-
https://huggingface.co/spaces/Segizu/buscador-visual/resolve/main/source/src/main.js
- Command line
-
hf download hf://spaces/Segizu/buscador-visual/source/src/main.js
-
curl -L -o main.js https://huggingface.co/spaces/Segizu/buscador-visual/resolve/main/source/src/main.js
10.1 kB
| import { GALLERY, EXAMPLES, MAX_IMAGES, MAX_IMAGE_BYTES, THUMB_SIDE, TOP_K, DOWNLOAD_MB } from './config.js'; | |
| import { rank, relativeBars, normRect, fitSize } from './lib.js'; | |
| const $ = (id) => document.getElementById(id); | |
| const wasmBase = new URL('./wasm/', location.href).href; | |
| let worker = null, ready = false, device = null; | |
| let seq = 0; const pending = new Map(); | |
| let queue = Promise.resolve(); // una inferencia a la vez | |
| let items = []; // {name, url, objectUrl, vec} | |
| let regionItem = null, regionRect = null; | |
| function makeWorker() { | |
| worker = new Worker(new URL('./worker.js', import.meta.url), { type: 'module' }); | |
| worker.onmessage = onMsg; | |
| } | |
| function call(msg, transfer = []) { | |
| const id = ++seq; | |
| const p = new Promise((resolve, reject) => pending.set(id, { resolve, reject })); | |
| queue = queue.then(() => { worker.postMessage({ ...msg, id }, transfer); return p.catch(() => {}); }); | |
| return p; | |
| } | |
| const files = {}; | |
| function onMsg(ev) { | |
| const m = ev.data; | |
| if (m.type === 'progress') { | |
| if (m.data.file && m.data.total) { files[m.data.file] = [m.data.loaded || 0, m.data.total]; } | |
| const tot = Object.values(files).reduce((a, [l, t]) => [a[0] + l, a[1] + t], [0, 0]); | |
| if (tot[1]) { $('load-progress').value = (100 * tot[0]) / tot[1]; $('model-status').textContent = `Descargando… ${(tot[0] / 2 ** 20).toFixed(0)} / ${(tot[1] / 2 ** 20).toFixed(0)} MiB`; } | |
| } else if (m.type === 'ready') { | |
| ready = true; device = m.device; | |
| $('load-progress').hidden = true; | |
| $('model-status').textContent = `Modelo listo (${m.device === 'webgpu' ? 'WebGPU' : `WASM, ${m.threads} hilo(s)`}).`; | |
| ['gallery-btn', 'files'].forEach((i) => ($(i).disabled = false)); | |
| } else if (m.type === 'webgpu-failed') { | |
| worker.terminate(); makeWorker(); | |
| $('model-status').textContent = 'WebGPU no disponible; cargando en WASM…'; | |
| worker.postMessage({ type: 'load', wantWebGPU: false, wasmBase }); | |
| } else if (m.type === 'vector') { | |
| pending.get(m.id)?.resolve(m); pending.delete(m.id); | |
| } else if (m.type === 'error') { | |
| if (m.stage === 'load') { $('model-status').textContent = 'Error al cargar: ' + m.message; $('load-btn').disabled = false; } | |
| const p = pending.get(m.id); if (p) { p.reject(new Error(m.message)); pending.delete(m.id); } | |
| } | |
| } | |
| $('load-btn').onclick = () => { | |
| $('load-btn').disabled = true; $('load-progress').hidden = false; | |
| $('model-status').textContent = `Descargando modelo (~${DOWNLOAD_MB} MiB la primera vez)…`; | |
| makeWorker(); | |
| worker.postMessage({ type: 'load', wantWebGPU: $('webgpu-chk').checked && !!navigator.gpu, wasmBase }); | |
| }; | |
| function loadImg(url) { | |
| return new Promise((res, rej) => { const im = new Image(); if (!url.startsWith('blob:')) im.crossOrigin = 'anonymous'; // ficheros LFS del Space redirigen a la CDN (con CORS) | |
| im.onload = () => res(im); im.onerror = () => rej(new Error('No se pudo leer la imagen')); im.src = url; }); | |
| } | |
| function pixels(img, rect = [0, 0, 1, 1]) { | |
| const sx = rect[0] * img.naturalWidth, sy = rect[1] * img.naturalHeight; | |
| const sw = Math.max(1, (rect[2] - rect[0]) * img.naturalWidth), sh = Math.max(1, (rect[3] - rect[1]) * img.naturalHeight); | |
| const [w, h] = fitSize(sw, sh, THUMB_SIDE); | |
| const c = new OffscreenCanvas(w, h); const ctx = c.getContext('2d'); | |
| ctx.drawImage(img, sx, sy, sw, sh, 0, 0, w, h); | |
| const d = ctx.getImageData(0, 0, w, h); | |
| return { width: w, height: h, buffer: d.data.buffer }; | |
| } | |
| async function embedImg(img, rect) { const px = pixels(img, rect); return call({ type: 'image', ...px }, [px.buffer]); } | |
| function renderGrid() { | |
| const g = $('grid'); g.innerHTML = ''; | |
| items.forEach((it, i) => { | |
| const d = document.createElement('div'); d.className = 'tile' + (it.vec ? '' : ' pending'); | |
| d.innerHTML = `<img alt="" loading="lazy"><div class="name"></div><div class="acts"><button data-sim="${i}">Parecidas</button><button data-reg="${i}">Región</button></div>`; | |
| d.querySelector('img').src = it.url; d.querySelector('.name').textContent = it.name; | |
| d.querySelectorAll('button').forEach((b) => (b.disabled = !it.vec)); | |
| g.appendChild(d); | |
| }); | |
| } | |
| $('grid').onclick = (e) => { | |
| const b = e.target.closest('button'); if (!b) return; | |
| if (b.dataset.sim) searchByImage(+b.dataset.sim); else openRegion(+b.dataset.reg); | |
| }; | |
| async function buildIndex(list) { | |
| items.forEach((it) => it.objectUrl && URL.revokeObjectURL(it.url)); | |
| items = list; renderGrid(); setSearchEnabled(false); | |
| const pr = $('index-progress'); pr.hidden = false; pr.value = 0; | |
| const t0 = performance.now(); let ok = 0, fail = 0; | |
| for (let i = 0; i < items.length; i++) { | |
| try { const img = await loadImg(items[i].url); const r = await embedImg(img); items[i].vec = r.vec; ok++; } | |
| catch (e) { fail++; console.warn(items[i].name, e); } | |
| pr.value = (100 * (i + 1)) / items.length; | |
| $('index-status').textContent = `Indexando ${i + 1}/${items.length}…`; | |
| } | |
| const ms = performance.now() - t0; | |
| pr.hidden = true; renderGrid(); setSearchEnabled(ok > 0); | |
| $('index-status').textContent = `Índice listo: ${ok} foto(s)${fail ? `, ${fail} con error` : ''} en ${(ms / 1000).toFixed(1)} s (${(ms / Math.max(1, ok)).toFixed(0)} ms/foto, ${device}).`; | |
| $('index-status').dataset.ready = '1'; $('index-status').dataset.msPerImage = (ms / Math.max(1, ok)).toFixed(0); | |
| } | |
| function setSearchEnabled(on) { ['query', 'search-btn'].forEach((i) => ($(i).disabled = !on)); document.querySelectorAll('#examples button').forEach((b) => (b.disabled = !on || !isGallery())); } | |
| const isGallery = () => items.length === GALLERY.length && items.every((it, i) => it.name === GALLERY[i]); | |
| $('gallery-btn').onclick = () => buildIndex(GALLERY.map((f) => ({ name: f, url: `./examples/${f}` }))); | |
| $('files').onchange = (e) => { | |
| const fl = [...e.target.files].filter((f) => /^image\/(jpeg|png|webp)$/.test(f.type) && f.size <= MAX_IMAGE_BYTES).slice(0, MAX_IMAGES); | |
| const skipped = e.target.files.length - fl.length; | |
| if (!fl.length) { $('index-status').textContent = 'Ningún archivo válido.'; return; } | |
| buildIndex(fl.map((f) => ({ name: f.name, url: URL.createObjectURL(f), objectUrl: true }))); | |
| if (skipped) setTimeout(() => ($('index-status').textContent += ` (${skipped} archivo(s) omitidos por tipo/tamaño/límite)`), 0); | |
| }; | |
| function showResults(kind, label, res, ms, exampleId = '', excludeName = '') { | |
| const ol = $('results'); ol.innerHTML = ''; | |
| for (const r of relativeBars(res)) { | |
| const it = items[r.index]; const li = document.createElement('li'); | |
| li.innerHTML = `<img alt=""><div class="bar"></div><div class="meta"><b></b><br><span></span></div>`; | |
| li.querySelector('img').src = it.url; li.querySelector('.bar').style.width = `${Math.max(4, r.bar * 100)}%`; | |
| li.querySelector('b').textContent = `sim ${r.score.toFixed(3)}`; li.querySelector('span').textContent = it.name; | |
| ol.appendChild(li); | |
| } | |
| $('summary').textContent = `${kind}: ${label} · consulta ${ms.toFixed(0)} ms (${device}) · ${items.length} fotos en el índice`; | |
| ol.dataset.status = 'ok'; ol.dataset.exampleId = exampleId; ol.dataset.ms = ms.toFixed(0); | |
| ol.dataset.top = JSON.stringify(res.map((r) => [items[r.index].name, +r.score.toFixed(4)])); | |
| } | |
| function fail(e) { $('results').dataset.status = 'error'; $('summary').textContent = 'Error: ' + e.message; } | |
| async function searchText(text, exampleId = '') { | |
| text = text.trim().slice(0, 200); if (!text) return; | |
| $('results').dataset.status = 'busy'; | |
| try { const r = await call({ type: 'text', text }); showResults('Texto', `«${text}»`, rank(r.vec, items.map((i) => i.vec), TOP_K), r.ms, exampleId); } | |
| catch (e) { fail(e); } | |
| } | |
| function searchByImage(i) { | |
| const t0 = performance.now(); | |
| showResults('Imagen', items[i].name, rank(items[i].vec, items.map((x) => x.vec), TOP_K, i), performance.now() - t0); | |
| } | |
| $('search-btn').onclick = () => searchText($('query').value); | |
| $('query').onkeydown = (e) => { if (e.key === 'Enter') searchText($('query').value); }; | |
| // Región | |
| const rc = $('region-canvas'); let regionImg = null, drag = null; | |
| function drawRegion() { | |
| const ctx = rc.getContext('2d'); ctx.drawImage(regionImg, 0, 0, rc.width, rc.height); | |
| if (regionRect) { const [a, b, c, d] = regionRect; ctx.lineWidth = 3; ctx.strokeStyle = '#f59e0b'; ctx.strokeRect(a * rc.width, b * rc.height, (c - a) * rc.width, (d - b) * rc.height); } | |
| } | |
| async function openRegion(i, rect = null) { | |
| regionItem = i; regionImg = await loadImg(items[i].url); | |
| const [w, h] = fitSize(regionImg.naturalWidth, regionImg.naturalHeight, 640); rc.width = w; rc.height = h; | |
| regionRect = rect; $('region-box').hidden = false; $('region-search').disabled = !rect; drawRegion(); | |
| } | |
| const pos = (e) => { const b = rc.getBoundingClientRect(); return [(e.clientX - b.left) / b.width, (e.clientY - b.top) / b.height]; }; | |
| rc.onpointerdown = (e) => { drag = pos(e); rc.setPointerCapture(e.pointerId); }; | |
| rc.onpointermove = (e) => { if (!drag) return; const p = pos(e); regionRect = normRect(drag[0], drag[1], p[0], p[1]); drawRegion(); }; | |
| rc.onpointerup = () => { drag = null; const ok = regionRect && regionRect[2] - regionRect[0] > 0.03 && regionRect[3] - regionRect[1] > 0.03; $('region-search').disabled = !ok; }; | |
| $('region-close').onclick = () => { $('region-box').hidden = true; }; | |
| async function searchRegion(exampleId = '') { | |
| $('results').dataset.status = 'busy'; | |
| try { | |
| const r = await embedImg(regionImg, regionRect); | |
| showResults('Región', `${items[regionItem].name} [${regionRect.map((v) => v.toFixed(2)).join(', ')}]`, rank(r.vec, items.map((x) => x.vec), TOP_K), r.ms, exampleId); | |
| } catch (e) { fail(e); } | |
| } | |
| $('region-search').onclick = () => searchRegion(); | |
| // Ejemplos | |
| for (const ex of EXAMPLES) { | |
| const b = document.createElement('button'); b.textContent = ex.label; b.dataset.example = ex.id; b.disabled = true; | |
| b.onclick = async () => { | |
| if (ex.kind === 'text') { $('query').value = ex.query; await searchText(ex.query, ex.id); } | |
| else { await openRegion(GALLERY.indexOf(ex.image), ex.box); $('region-search').disabled = false; await searchRegion(ex.id); } | |
| }; | |
| $('examples').appendChild(b); | |
| } | |