/* PathoAI — pathologist/intern app (single-file React). Main flow is ONE guided path: upload a case -> see the whole-slide overview and verdict -> zoom into the flagged patches -> confirm the read (which also teaches the model). The batch worklists live under a secondary "Review queue" tab. PathoAI never changes a sign-out and never diagnoses. */ const {useState, useEffect, useCallback} = React; const POST = (u, b) => fetch(u, {method:"POST", headers:{"Content-Type":"application/json"}, body:JSON.stringify(b)}).then(r=>r.json()); const api = { summary: () => fetch("/api/summary").then(r=>r.json()), worklist: () => fetch("/api/worklist").then(r=>r.json()), settings: (b) => POST("/api/settings", b), decision: (b) => POST("/api/decision", b), slideSummary: () => fetch("/api/slides/summary").then(r=>r.json()), slideWorklist: () => fetch("/api/slides/worklist").then(r=>r.json()), slideSettings: (b) => POST("/api/slides/settings", b), slideDecision: (b) => POST("/api/slides/decision", b), analyzeImage: (image) => POST("/api/analyze-image", {image}), feedback: (image, label, autoLearn) => POST("/api/feedback", {image, label, auto_learn: !!autoLearn}), feedbackStats: () => fetch("/api/feedback/stats").then(r=>r.json()), loadModel: (model) => POST("/api/load-model", {model}), modelInfo: () => fetch("/api/model-info").then(r=>r.json()), retrain: (epochs) => POST("/api/retrain", {epochs}), }; const pct = (x) => (100*x).toFixed(1) + "%"; const Read = ({v}) => {v}; const Card = ({k, v, sub}) =>
{k}
{v} {sub && {sub}}
; const readLabel = (r)=> r==="tumor"?"tumour":r; const readPill = (r)=> {readLabel(r)}; const IMG = {width:150,height:150,objectFit:"cover",border:"1px solid var(--line)",borderRadius:10}; /* ---- text report classifier (client-side, 5 buckets, negation-aware) ---- */ const CATS = { benign:{label:"benign / negative",rank:0,bg:"#0f241d",fg:"#a7f3d0"}, atypical:{label:"atypical / suspicious",rank:1,bg:"#2a1c0a",fg:"#fcd34d"}, dysplasia:{label:"dysplasia / pre-malignant",rank:2,bg:"#2a1c0a",fg:"#fcd34d"}, malignant:{label:"malignant / carcinoma",rank:3,bg:"#2a1414",fg:"#fca5a5"}, nondiag:{label:"non-diagnostic / insufficient",rank:null,bg:"#1c242e",fg:"#8b98a5"}, uncertain:{label:"uncertain",rank:null,bg:"#1c242e",fg:"#8b98a5"}, }; const catPill = (c)=>{ const x=CATS[c]||CATS.uncertain; return {x.label}; }; function scoreCats(t){ t=" "+(t||"").toLowerCase().replace(/\s+/g," ")+" "; const s={malignant:0,dysplasia:0,atypical:0,benign:0,nondiag:0}; const terms=[]; const add=(k,w,lab,side)=>{s[k]+=w; terms.push({label:lab,w,side});}; [[/non[- ]?diagnostic/g,2,"non-diagnostic"],[/insufficient|inadequate|scant|paucicellular|acellular/g,1.5,"insufficient sample"],[/cannot be (assessed|evaluated|interpreted)/g,1.5,"cannot be assessed"],[/no (epithelial|diagnostic) (cells|material)/g,1.5,"no diagnostic material"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("nondiag",w*m.length,lab,"nd");}); const negMal=/(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 neg=t.match(negMal); if(neg){neg.forEach(x=>add("benign",3,'"'+x.trim()+'"',"ben")); t=t.replace(negMal," ");} [[/benign/g,2.5,"benign"],[/within normal limits/g,2.5,"within normal limits"],[/unremarkable/g,1.5,"unremarkable"],[/reactive/g,1,"reactive changes"],[/preserved (crypt )?architecture/g,1.5,"preserved architecture"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("benign",w*m.length,lab,"ben");}); [[/adenocarcinoma/g,4,"adenocarcinoma"],[/carcinoma/g,3,"carcinoma"],[/sarcoma/g,3,"sarcoma"],[/malignan\w*/g,3,"malignant"],[/invasiv\w*|invasion/g,2,"invasion"],[/metasta\w*/g,3,"metastasis"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("malignant",w*m.length,lab,"mal");}); [[/high[- ]grade dysplasia/g,3,"high grade dysplasia"],[/low[- ]grade dysplasia/g,2,"low grade dysplasia"],[/dysplas\w*/g,1.5,"dysplasia"],[/intraepithelial neoplasi\w*/g,2,"intraepithelial neoplasia"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("dysplasia",w*m.length,lab,"warn");}); [[/atypi\w*/g,1.5,"atypia"],[/suspicious/g,2,"suspicious"],[/cannot exclude|cannot rule out/g,1.5,"cannot exclude malignancy"],[/indeterminate/g,1.5,"indeterminate"]].forEach(([re,w,lab])=>{const m=t.match(re); if(m)add("atypical",w*m.length,lab,"warn");}); return {s,terms}; } function classifyReport(t){ const base=scoreCats(t); const s={...base.s}; const idx=(t||"").toLowerCase().search(/impression|diagnosis|conclusion/); if(idx>=0){const si=scoreCats(t.slice(idx)).s; 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,terms:base.terms}; 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),terms:base.terms}; const sorted=axis.map(k=>[k,s[k]]).sort((a,b)=>b[1]-a[1]); const topK=sorted[0][0], topV=sorted[0][1], secV=sorted[1][1]; if(topV===0) return {cat:"uncertain",conf:0.5,terms:base.terms}; return {cat:topK,conf:Math.min(0.96,Math.max(0.55,0.55+0.41*(topV-secV)/(axisSum||1))),terms:base.terms}; } function Actions({onConfirm, onAmend, note, setNote}) { return
setNote(e.target.value)} style={{background:"var(--panel2)",border:"1px solid var(--line)",color:"var(--text)",borderRadius:6,padding:"5px 7px",fontSize:12,width:110}}/>
; } const Tag = ({d}) => {d === "amend" ? "Amended" : "Sign-out confirmed"}; /* =================== GUIDED FLOW (the front door) =================== */ function Step({n, title, children}) { return
{n}
{title &&
{title}
}{children}
; } function GuidedFlow() { const [img, setImg] = useState(null); const [res, setRes] = useState(null); const [busy, setBusy] = useState(false); const [stats, setStats] = useState(null); const [decision, setDecision] = useState(null); const [zoom, setZoom] = useState(null); const [modelMsg, setModelMsg] = useState("Checking model…"); const [retrainMsg, setRetrainMsg] = useState(""); useEffect(() => { api.feedbackStats().then(setStats); api.modelInfo().then(mi => { const a = mi.metrics && mi.metrics.test_auroc; if (mi.source === "trained") setModelMsg("Using the bundled trained model" + (a ? " · AUROC " + a.toFixed(2) : "") + "."); else if (mi.source === "uploaded") setModelMsg("Using your loaded model" + (a ? " · AUROC " + a.toFixed(2) : "") + "."); else setModelMsg("Using the built-in demo model (train and load one for real reads)."); }).catch(()=>setModelMsg("")); }, []); const loadModel = (e) => { const f=e.target.files[0]; if(!f)return; setModelMsg("Loading "+f.name+"…"); const r=new FileReader(); r.onload=async()=>{ try{ const res=await api.loadModel(r.result); const a=res.metrics&&res.metrics.test_auroc; setModelMsg("Loaded "+f.name+(a?" · test AUROC "+a.toFixed(2):"")+". Analyze an image to use it."); }catch(err){ setModelMsg("Could not load that file."); } }; r.readAsDataURL(f); }; const pick = (e) => { const f=e.target.files[0]; if(!f)return; const r=new FileReader(); r.onload=()=>{ setImg(r.result); setRes(null); setDecision(null); }; r.readAsDataURL(f); }; const run = async () => { if(!img)return; setBusy(true); setRes(null); setDecision(null); try{ setRes(await api.analyzeImage(img)); } finally{ setBusy(false); } }; const confirmRead = async (label) => { const matched = res.combined.read===label; setDecision({label, matched, saving:true}); const r = await api.feedback(img, label, true); // auto-learn on if (r.stats) setStats(r.stats); setDecision({label, matched, learned: r.retrained, auroc: r.val_auroc}); if (r.retrained) setModelMsg("Model updated from submissions"+(r.val_auroc?" · val AUROC "+r.val_auroc:"")+" (saved)."); }; const reset = () => { setImg(null); setRes(null); setDecision(null); }; const retrain = async () => { setRetrainMsg("Fine-tuning on your submitted labels… this can take a minute."); try { const r = await api.retrain(3); setModelMsg("Retrained on your labels · val AUROC " + r.val_auroc + ". Now in use."); setRetrainMsg("Done. Trained on " + r.n_train + " images; updated model saved and live."); api.feedbackStats().then(setStats); } catch(e) { setRetrainMsg("Need at least 3 'normal' and 3 'tumour' labels before fine-tuning."); } }; const verdictColor = (r)=> r==="tumor"?"var(--tumor,#f87171)":r==="normal"?"var(--ok,#34d399)":"var(--warn,#f59e0b)"; return <>
{modelMsg}
Choose an H&E image (a small patch or a whole slide). Nothing leaves this machine.
{img && } {img && !res &&
}
{res && <>
{readPill(res.combined.read)} combined verdict · {(100*res.combined.confidence).toFixed(0)}% · {res.combined.agree?"model + stain agree":"needs review"}
{res.combined.note}
Trained model
{readPill(res.model.read)}
P(tumour) {(100*res.model.prob_tumor).toFixed(0)}%{res.model.uncertainty!=null?` · uncertainty ${(100*res.model.uncertainty).toFixed(0)}%`:""}
Stain check
{(100*res.stain.suspicion).toFixed(0)}%
dense nuclei {(100*res.stain.frac).toFixed(0)}% of tissue
uploaded
{res.mode==="slide"?"tumour heatmap":"model attention"}
stain highlight
{res.mode==="slide" && res.tiles && res.tiles.length>0 &&
The specific patches the model reacted to most, with what it looked at (Grad-CAM). This is the "show me where" step.
{res.tiles.map((t,i)=>
tile ({t.row},{t.col}) · P(tumour) {(100*t.prob).toFixed(0)}%
)}
} {!decision ? <>
What is your read? This is recorded, and your answer becomes a training example so the model improves.
: <>
You marked {readPill(decision.label)}. {decision.matched ? PathoAI agreed, no discrepancy. : This differs from PathoAI's read, exactly the kind of case worth a second look. Your correction now trains it.}
{decision.saving &&
Saving and updating the model…
} {decision.learned &&
Saved and folded into the model{decision.auroc?` (val AUROC ${decision.auroc})`:""}. It will use this from the next case on.
} {!decision.saving && !decision.learned && stats && (stats.normal<3||stats.tumor<3) &&
Saved. Auto-learning kicks in once there are 3+ of each label (have {stats.normal} normal, {stats.tumor} tumour).
}
}
} {zoom &&
setZoom(null)}>
e.stopPropagation()}> zoom
} ; } /* =================== Batch worklists (secondary "Review queue") =================== */ function PatchesView() { const [summary, setSummary] = useState(null); const [items, setItems] = useState([]); const [tau, setTau] = useState(0.90); const [zoom, setZoom] = useState(null); const [notes, setNotes] = useState({}); const refresh = useCallback(async () => { const [s, w] = await Promise.all([api.summary(), api.worklist()]); setSummary(s); setItems(w.items || []); if (s && typeof s.tau === "number") setTau(s.tau); }, []); useEffect(() => { refresh(); }, [refresh]); const applyTau = async (v) => { setTau(v); const s = await api.settings({tau:v}); if (s.summary) setSummary(s.summary); const w = await api.worklist(); setItems(w.items||[]); }; const decide = async (id, a) => { await api.decision({case_id:id, action:a, note:notes[id]||""}); refresh(); }; if (!summary) return
Loading patch QA…
; const pending = items.filter(i => !i.decision); return <>
setTau(parseFloat(e.target.value))} onMouseUp={e=>applyTau(parseFloat(e.target.value))} onTouchEnd={e=>applyTau(parseFloat(e.target.value))} /> τ = {Number(tau).toFixed(3)} lower τ → catch more · higher τ → shorter queue
{pending.length === 0 ?
Nothing left to re-check at this threshold. ✅
: {items.map(it => )}
#PatchCaseSign-outModel readsConfidenceRe-review outcome
{it.priority} setZoom(it)} alt="patch"/> {it.case_id}
{it.model_confidence.toFixed(3)}
{it.decision ? : decide(it.case_id,"confirm_signout")} onAmend={()=>decide(it.case_id,"amend")} note={notes[it.case_id]} setNote={v=>setNotes({...notes,[it.case_id]:v})}/>}
} {zoom &&
setZoom(null)}>
e.stopPropagation()}>
{zoom.case_id} setZoom(null)}>✕
patch
patch
grad-cam
model attention (Grad-CAM)

{zoom.reason}

} ; } function SlidesView() { const [summary, setSummary] = useState(null); const [items, setItems] = useState([]); const [tau, setTau] = useState(0.70); const [notes, setNotes] = useState({}); const [zoom, setZoom] = useState(null); const refresh = useCallback(async () => { const [s, w] = await Promise.all([api.slideSummary(), api.slideWorklist()]); setSummary(s); setItems(w.items || []); if (s && typeof s.slide_tau === "number") setTau(s.slide_tau); }, []); useEffect(() => { refresh(); }, [refresh]); const applyTau = async (v) => { setTau(v); await api.slideSettings({tau:v}); refresh(); }; const decide = async (id, a) => { await api.slideDecision({slide_id:id, action:a, note:notes[id]||""}); refresh(); }; if (!summary) return
Loading slide QA…
; return <>
setTau(parseFloat(e.target.value))} onMouseUp={e=>applyTau(parseFloat(e.target.value))} onTouchEnd={e=>applyTau(parseFloat(e.target.value))} /> τ = {Number(tau).toFixed(3)} heatmap: green = normal, red = suspicious tissue
{items.length === 0 ?
No slides flagged at this threshold. ✅
:
{items.map(it =>
setZoom(it)} alt="heatmap"/>
#{it.priority} · {it.slide_id} score {it.slide_score.toFixed(2)}
sign-out  vs  model
{it.n_tumor_tiles} suspicious / {it.n_tissue_tiles} tissue tiles · conf {it.confidence.toFixed(2)}
{it.decision ? : decide(it.slide_id,"confirm_signout")} onAmend={()=>decide(it.slide_id,"amend")} note={notes[it.slide_id]} setNote={v=>setNotes({...notes,[it.slide_id]:v})}/>}
)}
} {zoom &&
setZoom(null)}>
e.stopPropagation()}>
{zoom.slide_id} setZoom(null)}>✕
heatmap

{zoom.reason}

} ; } function ReviewQueue() { const [q, setQ] = useState("patches"); return <>
Demo review queues: a batch of already signed-out cases; PathoAI lists only the ones it disagrees with.
{q==="patches" ? : } ; } /* =================== Report check (text, client-side) =================== */ const FIELD = {width:"100%",background:"var(--panel2)",border:"1px solid var(--line)",color:"var(--text)",borderRadius:8,padding:"9px 11px",fontSize:14,fontFamily:"inherit"}; const EXAMPLE_RPT = "SPECIMEN: Sigmoid colon, biopsy.\nMICROSCOPIC: Irregular cribriform glands with hyperchromatic, pleomorphic nuclei and desmoplastic stroma; foci suggest submucosal invasion.\nIMPRESSION: Findings consistent with invasive adenocarcinoma."; function ReportCheck() { const [report, setReport] = useState(""); const [concl, setConcl] = useState(null); const [free, setFree] = useState(""); const [res, setRes] = useState(null); const run = () => { if(!report.trim()){ setRes({error:true}); return; } setRes(classifyReport(report)); }; const patho = free.trim() ? classifyReport(free).cat : concl; const segBtn = (id) => ; const verdict = () => { if(!res || res.error) return null; const a=res.cat; if(!patho) return
Read only. Pick or type the pathologist's conclusion to compare.
; if(a==="uncertain") return
PathoAI is not sure. Add more report text or confirm with the pathologist.
; if(a==="nondiag"||patho==="nondiag"){ const both=a==="nondiag"&&patho==="nondiag"; return
{both?<>Both say non-diagnostic. Request a better sample.:<>Adequacy mismatch. Confirm sample adequacy with the pathologist.}
; } const gap=Math.abs(CATS[a].rank-CATS[patho].rank); const col=gap===0?"var(--ok,#34d399)":gap===1?"var(--warn,#f59e0b)":"var(--tumor,#f87171)"; return
Pathologist {catPill(patho)}  vs  PathoAI {catPill(a)}
{gap===0 ? <>Matches. No discrepancy, safe to proceed. : gap===1 ? <>Borderline difference. Worth a quick confirm with the pathologist. : <>Clear discrepancy, second look needed. Take it back to the pathologist before sign-out. Do not change the read yourself.}
; }; return <>