Delete app.js
Browse files
app.js
DELETED
|
@@ -1,96 +0,0 @@
|
|
| 1 |
-
const $ = (id) => document.getElementById(id);
|
| 2 |
-
const titles = {resnet18:"ResNet-18",vit:"ViT-B/16",clip:"CLIP ViT-B/32"};
|
| 3 |
-
const descriptions = {
|
| 4 |
-
resnet18:"A convolutional network with 1,000 fixed ImageNet labels. A small model to start with.",
|
| 5 |
-
vit:"A vision transformer with 1,000 fixed ImageNet labels. It compares patterns across image patches.",
|
| 6 |
-
clip:"A vision-language model. It ranks your candidate descriptions against the image.",
|
| 7 |
-
};
|
| 8 |
-
let worker, activeUrl, result, busy=false, sourceName="Cat sample", runSettings;
|
| 9 |
-
function setStatus(text,error=false){$("status").textContent=text;$("status").classList.toggle("error",error);}
|
| 10 |
-
function setBusy(value){busy=value;$("run").disabled=value;$("run").firstChild.textContent=value?"Classifying… ":"Classify image ";$("cancel").hidden=!value;$("progress").hidden=!value;for(const el of document.querySelectorAll("select,textarea,input,button.sample"))el.disabled=value;}
|
| 11 |
-
function resetResult(){result=null;$("empty-state").hidden=false;$("result-content").hidden=true;$("result-model").textContent="PREDICTION";}
|
| 12 |
-
function getWorker(){
|
| 13 |
-
if(worker)return worker;
|
| 14 |
-
worker=new Worker(new URL("inference-worker.js",import.meta.url),{type:"module"});
|
| 15 |
-
worker.onmessage=({data})=>{
|
| 16 |
-
if(data.type==="status"){setStatus(data.text);$("progress").removeAttribute("value");}
|
| 17 |
-
if(data.type==="progress"){
|
| 18 |
-
const percent=Math.max(0,Math.min(100,data.progress||0));$("progress").value=percent;
|
| 19 |
-
const mb=data.total?` (${(data.loaded/1048576).toFixed(1)} / ${(data.total/1048576).toFixed(1)} MB)`:"";
|
| 20 |
-
setStatus(`Loading ${data.file}: ${percent.toFixed(0)}%${mb}. Keep this tab open.`);
|
| 21 |
-
}
|
| 22 |
-
if(data.type==="result"){
|
| 23 |
-
result={...data.result,source:sourceName,top_k:runSettings.topk,review:{threshold:runSettings.threshold,flagged:data.result.predictions[0].score<runSettings.threshold}};
|
| 24 |
-
renderResult();setBusy(false);setStatus("Complete. Inspect the prediction, then try one controlled change.");
|
| 25 |
-
}
|
| 26 |
-
if(data.type==="error"){
|
| 27 |
-
setBusy(false);setStatus("Could not complete inference. Check access to Hugging Face and the model download, then retry. Details: "+data.message,true);
|
| 28 |
-
worker.terminate();worker=null;
|
| 29 |
-
}
|
| 30 |
-
};
|
| 31 |
-
worker.onerror=()=>{setBusy(false);setStatus("The browser AI runtime could not load. Check your network connection and try again.",true);worker.terminate();worker=null;};
|
| 32 |
-
return worker;
|
| 33 |
-
}
|
| 34 |
-
async function chooseImage(url,label){
|
| 35 |
-
const img=new Image();img.crossOrigin="anonymous";img.src=url;await img.decode();
|
| 36 |
-
if(img.width*img.height>25_000_000)throw new Error("Please use an image under 25 megapixels.");
|
| 37 |
-
if(activeUrl&&activeUrl!==url){URL.revokeObjectURL(activeUrl);activeUrl=null;}
|
| 38 |
-
$("preview").src=url;$("preview").alt=label+" selected for classification";$("image-name").textContent=label;sourceName=label;resetResult();setStatus("Image ready. Click Classify image.");
|
| 39 |
-
}
|
| 40 |
-
for(const button of document.querySelectorAll(".sample"))button.addEventListener("click",async()=>{
|
| 41 |
-
if(busy)return;
|
| 42 |
-
try{await chooseImage(button.dataset.file,button.dataset.label+" sample");
|
| 43 |
-
for(const el of document.querySelectorAll(".sample")){el.classList.toggle("selected",el===button);el.setAttribute("aria-pressed",String(el===button));}
|
| 44 |
-
}catch(err){setStatus(err.message,true);}
|
| 45 |
-
});
|
| 46 |
-
$("upload").addEventListener("change",async(event)=>{
|
| 47 |
-
const file=event.target.files[0];if(!file||busy)return;
|
| 48 |
-
if(file.size>12*1024*1024){setStatus("Please choose an image smaller than 12 MB.",true);return;}
|
| 49 |
-
const url=URL.createObjectURL(file);
|
| 50 |
-
try{await chooseImage(url,"Uploaded image");activeUrl=url;for(const el of document.querySelectorAll(".sample")){el.classList.remove("selected");el.setAttribute("aria-pressed","false");}}
|
| 51 |
-
catch(err){URL.revokeObjectURL(url);setStatus("Could not read that image. Choose a PNG, JPEG or WebP under 25 megapixels.",true);}
|
| 52 |
-
});
|
| 53 |
-
$("model").addEventListener("change",()=>{$("clip-controls").hidden=$("model").value!=="clip";$("model-description").textContent=descriptions[$("model").value];setStatus("Model selected. Run again to compare its prediction.");});
|
| 54 |
-
$("topk").addEventListener("input",()=>$("topk-value").value=$("topk").value);
|
| 55 |
-
$("threshold").addEventListener("input",()=>$("threshold-value").value=Number($("threshold").value).toFixed(2));
|
| 56 |
-
$("run").addEventListener("click",async()=>{
|
| 57 |
-
if(busy)return;
|
| 58 |
-
const model=$("model").value, labels=$("labels").value.split(/[,\n]/).map(s=>s.trim()).filter(Boolean);
|
| 59 |
-
if(model==="clip"){
|
| 60 |
-
if(labels.length<2||labels.length>50){setStatus("CLIP needs 2–50 candidate labels.",true);return;}
|
| 61 |
-
if(new Set(labels.map(x=>x.toLowerCase())).size!==labels.length){setStatus("Candidate labels must be unique.",true);return;}
|
| 62 |
-
if(labels.some(x=>x.length>100)){setStatus("Keep each candidate label within 100 characters.",true);return;}
|
| 63 |
-
}
|
| 64 |
-
try{
|
| 65 |
-
const img=$("preview");await img.decode();const scale=Math.min(1,1536/Math.max(img.naturalWidth,img.naturalHeight));
|
| 66 |
-
const canvas=document.createElement("canvas");canvas.width=Math.max(1,Math.round(img.naturalWidth*scale));canvas.height=Math.max(1,Math.round(img.naturalHeight*scale));
|
| 67 |
-
const ctx=canvas.getContext("2d");ctx.drawImage(img,0,0,canvas.width,canvas.height);const pixels=ctx.getImageData(0,0,canvas.width,canvas.height).data;
|
| 68 |
-
runSettings={topk:Number($("topk").value),threshold:Number($("threshold").value)};
|
| 69 |
-
setBusy(true);resetResult();setStatus("Preparing classification…");$("progress").removeAttribute("value");
|
| 70 |
-
getWorker().postMessage({model,labels,template:$("template").value,topk:runSettings.topk,width:canvas.width,height:canvas.height,pixels:pixels.buffer},[pixels.buffer]);
|
| 71 |
-
}catch(err){setBusy(false);setStatus(err.message,true);}
|
| 72 |
-
});
|
| 73 |
-
$("cancel").addEventListener("click",()=>{if(worker)worker.terminate();worker=null;setBusy(false);setStatus("Cancelled. You can choose another model and retry.");});
|
| 74 |
-
function renderResult(){
|
| 75 |
-
const top=result.predictions[0];$("empty-state").hidden=true;$("result-content").hidden=false;
|
| 76 |
-
$("result-model").textContent=titles[result.model];$("top-label").textContent=top.label;$("top-score").textContent=(top.score*100).toFixed(1)+"%";
|
| 77 |
-
$("result-context").textContent=`${result.candidate_count.toLocaleString()} labels in ${result.label_space} · ${result.source}`;
|
| 78 |
-
$("bars").replaceChildren();$("rows").replaceChildren();
|
| 79 |
-
for(const p of result.predictions){
|
| 80 |
-
const row=document.createElement("div");row.className="score-row";const caption=document.createElement("div");caption.className="bar-label";
|
| 81 |
-
const label=document.createElement("span"),score=document.createElement("span");label.textContent=p.label;score.textContent=(p.score*100).toFixed(2)+"%";caption.append(label,score);
|
| 82 |
-
const track=document.createElement("div");track.className="bar-track";const fill=document.createElement("div");fill.className="bar-fill";fill.style.width=(p.score*100)+"%";track.append(fill);row.append(caption,track);$("bars").append(row);
|
| 83 |
-
const tr=document.createElement("tr");for(const value of [p.rank,p.label,p.score.toFixed(6)]){const td=document.createElement("td");td.textContent=value;tr.append(td);}$("rows").append(tr);
|
| 84 |
-
}
|
| 85 |
-
$("review-note").textContent=result.review.flagged?"Review suggested: the top score is below your threshold.":"The top score meets your review threshold. Inspect the image and label before accepting it.";
|
| 86 |
-
$("score-note").textContent=result.score_note;
|
| 87 |
-
$("timing-note").textContent=`Inference: ${result.inference_ms.toLocaleString()} ms on this device, excluding model loading and interface time. Review threshold: ${result.review.threshold.toFixed(2)} (a display flag only).`;
|
| 88 |
-
$("json-output").textContent=JSON.stringify(result,null,2);
|
| 89 |
-
}
|
| 90 |
-
function download(content,name,type){const url=URL.createObjectURL(new Blob([content],{type}));const a=document.createElement("a");a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);}
|
| 91 |
-
$("json-download").addEventListener("click",()=>{if(result)download(JSON.stringify(result,null,2),"classification_result.json","application/json");});
|
| 92 |
-
$("csv-download").addEventListener("click",()=>{
|
| 93 |
-
if(!result)return;const quote=s=>'"'+String(s).replaceAll('"','""')+'"';
|
| 94 |
-
const rows=result.predictions.map(p=>{let label=p.label;if(/^[\s]*[=+@-]/.test(label))label="'"+label;return[p.rank,quote(label),p.score].join(",");});
|
| 95 |
-
download("\uFEFFrank,label,score\r\n"+rows.join("\r\n"),"classification_predictions.csv","text/csv;charset=utf-8");
|
| 96 |
-
});
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|