import * as ort from 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/ort.wasm.min.mjs'; import * as N from './nucleo.js'; import { iniciarVisor, mostrarNube } from './visor.js'; // Pesos fijados por commit: onnx-community/depth-anything-v3-small @ 0b6a7f3bf5595f9950b91389e0da3a0de130324c const REV = '0b6a7f3bf5595f9950b91389e0da3a0de130324c'; const BASE = `https://huggingface.co/onnx-community/depth-anything-v3-small/resolve/${REV}/onnx/`; ort.env.wasm.wasmPaths = 'https://cdn.jsdelivr.net/npm/onnxruntime-web@1.31.1/dist/'; ort.env.wasm.numThreads = self.crossOriginIsolated ? Math.min(4, navigator.hardwareConcurrency || 1) : 1; ort.env.logLevel = 'error'; const $ = (id) => document.getElementById(id); const estado = (t) => { $('estado').textContent = t; }; const MAX_VISTAS = 3, MIN_VISTAS = 2, MAX_BYTES = 20 * 1024 * 1024, MAX_MP = 40e6; let ses = null, imagenes = [], verdad = null, ultimo = null, ocupado = false, verdadTodo = null; async function descargar(url, nombre) { const cache = 'caches' in self ? await caches.open('da3-multivista-v1') : null; const r = cache && (await cache.match(url)); if (r) return new Uint8Array(await r.arrayBuffer()); const resp = await fetch(url); if (!resp.ok) throw new Error(`${nombre}: HTTP ${resp.status}`); const total = +resp.headers.get('content-length') || 0, lector = resp.body.getReader(), partes = []; let n = 0; for (;;) { const { done, value } = await lector.read(); if (done) break; partes.push(value); n += value.length; estado(`Descargando ${nombre}: ${(n / 1e6).toFixed(1)}${total ? ' / ' + (total / 1e6).toFixed(1) : ''} MB`); } const blob = new Blob(partes); if (cache) { try { await cache.put(url, new Response(blob)); } catch (e) { console.warn('No se pudo guardar en caché', e); } } return new Uint8Array(await blob.arrayBuffer()); } async function iniciar() { try { const t = performance.now(); const grafo = await descargar(BASE + 'model.onnx', 'grafo ONNX'); const pesos = await descargar(BASE + 'model.onnx_data', 'pesos DA3-Small (≈105 MB)'); estado('Creando sesión WASM…'); ses = await ort.InferenceSession.create(grafo, { executionProviders: ['wasm'], externalData: [{ path: 'model.onnx_data', data: pesos }] }); estado(`Modelo listo en ${((performance.now() - t) / 1000).toFixed(1)} s (WASM, ${ort.env.wasm.numThreads} hilo/s). Elige un ejemplo o sube 2–3 fotos.`); actualizarBoton(); if (imagenes.length >= MIN_VISTAS && $('ejecutar').dataset.auto === '1') ejecutar(); } catch (e) { estado('Error cargando el modelo: ' + e.message); console.error(e); } } const cargarImagen = (src) => new Promise((ok, mal) => { const im = new Image(); im.onload = () => ok(im); im.onerror = () => mal(new Error('No se pudo leer la imagen')); im.src = src; }); function actualizarBoton() { $('ejecutar').disabled = !ses || ocupado || imagenes.length < MIN_VISTAS; } function miniaturas() { const c = $('miniaturas'); c.innerHTML = ''; imagenes.forEach((im, i) => { const f = document.createElement('figure'); const e = im.cloneNode(); f.append(e); const cap = document.createElement('figcaption'); cap.textContent = `Vista ${i + 1} · ${im.naturalWidth}×${im.naturalHeight}`; f.append(cap); c.append(f); }); } // Píxeles de cada vista al tamaño de trabajo (recorte centrado a la proporción de la vista 1). function pixeles(im, w, h) { const c = new OffscreenCanvas(w, h), x = c.getContext('2d', { willReadFrequently: true }), r = N.recorteCentrado(im.naturalWidth, im.naturalHeight, w, h); x.drawImage(im, r.x, r.y, r.w, r.h, 0, 0, w, h); return x.getImageData(0, 0, w, h).data; } async function ejecutar() { if (ocupado || !ses) return; if (imagenes.length < MIN_VISTAS) { estado(`Necesitas al menos ${MIN_VISTAS} vistas.`); return; } ocupado = true; actualizarBoton(); try { const { w, h } = N.tamTrabajo(imagenes[0].naturalWidth, imagenes[0].naturalHeight, +$('lado').value); const px = imagenes.map((im) => pixeles(im, w, h)); estado(`Infiriendo ${px.length} vistas a ${w}×${h}… (una inferencia a la vez; en 1 hilo WASM tarda varios segundos)`); await new Promise((r) => setTimeout(r, 30)); const t0 = performance.now(); const s = await N.inferir(ort, ses, N.aTensor(px, w, h), px.length, w, h); const tInf = performance.now() - t0; ultimo = { s, px, w, h, tInf, P: N.poses(s), est: N.estadisticas(s) }; const t1 = performance.now(); ultimo.coh = N.coherencia(s, ultimo.P); ultimo.tCoh = performance.now() - t1; ultimo.cmp = verdad ? N.compararVerdad(ultimo.P, verdad, w, h) : null; pintarProfundidades(); actualizarNube(); resumen(); estado(`Listo: ${px.length} vistas en ${(tInf / 1000).toFixed(1)} s.`); } catch (e) { estado('Error: ' + e.message); console.error(e); } ocupado = false; actualizarBoton(); } function pintarProfundidades() { const { s, w, h, est } = ultimo, c = $('profundidades'); c.innerHTML = ''; const zmin = Math.min(...est.map((e) => e.p2)), zmax = Math.max(...est.map((e) => e.p98)); for (let i = 0; i < s.n; i++) { const cv = document.createElement('canvas'); cv.width = w; cv.height = h; cv.getContext('2d').putImageData(new ImageData(N.colorearProfundidad(s.depth.subarray(i * w * h, (i + 1) * w * h), w, h, zmin, zmax), w, h), 0, 0); const f = document.createElement('figure'); f.append(cv); const cap = document.createElement('figcaption'); cap.textContent = `Profundidad vista ${i + 1} (cerca = rojo, lejos = azul)`; f.append(cap); c.append(f); } } function actualizarNube() { if (!ultimo) return; const t = performance.now(); ultimo.nb = N.nube(ultimo.s, ultimo.px, ultimo.P, { paso: +$('paso').value, descartarConf: +$('conf').value / 100, bordes: $('bordes').checked ? 0.04 : 0 }); ultimo.tNube = performance.now() - t; mostrarNube(ultimo.nb, ultimo.P, { tamPunto: +$('tamPunto').value, colorPorVista: $('porVista').checked }); $('descargarPly').disabled = false; $('descargarJson').disabled = false; resumen(); } const f2 = (x, d = 2) => (Number.isFinite(x) ? x.toFixed(d).replace('.', ',') : '—'); function resumen() { const { s, P, est, coh, cmp, tInf, nb, w, h, tNube, tCoh } = ultimo; let txt = `Tamaño de trabajo: ${w}×${h} · vistas: ${s.n} · inferencia: ${(tInf / 1000).toFixed(2).replace('.', ',')} s (WASM ${ort.env.wasm.numThreads} hilo/s)\n`; txt += `Nube fusionada: ${nb ? nb.total.toLocaleString('es-CO') : 0} puntos (nube ${f2(tNube, 0)} ms · coherencia ${f2(tCoh, 0)} ms)\n\n`; txt += 'Poses relativas a la vista 1 (escala arbitraria; traslación expresada en múltiplos de la profundidad mediana de la vista 1)\n'; const dm = est[0].mediana; P.forEach((p, i) => { txt += `Vista ${i + 1}: giro ${f2(p.giro)}° (yaw ${f2(p.euler.yaw)}°, pitch ${f2(p.euler.pitch)}°, roll ${f2(p.euler.roll)}°) · centro [${p.C.map((v) => f2(v / dm, 3)).join('; ')}] · fx ${f2(p.K[0], 1)} fy ${f2(p.K[4], 1)} cx ${f2(p.K[2], 1)} cy ${f2(p.K[5], 1)} px\n`; }); txt += '\nProfundidad por vista (unidades relativas del modelo): ' + est.map((e, i) => `V${i + 1} ${f2(e.min)}–${f2(e.max)} (mediana ${f2(e.mediana)}, confianza media ${f2(e.confMedia)})`).join(' · ') + '\n'; txt += 'Coherencia multivista (vista i proyectada en la vista 1): ' + coh.map((c) => `V${c.vista}: ${f2(100 * c.dentro5, 0)} % de puntos con |Δz|<5 % (error mediano ${f2(100 * c.errMediano, 1)} %, visibles ${f2(100 * c.visibles, 0)} %)`).join(' · ') + '\n'; const fx = P.map((p) => p.K[0]), dispFx = (Math.max(...fx) - Math.min(...fx)) / Math.min(...fx); const rango = Math.min(...est.map((e) => e.p98 / e.p2)), cohMin = Math.min(...coh.map((c) => c.dentro5)); const dudoso = cohMin < 0.5 || rango < 1.15 || dispFx > 0.2; txt += dudoso ? '⚠ Resultado dudoso: baja coherencia entre vistas, profundidad casi plana o focales muy distintas. ¿Son fotos de la misma escena con solape suficiente?\n' : 'Chequeo heurístico: coherencia entre vistas aceptable (no garantiza exactitud).\n'; if (cmp) { txt += `\nComparación con la verdad sintética (escala alineada por mínimos cuadrados, factor ${f2(cmp.escala, 3)}):\n`; cmp.vistas.forEach((v) => { txt += `Vista ${v.vista}: giro real ${f2(v.giroVerdad)}° vs estimado ${f2(v.giroPred)}° → error de rotación ${f2(v.errRot)}° · error de dirección de traslación ${f2(v.errDirTras, 1)}° · error del centro tras escalar ${f2(v.errCentroEsc, 3)} (línea base real ${f2(v.baseVerdad, 2)})\n`; }); txt += `fx real ${f2(cmp.fxVerdad, 1)} px vs estimado ${cmp.fxPred.map((x) => f2(x, 1)).join(' / ')} px (${cmp.errFxPct.map((x) => (x > 0 ? '+' : '') + f2(x, 1)).join(' / ')} %)\n`; } $('resumen').textContent = txt; ultimo.dudoso = dudoso; } function descargarArchivo(datos, nombre, tipo) { const a = document.createElement('a'); a.href = URL.createObjectURL(new Blob([datos], { type: tipo })); a.download = nombre; a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 5000); } $('descargarPly').addEventListener('click', () => ultimo?.nb && descargarArchivo(N.ply(ultimo.nb.pos, ultimo.nb.col), 'nube_multivista.ply', 'application/octet-stream')); $('descargarJson').addEventListener('click', () => { if (!ultimo) return; const j = { modelo: `onnx-community/depth-anything-v3-small@${REV}`, ancho: ultimo.w, alto: ultimo.h, convencion: 'OpenCV mundo(cámara 1)→cámara i; escala arbitraria', vistas: ultimo.P.map((p, i) => ({ vista: i + 1, R: p.R, t: p.t, centro: p.C, K: p.K, giro_grados: p.giro, profundidad: ultimo.est[i] })), coherencia: ultimo.coh, verdad: ultimo.cmp }; descargarArchivo(JSON.stringify(j, null, 1), 'poses_intrinsecos.json', 'application/json'); }); $('ejemplos').addEventListener('click', async (e) => { const b = e.target.closest('button'); if (!b || ocupado) return; try { verdadTodo ??= await (await fetch('ejemplos/verdad.json')).json(); const v = verdadTodo.ejemplos.find((x) => x.id === b.dataset.id); // fetch → blob: los archivos del Space pueden venir de otro origen (CDN); así el canvas no queda «contaminado». imagenes = await Promise.all(v.vistas.map(async (x) => { const r = await fetch('ejemplos/' + x.imagen); if (!r.ok) throw new Error(`${x.imagen}: HTTP ${r.status}`); return cargarImagen(URL.createObjectURL(await r.blob())); })); verdad = v; $('lado').value = '504'; miniaturas(); actualizarBoton(); if (ses) ejecutar(); else { $('ejecutar').dataset.auto = '1'; estado('Imágenes listas; esperando a que termine de cargar el modelo…'); } } catch (err) { estado('Error: ' + err.message); } }); $('archivos').addEventListener('change', async (e) => { const fs = [...e.target.files]; try { if (fs.length < MIN_VISTAS || fs.length > MAX_VISTAS) throw new Error(`Selecciona entre ${MIN_VISTAS} y ${MAX_VISTAS} imágenes a la vez (tienes ${fs.length}).`); const ims = []; for (const f of fs) { if (f.size > MAX_BYTES) throw new Error(`${f.name}: mayor de 20 MB`); const im = await cargarImagen(URL.createObjectURL(f)); if (im.naturalWidth * im.naturalHeight > MAX_MP) throw new Error(`${f.name}: más de 40 megapíxeles`); ims.push(im); } imagenes = ims; verdad = null; miniaturas(); actualizarBoton(); const r0 = ims[0].naturalWidth / ims[0].naturalHeight, distinta = ims.some((im) => Math.abs(im.naturalWidth / im.naturalHeight - r0) / r0 > 0.02); estado(`${ims.length} imágenes cargadas${distinta ? ' (proporciones distintas: se recortarán al centro con la proporción de la vista 1)' : ''}. Pulsa «Reconstruir».`); } catch (err) { estado('Error: ' + err.message); } }); $('ejecutar').addEventListener('click', ejecutar); for (const id of ['paso', 'conf', 'bordes', 'tamPunto', 'porVista']) $(id).addEventListener('change', () => { $('confV').textContent = $('conf').value + ' %'; actualizarNube(); }); $('conf').addEventListener('input', () => { $('confV').textContent = $('conf').value + ' %'; }); iniciarVisor($('visor')); window.__da3 = { get ultimo() { return ultimo; }, get listo() { return !!ses; }, get ocupado() { return ocupado; }, ejecutar, N }; iniciar();