Fix comparator hidden measurement regression
Browse files- BROWSER_CHECKLIST.md +46 -0
- README.md +11 -1
- assets/index-Bs80IM8r.css +1 -0
- assets/index-DZgGZDxK.js +27 -0
- index.html +2 -2
BROWSER_CHECKLIST.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Checklist de verificación en navegador (coordinador)
|
| 2 |
+
|
| 3 |
+
**Alcance:** Space estático publicado / ZIP desplegado. Esta checklist **no** fue ejecutada por el agente constructor contra un Space HF en vivo (sin automatización del navegador del coordinador).
|
| 4 |
+
|
| 5 |
+
Marca cada ítem en el navegador real del visitante.
|
| 6 |
+
|
| 7 |
+
## Modelo y runtime
|
| 8 |
+
|
| 9 |
+
- [ ] «Cargar modelo» descarga ~27 MB + WASM; barra de progreso visible
|
| 10 |
+
- [ ] Cancelar descarga funciona; Reintentar tras error de red
|
| 11 |
+
- [ ] Tras listo, el botón Inferir se habilita solo con imagen seleccionada
|
| 12 |
+
- [ ] No se exige WebGPU; funciona en CPU/WASM
|
| 13 |
+
- [ ] En DevTools → Network: hay fetch al Hub/CDN del modelo; **no** hay upload del JPG del usuario a un backend propio
|
| 14 |
+
|
| 15 |
+
## Tres ejemplos
|
| 16 |
+
|
| 17 |
+
Para `house-1950s`, `wooden-modern`, `castle-living`:
|
| 18 |
+
|
| 19 |
+
- [ ] Inferencia completa sin error
|
| 20 |
+
- [ ] `#results[data-status="ok"]`
|
| 21 |
+
- [ ] `data-example-id` correcto
|
| 22 |
+
- [ ] `data-stats-non-constant="true"`
|
| 23 |
+
- [ ] `data-stats-finite` = `data-stats-pixels` (o finitos > 0)
|
| 24 |
+
- [ ] Dimensiones coherentes con el canvas de inferencia (lado largo ≤1024)
|
| 25 |
+
- [ ] Latencia `data-stats-latency-ms` > 0 (medida, no inventada)
|
| 26 |
+
|
| 27 |
+
**Nota:** estos checks no evalúan calidad geométrica del mapa.
|
| 28 |
+
|
| 29 |
+
## UI
|
| 30 |
+
|
| 31 |
+
- [ ] Slider comparador: en el **50%** el lado izquierdo debe mostrar la **foto original** (no el mapa coloreado) y el derecho el mapa. Probar también 0 y 99 — el divisor blanco se mueve y el contenido cambia de foto↔mapa (regresión previa: ambos lados mostraban solo profundidad por tamaño 0×0 del original medido con `#results[hidden]`).
|
| 32 |
+
- [ ] Parallax opcional: se puede activar si hay WebGL2 y no `prefers-reduced-motion`; etiqueta de efecto artístico visible
|
| 33 |
+
- [ ] Parallax: **mover el puntero sobre el lienzo** — el desplazamiento es conservador (diseño); un screenshot estático no demuestra fallo. Avisos GPU `ReadPixels` en consolas Chromium no son error de la app.
|
| 34 |
+
- [ ] Con `prefers-reduced-motion: reduce`, parallax no se fuerza
|
| 35 |
+
- [ ] Descargar PNG abre un PNG real (visualización 8-bit)
|
| 36 |
+
- [ ] Descargar JSON incluye `semantics.higherMeans: "closer"`, pin de revisión, stats, sin nombre de archivo de subida
|
| 37 |
+
- [ ] Limpiar resultados revoca previews; nueva inferencia no muestra resultado obsoleto
|
| 38 |
+
|
| 39 |
+
## Errores
|
| 40 |
+
|
| 41 |
+
- [ ] Archivo no imagen / >10 MB / >20 MP → mensaje en español
|
| 42 |
+
- [ ] Mensajes sin stack traces de servidor
|
| 43 |
+
|
| 44 |
+
## Accesibilidad rápida
|
| 45 |
+
|
| 46 |
+
- [ ] Foco visible en botones; `lang="es"`; skip link; textos de estado con `aria-live`
|
README.md
CHANGED
|
@@ -66,12 +66,22 @@ Smoke opcional en Node (no sustituye la prueba en el navegador del Space):
|
|
| 66 |
npm run smoke
|
| 67 |
```
|
| 68 |
|
| 69 |
-
Empaquetar ZIP desplegable (raíz = `index.html` + `README.md`):
|
| 70 |
|
| 71 |
```bash
|
| 72 |
npm run build && npm run package:zip
|
| 73 |
```
|
| 74 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
## Ejemplos CC0
|
| 76 |
|
| 77 |
Ver `examples/ATTRIBUTION.json` (Storylanding, Jolene Hardy, Daderot — Wikimedia Commons).
|
|
|
|
| 66 |
npm run smoke
|
| 67 |
```
|
| 68 |
|
| 69 |
+
Empaquetar ZIP desplegable (raíz = `index.html` + `README.md` + `BROWSER_CHECKLIST.md`):
|
| 70 |
|
| 71 |
```bash
|
| 72 |
npm run build && npm run package:zip
|
| 73 |
```
|
| 74 |
|
| 75 |
+
Verificación local del comparador (Chromium, sin modelo / sin HF):
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
npm run build && npm run verify:comparator
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
### Nota de corrección (comparador)
|
| 82 |
+
|
| 83 |
+
Bug en vivo: el original se medía con `#results[hidden]` → `clientHeight=0` → estilos inline `0×0` → el overlay vacío dejaba ver solo el mapa de profundidad a ambos lados del slider. La medición ocurre ahora **después** de mostrar resultados, con helper que no hornea ceros.
|
| 84 |
+
|
| 85 |
## Ejemplos CC0
|
| 86 |
|
| 87 |
Ver `examples/ATTRIBUTION.json` (Storylanding, Jolene Hardy, Daderot — Wikimedia Commons).
|
assets/index-Bs80IM8r.css
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
@font-face{font-family:Fraunces;font-style:normal;font-weight:400;font-display:swap;src:url(../fonts/fraunces-latin-400-normal.woff2) format("woff2")}@font-face{font-family:Fraunces;font-style:normal;font-weight:600;font-display:swap;src:url(../fonts/fraunces-latin-600-normal.woff2) format("woff2")}@font-face{font-family:Fraunces;font-style:normal;font-weight:700;font-display:swap;src:url(../fonts/fraunces-latin-700-normal.woff2) format("woff2")}@font-face{font-family:"Source Sans 3";font-style:normal;font-weight:400;font-display:swap;src:url(../fonts/source-sans-3-latin-400-normal.woff2) format("woff2")}@font-face{font-family:"Source Sans 3";font-style:normal;font-weight:600;font-display:swap;src:url(../fonts/source-sans-3-latin-600-normal.woff2) format("woff2")}@font-face{font-family:"Source Sans 3";font-style:normal;font-weight:700;font-display:swap;src:url(../fonts/source-sans-3-latin-700-normal.woff2) format("woff2")}:root{--bg0: #0c1418;--bg1: #132028;--bg2: #1a3038;--ink: #e7f0f2;--muted: #9bb0b8;--accent: #e0a045;--accent-ink: #1a1208;--line: rgba(231, 240, 242, .14);--ok: #3dba8b;--danger: #e07171;--radius: 14px;--font-display: "Fraunces", "Palatino Linotype", Palatino, serif;--font-body: "Source Sans 3", "Segoe UI", sans-serif;color-scheme:dark}*,*:before,*:after{box-sizing:border-box}html,body{margin:0;min-height:100%}body{font-family:var(--font-body);color:var(--ink);background:radial-gradient(1200px 600px at 10% -10%,rgba(224,160,69,.16),transparent 55%),radial-gradient(900px 500px at 90% 0%,rgba(61,186,139,.12),transparent 50%),linear-gradient(165deg,var(--bg0),var(--bg1) 45%,#0a1216 100%);line-height:1.5}img{max-width:100%;display:block}.skip-link{position:absolute;left:-999px;top:0;background:var(--accent);color:var(--accent-ink);padding:.5rem 1rem;z-index:100}.skip-link:focus{left:.5rem;top:.5rem}.site-header{padding:1.75rem clamp(1rem,4vw,2.5rem) .5rem}.brand{margin:0;font-family:var(--font-display);font-weight:700;font-size:clamp(2.4rem,6vw,3.6rem);letter-spacing:-.03em;line-height:1}.tagline{margin:.35rem 0 0;color:var(--muted);font-size:1.05rem}.shell{width:min(1080px,100%);margin:0 auto;padding:.5rem clamp(1rem,4vw,2.5rem) 3rem;display:grid;gap:1.25rem}.hero{padding:.5rem 0 .25rem;animation:rise .7s ease both}.hero-title{margin:0;font-family:var(--font-display);font-weight:600;font-size:clamp(1.35rem,3.2vw,1.85rem);max-width:22ch;line-height:1.2}.hero-lead{margin:.85rem 0 1.25rem;max-width:58ch;color:var(--muted)}.hero-cta{display:flex;flex-wrap:wrap;gap:.65rem}.notice,.panel{border:1px solid var(--line);background:#132028b8;border-radius:var(--radius);padding:1.1rem 1.2rem;-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px);animation:rise .8s ease both}.notice p{margin:0 0 .65rem;color:var(--muted)}.notice p:last-child{margin-bottom:0}.notice strong{color:var(--ink)}.panel h2,.parallax-block h3{margin:0 0 .35rem;font-family:var(--font-display);font-size:1.35rem}.panel-lead,.hint{margin:0 0 1rem;color:var(--muted);font-size:.98rem}.examples{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:.75rem;margin-bottom:1rem}@media(max-width:720px){.examples{grid-template-columns:1fr}}.example-btn{-webkit-appearance:none;-moz-appearance:none;appearance:none;border:1px solid var(--line);background:var(--bg2);color:inherit;border-radius:12px;padding:0;overflow:hidden;cursor:pointer;text-align:left;transition:border-color .2s ease,transform .2s ease}.example-btn:hover:not(:disabled){border-color:#e0a0458c;transform:translateY(-1px)}.example-btn:disabled{opacity:.45;cursor:not-allowed}.example-btn[aria-pressed=true]{border-color:var(--accent);box-shadow:inset 0 0 0 1px #e0a04559}.example-btn img{width:100%;aspect-ratio:4 / 3;object-fit:cover}.example-btn .cap{padding:.55rem .7rem .75rem;font-size:.88rem}.example-btn .meta{display:block;color:var(--muted);font-size:.78rem;margin-top:.2rem}.upload-row,.action-row,.export-row{display:flex;flex-wrap:wrap;gap:.65rem;align-items:center;margin-bottom:.85rem}.selection-label{margin:0;color:var(--muted);font-size:.92rem}.status-line{margin:0;min-height:1.4em;color:var(--muted)}.status-line[data-tone=ok]{color:var(--ok)}.status-line[data-tone=error]{color:var(--danger)}.btn{-webkit-appearance:none;-moz-appearance:none;appearance:none;border:1px solid transparent;border-radius:999px;padding:.65rem 1.15rem;font:inherit;font-weight:600;cursor:pointer;transition:background .2s ease,color .2s ease,opacity .2s ease}.btn:disabled{opacity:.4;cursor:not-allowed}.btn.primary{background:var(--accent);color:var(--accent-ink)}.btn.primary:hover:not(:disabled){filter:brightness(1.05)}.btn.secondary{background:transparent;border-color:#e0a0458c;color:var(--accent)}.btn.ghost{background:transparent;border-color:var(--line);color:var(--ink)}.progress{margin-top:1rem}.progress-track{height:8px;border-radius:999px;background:#ffffff14;overflow:hidden}.progress-bar{height:100%;background:linear-gradient(90deg,var(--accent),#f0c27a);transition:width .2s ease}.progress-text{margin:.45rem 0 0;color:var(--muted);font-size:.9rem}.comparator-frame{position:relative;width:min(100%,920px);margin:0 auto 1rem;border-radius:12px;overflow:hidden;border:1px solid var(--line);background:#000;-webkit-user-select:none;user-select:none;touch-action:none}.comparator-frame>#cmp-depth{display:block;width:100%;height:auto;vertical-align:top}.cmp-overlay{position:absolute;top:0;left:0;bottom:0;width:50%;overflow:hidden;border-right:2px solid rgba(255,255,255,.85);z-index:1;pointer-events:none}.cmp-overlay>#cmp-original{position:absolute;top:0;left:0;height:100%;width:auto;max-width:none;display:block}.cmp-slider{position:absolute;inset:auto 0 .65rem 0;width:calc(100% - 1.5rem);margin:0 auto;display:block;accent-color:var(--accent);z-index:2}.cmp-labels{position:absolute;top:.55rem;left:.7rem;right:.7rem;display:flex;justify-content:space-between;font-size:.78rem;letter-spacing:.04em;text-transform:uppercase;color:#fff;text-shadow:0 1px 2px rgba(0,0,0,.7);pointer-events:none;z-index:2}.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(110px,1fr));gap:.55rem;margin:0 0 1rem}.stats div{border:1px solid var(--line);border-radius:10px;padding:.55rem .65rem}.stats dt{margin:0;color:var(--muted);font-size:.75rem;text-transform:uppercase;letter-spacing:.04em}.stats dd{margin:.15rem 0 0;font-variant-numeric:tabular-nums;font-weight:600}.parallax-block{margin-top:.5rem;padding-top:.75rem;border-top:1px solid var(--line)}.check,.intensity{display:flex;align-items:center;gap:.55rem;margin-bottom:.65rem;color:var(--muted)}#parallax-canvas{width:100%;max-width:920px;border-radius:12px;border:1px solid var(--line);background:#000;margin-top:.5rem}.site-footer{width:min(1080px,100%);margin:0 auto;padding:0 clamp(1rem,4vw,2.5rem) 2.5rem;color:var(--muted);font-size:.9rem}.site-footer a{color:var(--accent)}@keyframes rise{0%{opacity:0;transform:translateY(10px)}to{opacity:1;transform:translateY(0)}}@media(prefers-reduced-motion:reduce){*,*:before,*:after{animation:none!important;transition:none!important}}
|
assets/index-DZgGZDxK.js
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
(function(){const a=document.createElement("link").relList;if(a&&a.supports&&a.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))o(i);new MutationObserver(i=>{for(const l of i)if(l.type==="childList")for(const s of l.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&o(s)}).observe(document,{childList:!0,subtree:!0});function e(i){const l={};return i.integrity&&(l.integrity=i.integrity),i.referrerPolicy&&(l.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?l.credentials="include":i.crossOrigin==="anonymous"?l.credentials="omit":l.credentials="same-origin",l}function o(i){if(i.ep)return;i.ep=!0;const l=e(i);fetch(i.href,l)}})();const W=10*1024*1024,$=2e7,V=1024,j=512,b={id:"onnx-community/depth-anything-v2-small",revision:"4472b7362082ad9968fee890ca0f1e5aca36b93d",file:"onnx/model_quantized.onnx",bytes:27258801,sha256:"fcf51f1b230362b28690bb9d1809bf0431f29cad20534e3f589bd7285547f20d"},Y="3.7.6",Q=new Set(["image/jpeg","image/png","image/webp"]),R=Object.freeze({encoding:"inverse_depth_relative",higherMeans:"closer",units:null,metricComparableAcrossImages:!1,note:"Depth Anything V2 Small predicts relative inverse depth. Higher values are closer to the camera. Values are not meters and are not comparable across images after per-image normalization."}),Z=Object.freeze([{id:"house-1950s",file:"examples/example-house-1950s.jpg",caption:"Interior de casa de los años 1950 (Shelburne Museum)",author:"Storylanding",license:"CC0",sourceUrl:"https://commons.wikimedia.org/wiki/File:1950s-house_interior.jpg"},{id:"wooden-modern",file:"examples/example-wooden-modern.jpg",caption:"Interior moderno de madera (Unsplash → Commons)",author:"Jolene Hardy",license:"CC0",sourceUrl:"https://commons.wikimedia.org/wiki/File:Modern_wooden_house_interior_(Unsplash).jpg"},{id:"castle-living",file:"examples/example-castle-living.jpg",caption:"Salón — Castle Hill on the Crane Estate, Ipswich, MA",author:"Daderot",license:"CC0",sourceUrl:"https://commons.wikimedia.org/wiki/File:Living_Room_-_Great_House_-_Castle_Hill_on_the_Crane_Estate_-_Ipswich,_Massachusetts_-_DSC06150.jpg"}]);function ee(t){const a=(t==null?void 0:t.type)||"",e=Number((t==null?void 0:t.size)??0);return Q.has(a)?!Number.isFinite(e)||e<=0?{ok:!1,code:"empty_file",message:"El archivo está vacío o no se pudo leer."}:e>W?{ok:!1,code:"file_too_large",message:`El archivo supera el límite de ${(W/(1024*1024)).toFixed(0)} MB.`}:{ok:!0}:{ok:!1,code:"invalid_type",message:"Formato no válido. Usa JPG, PNG o WebP."}}function te(t){const a=Number(t==null?void 0:t.width),e=Number(t==null?void 0:t.height);return!Number.isFinite(a)||!Number.isFinite(e)||a<=0||e<=0?{ok:!1,code:"invalid_dims",message:"No se pudieron obtener las dimensiones de la imagen."}:a*e>$?{ok:!1,code:"too_many_pixels",message:`La imagen supera ${$.toLocaleString("es")} píxeles (máx. 20 MP).`}:{ok:!0}}function ae(t,a,e=1024){const o=Math.max(1,Math.round(t)),i=Math.max(1,Math.round(a)),l=Math.max(o,i);if(l<=e)return{width:o,height:i,scale:1,resized:!1};const s=e/l;return{width:Math.max(1,Math.round(o*s)),height:Math.max(1,Math.round(i*s)),scale:s,resized:!0}}function ne(t){const a=(t==null?void 0:t.length)??0;if(!a)return{ok:!1,code:"empty",message:"Mapa de profundidad vacío."};let e=1/0,o=-1/0,i=0;for(let c=0;c<a;c++){const u=t[c];Number.isFinite(u)&&(i+=1,u<e&&(e=u),u>o&&(o=u))}if(i===0)return{ok:!1,code:"no_finite",message:"El mapa no contiene valores finitos (NaN/Inf).",pixelCount:a,finiteCount:0,nonConstant:!1};if(!(o>e))return{ok:!1,code:"constant",message:"El mapa es constante; se rechaza como resultado inválido.",min:e,max:o,finiteCount:i,pixelCount:a,nonConstant:!1,semantics:R.encoding,higherMeans:R.higherMeans};const s=o-e,d=new Float32Array(a);for(let c=0;c<a;c++){const u=t[c];d[c]=Number.isFinite(u)?(u-e)/s:NaN}return{ok:!0,min:e,max:o,finiteCount:i,pixelCount:a,nonConstant:!0,normalized:d,semantics:R.encoding,higherMeans:R.higherMeans}}function H(t,a,e){const o=a*e,i=new Uint8ClampedArray(o*4);for(let l=0;l<o;l++){const s=t[l],d=l*4;if(!Number.isFinite(s)){i[d]=0,i[d+1]=0,i[d+2]=0,i[d+3]=0;continue}const c=oe(re(s));i[d]=c[0],i[d+1]=c[1],i[d+2]=c[2],i[d+3]=255}return i}function re(t){return t<0?0:t>1?1:t}const S=[[0,[94,79,162]],[.25,[50,136,189]],[.5,[102,194,165]],[.75,[254,224,139]],[1,[213,62,79]]];function oe(t){for(let a=0;a<S.length-1;a++){const[e,o]=S[a],[i,l]=S[a+1];if(t>=e&&t<=i){const s=(t-e)/(i-e||1);return[Math.round(o[0]+(l[0]-o[0])*s),Math.round(o[1]+(l[1]-o[1])*s),Math.round(o[2]+(l[2]-o[2])*s)]}}return S[S.length-1][1]}function ie(t,a,e,o=j){const i=Math.max(a,e);if(i<=o)return{data:t instanceof Float32Array?t:Float32Array.from(t),width:a,height:e,downsampled:!1,originalWidth:a,originalHeight:e};const l=o/i,s=Math.max(1,Math.round(a*l)),d=Math.max(1,Math.round(e*l)),c=new Float32Array(s*d);for(let u=0;u<d;u++){const C=Math.floor(u*e/d),P=Math.floor((u+1)*e/d);for(let m=0;m<s;m++){const x=Math.floor(m*a/s),E=Math.floor((m+1)*a/s);let A=0,I=0;for(let T=C;T<Math.max(P,C+1);T++)for(let v=x;v<Math.max(E,x+1);v++){const _=t[T*a+v];Number.isFinite(_)&&(A+=_,I+=1)}c[u*s+m]=I?A/I:NaN}}return{data:c,width:s,height:d,downsampled:!0,originalWidth:a,originalHeight:e}}function le(t){const{relative:a,width:e,height:o,stats:i,sourceKind:l,exampleId:s=null,model:d=b,latencyMs:c,runtime:u="wasm",inferenceSize:C,originalSize:P}=t,m=ie(a,e,o,j),x={formatVersion:1,timestamp:new Date().toISOString(),sourceKind:l,model:{id:d.id,revision:d.revision,file:d.file??b.file,dtype:"q8"},semantics:{...R},originalSize:P,inferenceSize:C,relative:{width:m.width,height:m.height,downsampled:m.downsampled,originalWidth:m.originalWidth,originalHeight:m.originalHeight,values:Array.from(m.data,E=>Number.isFinite(E)?Number(E):null)},stats:{min:i.min,max:i.max,finiteCount:i.finiteCount,pixelCount:i.pixelCount,nonConstant:i.nonConstant},inferenceLatencyMs:c,runtime:u,disclaimer:"Valores relativos (inverso). No son metros ni geometría 3D métrica. La normalización es por imagen."};return l==="example"&&s&&(x.exampleId=s),x}async function q(t,a,e){const o=typeof OffscreenCanvas<"u"?new OffscreenCanvas(a,e):Object.assign(document.createElement("canvas"),{width:a,height:e});o.width=a,o.height=e;const i=o.getContext("2d");if(!i)throw new Error("No 2D context");const l=new ImageData(t,a,e);return i.putImageData(l,0,0),o.convertToBlob?o.convertToBlob({type:"image/png"}):new Promise((s,d)=>{o.toBlob(c=>c?s(c):d(new Error("PNG falló")),"image/png")})}class se{constructor(){this.urls=new Set}create(a){const e=URL.createObjectURL(a);return this.urls.add(e),e}revoke(a){a&&this.urls.has(a)&&(URL.revokeObjectURL(a),this.urls.delete(a))}revokeAll(){for(const a of this.urls)URL.revokeObjectURL(a);this.urls.clear()}}function J(t,a,e){const o=e.create(t),i=document.createElement("a");i.href=o,i.download=a,i.rel="noopener",document.body.appendChild(i),i.click(),i.remove(),setTimeout(()=>e.revoke(o),2e3)}function de(t,a){const e=Number(t==null?void 0:t.clientWidth)||0,o=Number(t==null?void 0:t.clientHeight)||0;return e<=0||o<=0?(a.style.removeProperty("width"),a.style.removeProperty("height"),{ok:!1,reason:"not_laid_out"}):(a.style.width=`${e}px`,a.style.height=`${o}px`,{ok:!0,width:e,height:o})}function ce(t,a){const e=t.getContext("webgl2",{antialias:!0,alpha:!0,premultipliedAlpha:!0});if(!e)return{supported:!1,reason:"webgl2_unavailable",dispose(){},setOffset(){},setIntensity(){},draw(){}};const{imageBitmap:o,depthNorm:i,width:l,height:s}=a;let d=Math.min(.35,Math.max(0,a.intensity??.12)),c=0,u=0;t.width=l,t.height=s;const m=me(e,`#version 300 es
|
| 2 |
+
in vec2 a_uv;
|
| 3 |
+
uniform sampler2D u_depth;
|
| 4 |
+
uniform vec2 u_offset;
|
| 5 |
+
uniform float u_intensity;
|
| 6 |
+
out vec2 v_uv;
|
| 7 |
+
void main() {
|
| 8 |
+
float d = texture(u_depth, a_uv).r;
|
| 9 |
+
// higher d = closer → move more with camera offset
|
| 10 |
+
vec2 disp = u_offset * u_intensity * (d - 0.5) * 2.0;
|
| 11 |
+
vec2 p = a_uv * 2.0 - 1.0;
|
| 12 |
+
p.y *= -1.0;
|
| 13 |
+
gl_Position = vec4(p + disp, 0.0, 1.0);
|
| 14 |
+
gl_PointSize = 2.0;
|
| 15 |
+
v_uv = a_uv;
|
| 16 |
+
}`,`#version 300 es
|
| 17 |
+
precision highp float;
|
| 18 |
+
in vec2 v_uv;
|
| 19 |
+
uniform sampler2D u_color;
|
| 20 |
+
out vec4 outColor;
|
| 21 |
+
void main() {
|
| 22 |
+
outColor = texture(u_color, v_uv);
|
| 23 |
+
}`),x=e.getAttribLocation(m,"a_uv"),E=e.getUniformLocation(m,"u_color"),A=e.getUniformLocation(m,"u_depth"),I=e.getUniformLocation(m,"u_offset"),T=e.getUniformLocation(m,"u_intensity"),v=Math.max(1,Math.floor(Math.max(l,s)/320)),_=[];for(let h=0;h<s;h+=v)for(let y=0;y<l;y+=v)_.push(y/(l-1||1),h/(s-1||1));const N=e.createBuffer();e.bindBuffer(e.ARRAY_BUFFER,N),e.bufferData(e.ARRAY_BUFFER,new Float32Array(_),e.STATIC_DRAW);const k=e.createTexture();e.bindTexture(e.TEXTURE_2D,k),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,1),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,o);const D=e.createTexture();e.bindTexture(e.TEXTURE_2D,D),e.pixelStorei(e.UNPACK_FLIP_Y_WEBGL,0),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MIN_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_MAG_FILTER,e.LINEAR),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE),e.texParameteri(e.TEXTURE_2D,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE);const M=new Uint8Array(l*s*4);for(let h=0;h<l*s;h++){const y=i[h],O=Number.isFinite(y)?Math.round(ue(y)*255):0,U=h*4;M[U]=O,M[U+1]=O,M[U+2]=O,M[U+3]=255}e.texImage2D(e.TEXTURE_2D,0,e.RGBA,l,s,0,e.RGBA,e.UNSIGNED_BYTE,M);const F=e.createVertexArray();e.bindVertexArray(F),e.bindBuffer(e.ARRAY_BUFFER,N),e.enableVertexAttribArray(x),e.vertexAttribPointer(x,2,e.FLOAT,!1,0,0);function L(){e.viewport(0,0,t.width,t.height),e.clearColor(.05,.07,.09,1),e.clear(e.COLOR_BUFFER_BIT),e.useProgram(m),e.bindVertexArray(F),e.activeTexture(e.TEXTURE0),e.bindTexture(e.TEXTURE_2D,k),e.uniform1i(E,0),e.activeTexture(e.TEXTURE1),e.bindTexture(e.TEXTURE_2D,D),e.uniform1i(A,1),e.uniform2f(I,c,u),e.uniform1f(T,d),e.drawArrays(e.POINTS,0,_.length/2)}return L(),{supported:!0,reason:null,setOffset(h,y){c=h,u=y,L()},setIntensity(h){d=Math.min(.35,Math.max(0,h)),L()},draw:L,dispose(){e.deleteTexture(k),e.deleteTexture(D),e.deleteBuffer(N),e.deleteVertexArray(F),e.deleteProgram(m)}}}function ue(t){return t<0?0:t>1?1:t}function me(t,a,e){const o=G(t,t.VERTEX_SHADER,a),i=G(t,t.FRAGMENT_SHADER,e),l=t.createProgram();if(t.attachShader(l,o),t.attachShader(l,i),t.linkProgram(l),!t.getProgramParameter(l,t.LINK_STATUS))throw new Error(t.getProgramInfoLog(l)||"WebGL link failed");return t.deleteShader(o),t.deleteShader(i),l}function G(t,a,e){const o=t.createShader(a);if(t.shaderSource(o,e),t.compileShader(o),!t.getShaderParameter(o,t.COMPILE_STATUS))throw new Error(t.getShaderInfoLog(o)||"WebGL compile failed");return o}function z(){return typeof matchMedia=="function"&&matchMedia("(prefers-reduced-motion: reduce)").matches}function pe(t){return new Worker(""+new URL("depthWorker-D_RFPcXH.js",import.meta.url).href,{type:"module",name:t==null?void 0:t.name})}const g=new se,r={btnLoad:document.getElementById("btn-load"),btnCancelLoad:document.getElementById("btn-cancel-load"),loadProgress:document.getElementById("load-progress"),loadBar:document.getElementById("load-progress-bar"),loadText:document.getElementById("load-progress-text"),examples:document.getElementById("examples"),fileInput:document.getElementById("file-input"),selectionLabel:document.getElementById("selection-label"),btnInfer:document.getElementById("btn-infer"),btnCancelInfer:document.getElementById("btn-cancel-infer"),btnClear:document.getElementById("btn-clear"),status:document.getElementById("status-line"),results:document.getElementById("results"),cmpOriginal:document.getElementById("cmp-original"),cmpDepth:document.getElementById("cmp-depth"),cmpOverlay:document.getElementById("cmp-overlay"),cmpSlider:document.getElementById("cmp-slider"),btnPng:document.getElementById("btn-export-png"),btnJson:document.getElementById("btn-export-json"),parallaxToggle:document.getElementById("parallax-toggle"),parallaxIntensity:document.getElementById("parallax-intensity"),parallaxCanvas:document.getElementById("parallax-canvas"),parallaxNote:document.getElementById("parallax-note")},w=new pe,n={modelReady:!1,loading:!1,inferring:!1,sourceKind:null,exampleId:null,imageBitmap:null,previewUrl:null,originalSize:null,inferenceSize:null,relative:null,normalized:null,depthWidth:0,depthHeight:0,stats:null,latencyMs:null,depthPngUrl:null,originalCmpUrl:null,lastJson:null,inferId:0,parallax:null};function p(t,a=""){r.status.textContent=t,a?r.status.dataset.tone=a:delete r.status.dataset.tone}function f(){r.btnLoad.disabled=n.loading||n.modelReady,r.btnCancelLoad.disabled=!n.loading,r.btnInfer.disabled=!n.modelReady||!n.imageBitmap||n.inferring||n.loading,r.btnCancelInfer.disabled=!n.inferring,r.btnClear.disabled=!n.relative&&!n.imageBitmap,r.btnPng.disabled=!n.depthPngUrl,r.btnJson.disabled=!n.lastJson;const t=!!n.relative&&!!n.imageBitmap&&!z()&&!!document.createElement("canvas").getContext("webgl2");r.parallaxToggle.disabled=!t,r.parallaxIntensity.disabled=!r.parallaxToggle.checked;for(const a of r.examples.querySelectorAll("button"))a.disabled=n.inferring;r.fileInput.disabled=n.inferring}function fe(){r.examples.innerHTML="";for(const t of Z){const a=document.createElement("button");a.type="button",a.className="example-btn",a.role="listitem",a.dataset.exampleId=t.id,a.setAttribute("aria-pressed","false"),a.innerHTML=`
|
| 24 |
+
<img src="./${t.file}" alt="" loading="lazy" width="640" height="480" />
|
| 25 |
+
<span class="cap">${t.caption}
|
| 26 |
+
<span class="meta">${t.author} · ${t.license}</span>
|
| 27 |
+
</span>`,a.addEventListener("click",()=>he(t)),r.examples.appendChild(a)}}async function he(t){try{X({keepSelection:!1});const a=await fetch(`./${t.file}`);if(!a.ok)throw new Error("No se pudo cargar el ejemplo.");const e=await a.blob();await K(e,{sourceKind:"example",exampleId:t.id,label:`${t.caption} (${t.author}, ${t.license})`});for(const o of r.examples.querySelectorAll("button"))o.setAttribute("aria-pressed",o.dataset.exampleId===t.id?"true":"false")}catch(a){p(a.message||"Error al cargar el ejemplo.","error")}}r.fileInput.addEventListener("change",async()=>{var e;const t=(e=r.fileInput.files)==null?void 0:e[0];if(r.fileInput.value="",!t)return;const a=ee(t);if(!a.ok){p(a.message,"error");return}try{X({keepSelection:!1});for(const o of r.examples.querySelectorAll("button"))o.setAttribute("aria-pressed","false");await K(t,{sourceKind:"upload",exampleId:null,label:`Archivo local (${(t.size/1024).toFixed(0)} KB) — el nombre no se guarda`})}catch(o){p(o.message||"No se pudo decodificar la imagen.","error")}});async function K(t,a){const e=await createImageBitmap(t),o=te({width:e.width,height:e.height});if(!o.ok){e.close(),p(o.message,"error"),f();return}n.imageBitmap&&n.imageBitmap.close(),n.previewUrl&&g.revoke(n.previewUrl),n.imageBitmap=e,n.originalSize={width:e.width,height:e.height},n.sourceKind=a.sourceKind,n.exampleId=a.exampleId,n.previewUrl=g.create(t),r.selectionLabel.textContent=a.label,p("Imagen lista. Puedes inferir cuando el modelo esté cargado.","ok"),f()}function ge(){return new URL("wasm/",document.baseURI).href}r.btnLoad.addEventListener("click",()=>{n.loading=!0,r.loadProgress.hidden=!1,r.loadBar.style.width="0%",r.loadText.textContent=`Descargando ${b.id}@${b.revision.slice(0,7)} (~${(b.bytes/1e6).toFixed(0)} MB) + runtime…`,p("Cargando modelo…"),f(),w.postMessage({type:"load",wasmPaths:ge()})});r.btnCancelLoad.addEventListener("click",()=>{w.postMessage({type:"cancelLoad"}),n.loading=!1,r.loadProgress.hidden=!0,p("Descarga cancelada.","error"),f()});r.btnInfer.addEventListener("click",()=>xe());r.btnCancelInfer.addEventListener("click",()=>{w.postMessage({type:"cancelInfer",id:n.inferId}),n.inferring=!1,p("Inferencia cancelada.","error"),f()});r.btnClear.addEventListener("click",()=>{X({keepSelection:!1}),p(n.modelReady?"Resultados limpios. Modelo listo.":"Resultados limpios."),f()});r.cmpSlider.addEventListener("input",()=>{const t=Number(r.cmpSlider.value);r.cmpOverlay.style.width=`${t}%`});r.btnPng.addEventListener("click",async()=>{if(n.normalized)try{const t=H(n.normalized,n.depthWidth,n.depthHeight),a=await q(t,n.depthWidth,n.depthHeight);J(a,"depthlab-depth.png",g)}catch(t){p(t.message||"No se pudo exportar el PNG.","error")}});r.btnJson.addEventListener("click",()=>{if(!n.lastJson)return;const t=new Blob([JSON.stringify(n.lastJson,null,2)],{type:"application/json"});J(t,"depthlab-relative.json",g)});r.parallaxToggle.addEventListener("change",()=>{r.parallaxToggle.checked?be():B(),f()});r.parallaxIntensity.addEventListener("input",()=>{var a;const t=Number(r.parallaxIntensity.value)/100;(a=n.parallax)==null||a.setIntensity(t)});async function xe(){if(!n.imageBitmap||!n.modelReady)return;n.inferring=!0,n.inferId+=1;const t=n.inferId;p("Inferencia en curso (WASM)…"),f();try{const a=ae(n.imageBitmap.width,n.imageBitmap.height,V);n.inferenceSize={width:a.width,height:a.height};const e=document.createElement("canvas");e.width=a.width,e.height=a.height;const o=e.getContext("2d",{willReadFrequently:!0});o.drawImage(n.imageBitmap,0,0,a.width,a.height);const{data:i}=o.getImageData(0,0,a.width,a.height),l=i.slice();w.postMessage({type:"infer",id:t,width:a.width,height:a.height,rgba:l},[l.buffer])}catch(a){n.inferring=!1,p(/memory|array buffer/i.test(String(a))?"Memoria insuficiente al preparar la imagen.":a.message||"Error al preparar la inferencia.","error"),f()}}w.onmessage=t=>{const a=t.data||{};if(a.type==="progress"){const e=typeof a.progress=="number"?a.progress:a.total?100*(a.loaded||0)/a.total:0;r.loadBar.style.width=`${Math.min(100,Math.max(0,e)).toFixed(1)}%`,r.loadText.textContent=`${a.status||"descarga"}: ${a.file||"modelo"} (${e.toFixed(0)}%)`}else if(a.type==="ready")n.loading=!1,n.modelReady=!0,r.loadBar.style.width="100%",r.loadText.textContent=a.reused?"Modelo ya en memoria (reutilizado).":`Modelo listo · Transformers.js ${Y} · WASM`,p("Modelo listo. Elige una imagen e infiere.","ok"),f();else if(a.type==="loadCancelled")n.loading=!1,f();else if(a.type==="result"){if(a.id!==n.inferId)return;n.inferring=!1,ye(a)}else if(a.type==="inferCancelled")a.id===n.inferId&&(n.inferring=!1,f());else if(a.type==="error"){if(a.phase==="load")n.loading=!1,r.loadProgress.hidden=!1,p(a.message||"Error de carga.","error");else if(a.phase==="infer"){if(a.id&&a.id!==n.inferId)return;n.inferring=!1,p(a.message||"Error de inferencia.","error")}else p(a.message||"Error del worker.","error");f()}};async function ye(t){const a=new Float32Array(t.predictedDepth),e=ne(a);if(!e.ok){p(e.message||"Mapa inválido.","error"),r.results.hidden=!1,r.results.dataset.status="error",f();return}n.relative=a,n.normalized=e.normalized,n.depthWidth=t.width,n.depthHeight=t.height,n.latencyMs=t.latencyMs,n.stats={min:e.min,max:e.max,finiteCount:e.finiteCount,pixelCount:e.pixelCount,nonConstant:e.nonConstant};const o=H(e.normalized,t.width,t.height),i=await q(o,t.width,t.height);n.depthPngUrl&&g.revoke(n.depthPngUrl),n.depthPngUrl=g.create(i);const l=document.createElement("canvas");l.width=t.width,l.height=t.height,l.getContext("2d").drawImage(n.imageBitmap,0,0,t.width,t.height);const s=await new Promise(c=>l.toBlob(u=>c(u),"image/jpeg",.92));n.originalCmpUrl&&g.revoke(n.originalCmpUrl),n.originalCmpUrl=g.create(s),r.cmpDepth.src=n.depthPngUrl,r.cmpOriginal.src=n.originalCmpUrl,r.cmpOverlay.style.width="50%",r.cmpSlider.value="50",document.querySelector('[data-stat="min"]').textContent=e.min.toFixed(4),document.querySelector('[data-stat="max"]').textContent=e.max.toFixed(4),document.querySelector('[data-stat="finite"]').textContent=String(e.finiteCount),document.querySelector('[data-stat="pixels"]').textContent=String(e.pixelCount),document.querySelector('[data-stat="nonConstant"]').textContent="sí",document.querySelector('[data-stat="latency"]').textContent=`${t.latencyMs.toFixed(0)} ms`,document.querySelector('[data-stat="runtime"]').textContent=t.runtime||"wasm",n.lastJson=le({relative:a,width:t.width,height:t.height,stats:n.stats,sourceKind:n.sourceKind,exampleId:n.exampleId,model:b,latencyMs:t.latencyMs,runtime:t.runtime||"wasm",inferenceSize:n.inferenceSize,originalSize:n.originalSize}),r.results.hidden=!1,r.results.dataset.status="ok",r.results.dataset.exampleId=n.exampleId||"",r.results.dataset.statsMin=String(e.min),r.results.dataset.statsMax=String(e.max),r.results.dataset.statsFinite=String(e.finiteCount),r.results.dataset.statsPixels=String(e.pixelCount),r.results.dataset.statsNonConstant="true",r.results.dataset.statsLatencyMs=String(Math.round(t.latencyMs)),r.results.dataset.runtime=t.runtime||"wasm",await Promise.all([r.cmpDepth.decode().catch(()=>{}),r.cmpOriginal.decode().catch(()=>{})]),r.cmpDepth.offsetHeight;const d=()=>{de(r.cmpDepth,r.cmpOriginal)};d(),requestAnimationFrame(d),window.addEventListener("resize",d,{passive:!0}),p(`Listo · ${t.width}×${t.height} · ${t.latencyMs.toFixed(0)} ms WASM · mayor valor ≈ más cerca`,"ok"),B(),r.parallaxToggle.checked=!1,z()?r.parallaxNote.textContent="Parallax desactivado por prefers-reduced-motion.":r.parallaxNote.textContent="Opcional. Arrastra el ratón sobre el lienzo cuando esté activo.",f()}function be(){if(z()){r.parallaxNote.textContent="Preferencia de movimiento reducido activa.",r.parallaxToggle.checked=!1;return}if(!(!n.imageBitmap||!n.normalized)){B(),r.parallaxCanvas.hidden=!1;try{if(n.parallax=ce(r.parallaxCanvas,{imageBitmap:n.imageBitmap,depthNorm:n.normalized,width:n.depthWidth,height:n.depthHeight,intensity:Number(r.parallaxIntensity.value)/100}),!n.parallax.supported){r.parallaxNote.textContent="WebGL2 no disponible: parallax deshabilitado.",r.parallaxToggle.checked=!1,r.parallaxCanvas.hidden=!0;return}const t=a=>{var l;const e=r.parallaxCanvas.getBoundingClientRect(),o=(a.clientX-e.left)/e.width*2-1,i=(a.clientY-e.top)/e.height*2-1;(l=n.parallax)==null||l.setOffset(o*.04,-i*.04)};r.parallaxCanvas.onpointermove=t,r.parallaxNote.textContent="Efecto artístico — agujeros por oclusión esperados; no es 3D fiel."}catch(t){r.parallaxNote.textContent=t.message||"No se pudo iniciar parallax.",r.parallaxToggle.checked=!1}}}function B(){n.parallax&&(n.parallax.dispose(),n.parallax=null),r.parallaxCanvas.hidden=!0,r.parallaxCanvas.onpointermove=null}function X({keepSelection:t}){B(),n.relative=null,n.normalized=null,n.stats=null,n.latencyMs=null,n.lastJson=null,n.depthPngUrl&&(g.revoke(n.depthPngUrl),n.depthPngUrl=null),n.originalCmpUrl&&(g.revoke(n.originalCmpUrl),n.originalCmpUrl=null),r.cmpOriginal.style.removeProperty("width"),r.cmpOriginal.style.removeProperty("height"),r.cmpDepth.removeAttribute("src"),r.cmpOriginal.removeAttribute("src"),r.results.hidden=!0,r.results.dataset.status="idle",delete r.results.dataset.exampleId;{n.imageBitmap&&(n.imageBitmap.close(),n.imageBitmap=null),n.previewUrl&&(g.revoke(n.previewUrl),n.previewUrl=null),n.sourceKind=null,n.exampleId=null,n.originalSize=null,n.inferenceSize=null,r.selectionLabel.textContent="Ninguna imagen seleccionada";for(const a of r.examples.querySelectorAll("button"))a.setAttribute("aria-pressed","false")}f()}window.addEventListener("pagehide",()=>{w.postMessage({type:"dispose"}),g.revokeAll(),n.imageBitmap&&n.imageBitmap.close(),B()});fe();f();p(`Modelo no cargado. Pin ${b.revision.slice(0,12)}…`);
|
index.html
CHANGED
|
@@ -8,8 +8,8 @@
|
|
| 8 |
content="DepthLab — profundidad relativa monocular en el navegador (WASM). Sin servidor de inferencia."
|
| 9 |
/>
|
| 10 |
<title>DepthLab</title>
|
| 11 |
-
<script type="module" crossorigin src="./assets/index-
|
| 12 |
-
<link rel="stylesheet" crossorigin href="./assets/index-
|
| 13 |
</head>
|
| 14 |
<body>
|
| 15 |
<a class="skip-link" href="#principal">Saltar al contenido</a>
|
|
|
|
| 8 |
content="DepthLab — profundidad relativa monocular en el navegador (WASM). Sin servidor de inferencia."
|
| 9 |
/>
|
| 10 |
<title>DepthLab</title>
|
| 11 |
+
<script type="module" crossorigin src="./assets/index-DZgGZDxK.js"></script>
|
| 12 |
+
<link rel="stylesheet" crossorigin href="./assets/index-Bs80IM8r.css">
|
| 13 |
</head>
|
| 14 |
<body>
|
| 15 |
<a class="skip-link" href="#principal">Saltar al contenido</a>
|