Spaces:
Running
Running
Download index.html from Shubhambhandari/Pathify: direct link, hf CLI and curl.
- Browser
- Download file 18.9 kB
-
https://huggingface.co/spaces/Shubhambhandari/Pathify/resolve/main/index.html
- Command line
-
hf download hf://spaces/Shubhambhandari/Pathify/index.html
-
curl -L -o index.html https://huggingface.co/spaces/Shubhambhandari/Pathify/resolve/main/index.html
18.9 kB
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"/> | |
| <meta name="viewport" content="width=device-width, initial-scale=1"/> | |
| <title>Pathify · second-reader QA</title> | |
| <script src="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.19.2/dist/ort.min.js"></script> | |
| <style> | |
| :root{ color-scheme:light; | |
| --bg:#f7f8fa; --card:#fff; --text:#111827; --muted:#6b7280; --line:#e5e7eb; | |
| --accent:#0f766e; --accentbg:#e6f4f1; | |
| --tumor:#b91c1c; --tumorbg:#fee2e2; --normal:#047857; --normalbg:#d1fae5; | |
| --warn:#b45309; --warnbg:#fef3c7; } | |
| *{box-sizing:border-box} | |
| body{margin:0;background:var(--bg);color:var(--text);font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;line-height:1.5} | |
| .wrap{max-width:760px;margin:0 auto;padding:22px 18px 44px} | |
| h1{font-size:20px;margin:0} | |
| .sub{color:var(--muted);font-size:13px;margin-top:3px} | |
| .chip{display:inline-block;font-size:11px;padding:3px 9px;border-radius:999px;background:var(--accentbg);color:var(--accent);margin-top:8px} | |
| .banner{margin:14px 0 16px;padding:10px 14px;border:1px solid var(--line);border-left:3px solid var(--accent);background:#fff;border-radius:8px;font-size:13px;color:var(--muted)} | |
| .banner b{color:var(--text)} | |
| .tabs{display:flex;gap:8px;margin-bottom:16px;flex-wrap:wrap} | |
| .tab{background:#fff;border:1px solid var(--line);color:var(--muted);padding:8px 14px;border-radius:10px;font-size:14px;cursor:pointer} | |
| .tab.active{color:var(--text);border-color:var(--accent);background:var(--accentbg)} | |
| .card{background:var(--card);border:1px solid var(--line);border-radius:14px;padding:18px;margin-top:14px} | |
| .stitle{font-size:15px;font-weight:600;margin-bottom:6px} | |
| .hint{font-size:12.5px;color:var(--muted);margin:2px 0 10px} | |
| textarea,input[type=text]{width:100%;border:1px solid var(--line);border-radius:10px;padding:10px 12px;font-size:14px;font-family:inherit;background:#fff;color:var(--text)} | |
| textarea{min-height:130px;resize:vertical} | |
| .btn{font-size:14px;padding:10px 16px;border-radius:10px;border:1px solid var(--line);background:#fff;color:var(--text);cursor:pointer} | |
| .btn:hover{border-color:var(--accent)} | |
| .btn.primary{background:var(--accent);border-color:var(--accent);color:#fff;font-weight:600} | |
| .btn.primary:disabled{opacity:.5;cursor:default} | |
| .pill{display:inline-block;font-size:13px;font-weight:600;padding:4px 12px;border-radius:999px} | |
| .pill.tumor{background:var(--tumorbg);color:var(--tumor)} | |
| .pill.normal{background:var(--normalbg);color:var(--normal)} | |
| .pill.uncertain{background:#f3f4f6;color:#4b5563} | |
| .cards{display:grid;grid-template-columns:repeat(2,1fr);gap:12px} | |
| .k{color:var(--muted);font-size:12px} .v{font-size:22px;font-weight:600;margin-top:4px} | |
| .imgs{display:flex;gap:14px;flex-wrap:wrap;margin-top:12px} | |
| .imgs figure{margin:0;text-align:center} | |
| .imgs img,.imgs canvas{width:150px;height:150px;object-fit:cover;border:1px solid var(--line);border-radius:10px;display:block} | |
| figcaption{font-size:11px;color:var(--muted);margin-top:4px} | |
| .verdict{border-radius:14px;padding:16px;margin-top:14px;border:1.5px solid} | |
| .verdict.ok{background:var(--normalbg);border-color:#a7f3d0} | |
| .verdict.flag{background:var(--tumorbg);border-color:#fca5a5} | |
| .verdict.soft{background:var(--warnbg);border-color:#f59e0b} | |
| .foot{color:var(--muted);font-size:12px;margin-top:20px;line-height:1.6} | |
| .muted{color:var(--muted)} | |
| .spin{display:inline-block;width:14px;height:14px;border:2px solid #cbd5e1;border-top-color:var(--accent);border-radius:50%;animation:s .7s linear infinite;vertical-align:-2px;margin-right:6px} | |
| @keyframes s{to{transform:rotate(360deg)}} | |
| .term{display:inline-block;font-size:12px;padding:3px 9px;border-radius:999px;margin:4px 6px 0 0} | |
| </style> | |
| </head> | |
| <body> | |
| <div class="wrap"> | |
| <h1>Pathify · second-reader QA</h1> | |
| <div class="sub">An AI safety-net for the pathology sign-out. Quality assurance, not diagnosis.</div> | |
| <span class="chip" id="modelchip">loading model…</span> | |
| <div class="banner"><b>Assist, not replace.</b> Pathify gives an independent read and flags cases worth a second look. Everything runs in your browser; images never leave your device.</div> | |
| <div class="tabs"> | |
| <button class="tab active" data-t="analyze">Analyze a case</button> | |
| <button class="tab" data-t="report">Report check</button> | |
| <button class="tab" data-t="model">Model</button> | |
| </div> | |
| <div id="view"></div> | |
| <div class="foot">Pathify outputs re-check recommendations only; it does not diagnose. Runs on-device in the browser (no server). Model: ResNet18 trained on open histopathology data.</div> | |
| </div> | |
| <script> | |
| ; | |
| const MEAN=[0.485,0.456,0.406], STD=[0.229,0.224,0.225]; | |
| let SESSION=null, META={temperature:1.0, metrics:{}}; | |
| const $=s=>document.querySelector(s), el=h=>{const d=document.createElement("div");d.innerHTML=h.trim();return d.firstElementChild;}; | |
| const pill=r=>`<span class="pill ${r==='tumor'?'tumor':r==='normal'?'normal':'uncertain'}">${r==='tumor'?'tumour':r}</span>`; | |
| async function loadModel(){ | |
| try{ | |
| ort.env.wasm.wasmPaths="https://cdn.jsdelivr.net/npm/onnxruntime-web@1.19.2/dist/"; | |
| META=await (await fetch("model_meta.json")).json(); | |
| SESSION=await ort.InferenceSession.create("model.onnx"); | |
| $("#modelchip").textContent="model ready · AUROC "+((META.metrics&&META.metrics.test_auroc)?META.metrics.test_auroc.toFixed(2):"—"); | |
| }catch(e){ $("#modelchip").textContent="model failed to load"; console.error(e); } | |
| } | |
| /* preprocess a canvas/image to a 96x96 normalized CHW tensor */ | |
| function toTensor(src){ | |
| const c=document.createElement("canvas"); c.width=96;c.height=96; | |
| c.getContext("2d").drawImage(src,0,0,96,96); | |
| const d=c.getContext("2d").getImageData(0,0,96,96).data, N=96*96, arr=new Float32Array(3*N); | |
| for(let i=0;i<N;i++){ | |
| arr[i] =(d[i*4]/255-MEAN[0])/STD[0]; | |
| arr[N+i] =(d[i*4+1]/255-MEAN[1])/STD[1]; | |
| arr[2*N+i] =(d[i*4+2]/255-MEAN[2])/STD[2]; | |
| } | |
| return new ort.Tensor("float32",arr,[1,3,96,96]); | |
| } | |
| async function probTumour(src){ | |
| const out=await SESSION.run({input:toTensor(src)}); | |
| const lg=out[Object.keys(out)[0]].data, T=META.temperature||1; | |
| const a=lg[0]/T, b=lg[1]/T, m=Math.max(a,b), ea=Math.exp(a-m), eb=Math.exp(b-m); | |
| return eb/(ea+eb); | |
| } | |
| /* stain heuristic on a canvas -> {frac,susp} and paints red overlay canvas */ | |
| function stain(src,S){ | |
| S=S||160; const c=document.createElement("canvas");c.width=S;c.height=S; | |
| const g=c.getContext("2d"); g.drawImage(src,0,0,S,S); | |
| const im=g.getImageData(0,0,S,S), d=im.data; let nuc=0,tis=0; | |
| for(let i=0;i<d.length;i+=4){const r=d[i],gr=d[i+1],b=d[i+2],br=(r+gr+b)/3; if(br>245)continue; tis++; | |
| if(b>70&&r>55&&gr<r-12&&gr<b-12&&br<175){nuc++; d[i]=220;d[i+1]=30;d[i+2]=30;}} | |
| g.putImageData(im,0,0); | |
| const frac=tis?nuc/tis:0; | |
| return {frac, susp:Math.max(0,Math.min(1,(frac-0.06)/0.22)), overlay:c}; | |
| } | |
| function combine(prob,susp,read){ | |
| const agree=(read==="tumor"&&susp>=0.4)||(read==="normal"&&susp<=0.3); | |
| if(agree) return {read, conf:Math.min(0.99,Math.max(prob,1-prob)+0.05), note:"Model and stain check agree."}; | |
| const bl=0.35*prob+0.65*susp; | |
| let r,conf; | |
| if(bl>=0.6){r="tumor";conf=Math.min(0.9,0.5+0.5*(bl-0.5)/0.5);} | |
| else if(bl<=0.4){r="normal";conf=Math.min(0.9,0.5+0.5*(0.5-bl)/0.5);} | |
| else{r="uncertain";conf=0.5;} | |
| return {read:r, conf, note:"Model and stain check differ; blended read. Needs review."}; | |
| } | |
| /* ---------------- Analyze view ---------------- */ | |
| function analyzeView(){ | |
| $("#view").innerHTML=`<div class="card"> | |
| <div class="stitle">Upload an H&E image</div> | |
| <div class="hint">A small patch or a whole slide. Runs on-device.</div> | |
| <input type="file" id="imgf" accept="image/*"> | |
| <button class="btn primary" id="run" style="margin-left:10px" disabled>Analyze</button> | |
| <span id="st" class="muted" style="font-size:13px;margin-left:8px"></span> | |
| <div id="res"></div></div>`; | |
| let img=null; | |
| $("#imgf").onchange=e=>{const f=e.target.files[0]; if(!f)return; const im=new Image(); | |
| im.onload=()=>{img=im; $("#run").disabled=!SESSION;}; im.src=URL.createObjectURL(f);}; | |
| $("#run").onclick=async()=>{ | |
| if(!img||!SESSION)return; $("#st").innerHTML='<span class="spin"></span>Analyzing…'; $("#res").innerHTML=""; | |
| const big=Math.min(img.width,img.height)>=192; | |
| let out; | |
| if(big) out=await analyzeSlide(img); else out=await analyzePatch(img); | |
| $("#st").textContent=""; $("#res").innerHTML=""; $("#res").appendChild(out); | |
| }; | |
| } | |
| async function analyzePatch(img){ | |
| const p=await probTumour(img), read=(p>=0.6?"tumor":p<=0.4?"normal":"uncertain"); | |
| const s=stain(img); const cm=combine(p,s.susp,read); | |
| const up=document.createElement("canvas");up.width=150;up.height=150;up.getContext("2d").drawImage(img,0,0,150,150); | |
| const box=el(`<div> | |
| <div class="verdict ${cm.read==='tumor'?'flag':cm.read==='normal'?'ok':'soft'}"> | |
| <div style="font-size:17px;font-weight:600">${pill(cm.read)} <span class="muted" style="font-weight:400;font-size:13px">${(cm.conf*100).toFixed(0)}% · ${cm.note}</span></div></div> | |
| <div class="cards" style="margin-top:12px"> | |
| <div class="card"><div class="k">Trained model</div><div class="v">${pill(read)}</div><div class="muted" style="font-size:12px;margin-top:6px">P(tumour) ${(p*100).toFixed(0)}%</div></div> | |
| <div class="card"><div class="k">Stain check</div><div class="v">${(s.susp*100).toFixed(0)}%</div><div class="muted" style="font-size:12px;margin-top:6px">dense nuclei ${(s.frac*100).toFixed(0)}% of tissue</div></div> | |
| </div> | |
| <div class="imgs"><figure><span class="up"></span><figcaption>uploaded</figcaption></figure> | |
| <figure><span class="ov"></span><figcaption>stain highlight</figcaption></figure></div></div>`); | |
| box.querySelector(".up").replaceWith(up); s.overlay.style.width="150px";s.overlay.style.height="150px";s.overlay.style.borderRadius="10px";s.overlay.style.border="1px solid var(--line)"; | |
| box.querySelector(".ov").replaceWith(s.overlay); | |
| return box; | |
| } | |
| async function analyzeSlide(img){ | |
| const S=Math.min(768,Math.max(img.width,img.height)); const scale=S/Math.max(img.width,img.height); | |
| const W=Math.round(img.width*scale),H=Math.round(img.height*scale); | |
| const base=document.createElement("canvas");base.width=W;base.height=H;base.getContext("2d").drawImage(img,0,0,W,H); | |
| const tile=96, cols=Math.floor(W/tile), rows=Math.floor(H/tile), probs=[]; | |
| const heat=document.createElement("canvas");heat.width=cols*12;heat.height=rows*12;const hg=heat.getContext("2d"); | |
| hg.fillStyle="#0f1419";hg.fillRect(0,0,heat.width,heat.height); | |
| const bg=base.getContext("2d"); | |
| for(let r=0;r<rows;r++)for(let c=0;c<cols;c++){ | |
| const t=document.createElement("canvas");t.width=tile;t.height=tile; | |
| t.getContext("2d").drawImage(base,c*tile,r*tile,tile,tile,0,0,tile,tile); | |
| const dd=t.getContext("2d").getImageData(0,0,tile,tile).data; let br=0; for(let i=0;i<dd.length;i+=4)br+=(dd[i]+dd[i+1]+dd[i+2])/3; br/=(tile*tile); | |
| if(br>235)continue; // background | |
| const p=await probTumour(t); probs.push(p); | |
| let col; if(p<0.5){const u=p/0.5;col=`rgb(${29+u*160|0},${158+u*40|0},${117-u*80|0})`;}else{const u=(p-0.5)/0.5;col=`rgb(245,${199-u*160|0},${39+u*36|0})`;} | |
| hg.fillStyle=col; hg.fillRect(c*12,r*12,12,12); | |
| } | |
| probs.sort((a,b)=>b-a); const k=Math.max(4,Math.floor(0.02*probs.length))||1; | |
| const score=probs.length?probs.slice(0,k).reduce((a,b)=>a+b,0)/k:0; | |
| const read=score>=0.6?"tumor":score<=0.4?"normal":"uncertain"; | |
| const s=stain(img); const cm=combine(score,s.susp,read); | |
| const up=document.createElement("canvas");up.width=150;up.height=150;up.getContext("2d").drawImage(img,0,0,150,150); | |
| const box=el(`<div> | |
| <div class="verdict ${cm.read==='tumor'?'flag':cm.read==='normal'?'ok':'soft'}"> | |
| <div style="font-size:17px;font-weight:600">${pill(cm.read)} <span class="muted" style="font-weight:400;font-size:13px">${(cm.conf*100).toFixed(0)}% · whole slide · ${cm.note}</span></div> | |
| <div class="muted" style="font-size:12px;margin-top:6px">slide score ${(score*100).toFixed(0)}% · ${probs.filter(p=>p>=0.5).length} suspicious of ${probs.length} tissue tiles</div></div> | |
| <div class="imgs"><figure><span class="up"></span><figcaption>uploaded</figcaption></figure> | |
| <figure><span class="ht"></span><figcaption>tumour heatmap</figcaption></figure></div></div>`); | |
| box.querySelector(".up").replaceWith(up); | |
| heat.style.width="150px";heat.style.height="150px";heat.style.borderRadius="10px";heat.style.border="1px solid var(--line)";heat.style.imageRendering="pixelated"; | |
| box.querySelector(".ht").replaceWith(heat); | |
| return box; | |
| } | |
| /* ---------------- Report check (client-side) ---------------- */ | |
| const CATS={benign:{label:"benign / negative",rank:0,bg:"#d1fae5",fg:"#047857"},atypical:{label:"atypical / suspicious",rank:1,bg:"#fef3c7",fg:"#b45309"},dysplasia:{label:"dysplasia / pre-malignant",rank:2,bg:"#fef3c7",fg:"#b45309"},malignant:{label:"malignant / carcinoma",rank:3,bg:"#fee2e2",fg:"#b91c1c"},nondiag:{label:"non-diagnostic",rank:null,bg:"#f3f4f6",fg:"#4b5563"},uncertain:{label:"uncertain",rank:null,bg:"#f3f4f6",fg:"#4b5563"}}; | |
| const catPill=c=>{const x=CATS[c]||CATS.uncertain;return `<span style="background:${x.bg};color:${x.fg};padding:3px 10px;border-radius:999px;font-size:13px;font-weight:600">${x.label}</span>`;}; | |
| function scoreCats(t){t=" "+(t||"").toLowerCase().replace(/\s+/g," ")+" ";const s={malignant:0,dysplasia:0,atypical:0,benign:0,nondiag:0};const add=(k,w)=>s[k]+=w; | |
| [[/non[- ]?diagnostic/g,2],[/insufficient|inadequate|scant|acellular/g,1.5],[/cannot be (assessed|evaluated)/g,1.5]].forEach(([re,w])=>{const m=t.match(re);if(m)add("nondiag",w*m.length);}); | |
| const neg=/(no|negative for|without|absence of|free of)\s+(evidence of\s+)?((?:\w+\s+){0,2})(malignan\w*|tumou?rs?|carcinoma|dysplasi\w*|atypi\w*|neoplas\w*)/g;const ng=t.match(neg);if(ng){ng.forEach(()=>add("benign",3));t=t.replace(neg," ");} | |
| [[/benign/g,2.5],[/within normal limits/g,2.5],[/unremarkable/g,1.5],[/reactive/g,1],[/no dysplasia/g,2],[/preserved (crypt )?architecture/g,1.5]].forEach(([re,w])=>{const m=t.match(re);if(m)add("benign",w*m.length);}); | |
| [[/adenocarcinoma/g,4],[/carcinoma/g,3],[/sarcoma/g,3],[/malignan\w*/g,3],[/invasiv\w*|invasion/g,2],[/metasta\w*/g,3]].forEach(([re,w])=>{const m=t.match(re);if(m)add("malignant",w*m.length);}); | |
| [[/high[- ]grade dysplasia/g,3],[/low[- ]grade dysplasia/g,2],[/dysplas\w*/g,1.5],[/intraepithelial neoplasi\w*/g,2]].forEach(([re,w])=>{const m=t.match(re);if(m)add("dysplasia",w*m.length);}); | |
| [[/atypi\w*/g,1.5],[/suspicious/g,2],[/cannot exclude|cannot rule out/g,1.5],[/indeterminate/g,1.5]].forEach(([re,w])=>{const m=t.match(re);if(m)add("atypical",w*m.length);}); | |
| return s;} | |
| function classifyReport(t){let s=scoreCats(t);const idx=(t||"").toLowerCase().search(/impression|diagnosis|conclusion/);if(idx>=0){const si=scoreCats(t.slice(idx));for(const k in s)s[k]+=2*si[k];} | |
| const axis=["malignant","dysplasia","atypical","benign"];const total=Object.values(s).reduce((a,b)=>a+b,0);if(total===0)return{cat:"uncertain",conf:0.45}; | |
| const axisSum=axis.reduce((a,k)=>a+s[k],0);if(s.nondiag>0&&s.nondiag>=axisSum)return{cat:"nondiag",conf:Math.min(0.95,s.nondiag/total+0.3)}; | |
| const so=axis.map(k=>[k,s[k]]).sort((a,b)=>b[1]-a[1]);if(so[0][1]===0)return{cat:"uncertain",conf:0.5}; | |
| return{cat:so[0][0],conf:Math.min(0.96,Math.max(0.55,0.55+0.41*(so[0][1]-so[1][1])/(axisSum||1)))};} | |
| function reportView(){ | |
| $("#view").innerHTML=`<div class="card"><div class="stitle">Paste the pathologist's report</div> | |
| <textarea id="rep" placeholder="Paste the report or impression…"></textarea> | |
| <div style="margin-top:8px"><button class="btn" id="ex">Load example</button></div></div> | |
| <div class="card"><div class="stitle">Pathologist's conclusion</div> | |
| <input type="text" id="concl" placeholder='e.g. "benign, no malignancy" or "invasive carcinoma"'></div> | |
| <button class="btn primary" id="rc" style="margin-top:12px">Run report check</button><div id="rres"></div>`; | |
| $("#ex").onclick=()=>{$("#rep").value="IMPRESSION: Sections show irregular cribriform glands with hyperchromatic, pleomorphic nuclei and desmoplastic stroma; findings consistent with invasive adenocarcinoma.";}; | |
| $("#rc").onclick=()=>{ | |
| const rep=$("#rep").value.trim(); if(!rep){$("#rres").innerHTML='<div class="hint">Paste a report first.</div>';return;} | |
| const a=classifyReport(rep), c=$("#concl").value.trim()?classifyReport($("#concl").value).cat:null; | |
| let v=""; | |
| if(c){ if(a.cat==="uncertain"){v=`<div class="verdict soft"><b>Pathify is not sure.</b> Add more text or confirm with the pathologist.</div>`;} | |
| else if(a.cat==="nondiag"||c==="nondiag"){v=`<div class="verdict soft"><b>Adequacy mismatch.</b> Confirm sample adequacy.</div>`;} | |
| else{const gap=Math.abs(CATS[a.cat].rank-CATS[c].rank); | |
| v=`<div class="verdict ${gap===0?'ok':gap===1?'soft':'flag'}"><div>Pathologist ${catPill(c)} vs Pathify ${catPill(a.cat)}</div> | |
| <div style="margin-top:6px;font-weight:600">${gap===0?'Matches. No discrepancy.':gap===1?'Borderline difference. Quick confirm advised.':'Clear discrepancy. Second look needed.'}</div></div>`;}} | |
| $("#rres").innerHTML=`<div class="card"><div class="stitle">Pathify's read: ${catPill(a.cat)} <span class="muted" style="font-weight:400">· ${(a.conf*100).toFixed(0)}%</span></div> | |
| <div class="hint">Reading the words in the report (not tissue).</div></div>${v}`; | |
| }; | |
| } | |
| /* ---------------- Model view ---------------- */ | |
| function modelView(){ | |
| const base=352140, contrib=parseInt(localStorage.getItem("pathify_contrib")||"0",10); | |
| const auroc=(META.metrics&&META.metrics.test_auroc)?META.metrics.test_auroc.toFixed(3):"—"; | |
| $("#view").innerHTML=`<div class="cards"> | |
| <div class="card"><div class="k">Images in the database</div><div class="v">${(base+contrib).toLocaleString()}</div><div class="hint">base ${base.toLocaleString()} + your ${contrib}</div></div> | |
| <div class="card"><div class="k">Model score (AUROC)</div><div class="v">${auroc}</div><div class="hint">held-out test</div></div> | |
| </div> | |
| <div class="card"><div class="stitle">About this model</div> | |
| <div class="hint">ResNet18 trained on open histopathology data (PathMNIST + PatchCamelyon), running in your browser via ONNX. This static site has no server, so contributions are counted locally in this browser. For shared, persistent learning across users, run the full server version.</div></div>`; | |
| } | |
| /* ---------------- shell ---------------- */ | |
| document.querySelectorAll(".tab").forEach(b=>b.onclick=()=>{ | |
| document.querySelectorAll(".tab").forEach(x=>x.classList.remove("active")); b.classList.add("active"); | |
| ({analyze:analyzeView,report:reportView,model:modelView})[b.dataset.t](); | |
| }); | |
| analyzeView(); loadModel(); | |
| </script> | |
| </body> | |
| </html> | |