File size: 2,582 Bytes
1cbe663
1
let handbook=[];const $=s=>document.querySelector(s);const escapeHtml=s=>String(s).replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#39;'}[c]));const stop=new Set('what which where when how does that this with from into their there about could should would have been were does only dose dosing patient patients please show tell using they them the for and are can you your'.split(' '));function tokens(s){return [...new Set((s.toLowerCase().match(/[a-z0-9]+/g)||[]).filter(w=>w.length>2&&!stop.has(w)))];}function highlight(s,words){let safe=escapeHtml(s);for(const w of words.filter(w=>w.length>3).slice(0,8)){const re=new RegExp('\\b('+w+')\\b','gi');safe=safe.replace(re,'<mark>$1</mark>')}return safe;}function search(q){const words=tokens(q);if(!words.length)return [];return handbook.flatMap(p=>p.paras.map((text,i)=>{const hay=text.toLowerCase(),title=p.section.toLowerCase();let score=0;for(const w of words){if(hay.includes(w))score+=2;if(title.includes(w))score+=1;}return {page:p.page,section:p.section,text,score,i};})).filter(x=>x.score>0).sort((a,b)=>b.score-a.score||a.page-b.page).slice(0,5)}function render(q){const root=$('#results');const hits=search(q);const words=tokens(q);let html='<div class="notice"><strong>Evidence browser, not a medical answer.</strong> These are keyword matches from a synthetic teaching handbook. Verify the cited passage and its scope. This demo does not run the notebook’s embedding model, reranker, or clinical reasoning.</div>';if(!hits.length){root.innerHTML=html+'<div class="empty"><h3>No matching passages</h3><p>The handbook may not cover this question. Do not infer an answer.</p></div>';return;}html+='<div class="result-head"><h3>Matching handbook passages</h3><span>'+hits.length+' passage(s) · ranked by keyword overlap</span></div>';for(const h of hits)html+='<article class="passage"><div class="passage-top"><h4>'+escapeHtml(h.section)+'</h4><span class="page">Page '+h.page+'</span></div><p>'+highlight(h.text,words)+'</p></article>';root.innerHTML=html;}fetch('handbook.json').then(r=>{if(!r.ok)throw Error('Could not load handbook');return r.json()}).then(data=>{handbook=data}).catch(()=>{$('#results').innerHTML='<div class="notice">Could not load handbook.json. Serve the folder through Hugging Face Spaces or a local web server.</div>'});$('#search-form').addEventListener('submit',e=>{e.preventDefault();render($('#question').value.trim())});document.querySelectorAll('.example').forEach(b=>b.addEventListener('click',()=>{$('#question').value=b.dataset.q;render(b.dataset.q)}));