Topic4APIR / app.js
ZevonLew's picture
Upload 104 files
e51808a verified
Raw History Blame Contribute Delete
21.3 kB
/** 默认英文界面与中文切换;所有预测来自真实模型调用,文字输出用textContent避免HTML注入。 */
import * as recognition from './recognizers.js?v=20261020-static-1';
import {sampleCatalog,sampleGroups} from './sample_catalog.js?v=20261022-natural-1';
const {recognizeFace,recognizeGesture,recognizeOCR,handConnections,versions}=recognition;
const APP_RELEASE='20261020-static-1';
const $=id=>document.getElementById(id);
const deploymentMessage=['Models download on first use and can be reused by your browser.','模型在首次使用时下载,浏览器可复用已下载的文件。'];
let task='face',lang='en',busy=false,reference=null,probe=null,result=null;
let sampleGroup='starter',selectedSample=null;
const CONTENT_RELEASE='20261022-natural-1';
// OCR工作线程会在点击运行时重新读取图片地址,因此当前上传图的Blob URL必须保持有效。
const uploadUrls={reference:null,probe:null};
// 只缓存少量已解码的样例,避免切回任务时反复下载;上传图片仍保留各自Blob地址。
const sampleImageCache=new Map();
let sampleLoading=false,sampleGeneration=0,sampleLoadController=null;
function releaseUploadUrl(kind){if(uploadUrls[kind])URL.revokeObjectURL(uploadUrls[kind]);uploadUrls[kind]=null;}
const dictionary={retry:['Retry sample','重试样例'],guide:['How to Start','开始使用'],eyebrow:['PRETRAINED MODELS · REAL INFERENCE','预训练模型 · 真实推理'],lede:['Compare faces. Read a gesture. Turn printed text into editable words.','比较人脸、识别手势,将印刷文字转为可编辑文本。'],path:['One image. A useful result.','一张图片,一份可解释的结果。'],promise:['Choose a task, inspect its output, change one setting and explain the difference.','选择任务、观察结果、改变一个设置并解释差异。'],browser:['Runs in your browser','在浏览器中运行'],training:['No training required','无需训练'],face:['01 Face verification','01 人脸验证'],gesture:['02 Gesture recognition','02 手势识别'],ocr:['03 Text OCR','03 文字 OCR'],step1:['STEP 1 · CHOOSE AN INPUT','步骤 1 · 选择输入'],step2:['STEP 2 · INSPECT THE RESULT','步骤 2 · 观察结果'],step3:['STEP 3 · ASK A BETTER QUESTION','步骤 3 · 提出实验问题'],refupload:['Upload reference image','上传参考人像'],probeupload:['Upload probe image','上传待比较人像'],upload:['Upload your image','上传图片'],layout:['Text layout','文字布局'],block:['One text block','单个文本块'],sparse:['Sparse text','稀疏文字'],line:['One text line','单行文字'],english:['English printed text · Tesseract LSTM','英文印刷体 · Tesseract LSTM'],run:['Run recognition','运行识别'],export:['Export result JSON','导出结果 JSON'],reference:['Reference','参考图'],ready:['Ready to explore','准备开始'],readyhelp:['Select a sample and run a real pretrained model.','选择样例并运行预训练模型。'],details:['Result details','结果详情'],record:['Record your evidence','记录实验依据'],recordhelp:['Keep the input fixed. Save the setting, the output, one success and one limitation. Change only one factor.','保持输入不变,保存参数、输出、一个成功观察和一个局限;每次只改变一个因素。'],privacy:['Recognition runs in your browser. Uploaded images are not sent to a server. Use synthetic or permitted images. Results and face descriptors are not stored by the app.','识别在浏览器中运行,上传图片不会发送到服务器。请使用合成或已获许可的图片;应用不持久保存结果与人脸特征。'],limits:['Teaching demo: no identity proof, no sign-language translation, no guaranteed transcription accuracy. Model files may take time to load.','教学演示:不能作为身份证明,不是手语翻译,不保证文字转写正确;首次模型加载需要时间。'],samplegroup:['Sample group','样例分组'],samplehelp:['Choose a group, then select an input. Hard inputs need checking.','先选分组,再选择输入;困难输入需核对实际结果。'],submission:['Student guide: core task and extensions →','学生指南:基础作业与拓展 →']};
const configs={face:{title:['Do these faces match?','这两张脸是否匹配?'],desc:['Compare one reference with one probe. Each image must contain exactly one face.','比较参考图与待比较图,每图需要恰好一张清晰人脸。'],question:['What changes when the distance threshold becomes stricter?','距离阈值变严格后有什么变化?'],experiment:['Keep the pair fixed. Try 0.40, 0.60 and 0.80. A smaller threshold accepts fewer pairs; descriptors stay the same.','固定两张图,尝试0.40、0.60、0.80。较小阈值允许更少匹配,特征不变。'],samples:[['Same person','同一人物','face_a_turn'],['Different person','不同人物','face_b']]},gesture:{title:['Which gesture is visible?','看到了什么手势?'],desc:['Use a complete, visible hand. The model recognizes a small set of static gestures.','使用完整清晰的手部图片,模型只识别有限的静态手势。'],question:['Does a higher score threshold remove a weak prediction?','提高分数阈值会过滤弱预测吗?'],experiment:['Run the same image at 0.30, 0.60 and 0.90. Record the candidate, score and accepted label. An unrecognized gesture differs from an undetected hand.','同一图片测试0.30、0.60、0.90,记录候选、分数和接受标签。未发现手与手势未识别是两种结果。'],samples:[['Open palm','张掌','hand_palm'],['Victory','胜利','hand_victory'],['Fist','握拳','hand_fist'],['Thumb up','点赞','hand_thumb']]},ocr:{title:['What does the image say?','图片上写了什么?'],desc:['Read printed English. Choose a layout that matches the arrangement of the text.','识别英文印刷体,选择与文字排列相符的布局。'],question:['Which layout preserves the most correct words?','哪种布局保留更多正确文字?'],experiment:['Keep the image fixed. Compare one text block with sparse text. Check the transcript against the image; confidence alone is not accuracy.','固定图片,对比单个文本块与稀疏文字;逐字核对原图,置信度不能代替正确率。'],samples:[['Lab card','实验卡','ocr_card'],['Receipt','票据','ocr_receipt'],['Sparse labels','稀疏标签','ocr_sparse'],['Hard case','困难样例','ocr_hard']]}};
const tr=pair=>pair[lang==='en'?0:1];
function text(tag,value,cls){const e=document.createElement(tag);e.textContent=value;if(cls)e.className=cls;return e;}
function status(message){$('status').textContent=message;}
function resetResult(){result=null;$('export').disabled=true;$('details').hidden=true;$('result').replaceChildren(text('h3',tr(dictionary.ready)),text('p',tr(dictionary.readyhelp)));}
/** 下载样例只禁用识别和导出;实际推理时才锁定会改变输入的控件。 */
function syncControls(){
document.querySelectorAll('button,input,select').forEach(element=>element.disabled=busy);
$('run').disabled=busy||sampleLoading||!probe||(task==='face'&&!reference);
$('export').disabled=busy||sampleLoading||!result;
$('canvases').setAttribute('aria-busy',String(sampleLoading));
}
function setBusy(value){busy=value;syncControls();}
/** 递增序号使旧请求即使较晚返回,也不能覆盖新任务或用户上传的图片。 */
function cancelSampleLoad(){
sampleLoadController?.abort();sampleLoadController=null;
sampleGeneration+=1;sampleLoading=false;
}
/** 保留匿名CORS以支持Static Space到文件CDN的重定向,并为慢下载提供超时与取消。 */
async function loadImage(src,{signal,timeoutMs=20000}={}){
if(signal?.aborted)throw new DOMException('Image selection changed.','AbortError');
if(sampleImageCache.has(src))return sampleImageCache.get(src);
return new Promise((resolve,reject)=>{
const image=new Image();let finished=false;
const cleanup=()=>{clearTimeout(timer);image.onload=image.onerror=null;signal?.removeEventListener('abort',abort);};
const fail=error=>{if(finished)return;finished=true;cleanup();image.removeAttribute('src');reject(error);};
const abort=()=>fail(new DOMException('Image selection changed.','AbortError'));
const timer=setTimeout(()=>fail(new Error(tr(['Image download timed out. Retry this sample or choose another task.','图片下载超时。请重试当前样例,或选择其他任务。']))),timeoutMs);
image.crossOrigin='anonymous';
image.onload=()=>{
if(finished)return;
if(image.naturalWidth*image.naturalHeight>24000000){fail(new Error('Use an image of at most 24 megapixels.'));return;}
finished=true;cleanup();
if(src.startsWith('./samples/')){
sampleImageCache.set(src,image);
if(sampleImageCache.size>6)sampleImageCache.delete(sampleImageCache.keys().next().value);
}
resolve(image);
};
image.onerror=()=>fail(new Error(tr(['Could not load this image. Retry and check that the complete samples folder was uploaded.','无法加载图片。请重试,并确认已完整上传samples文件夹。'])));
signal?.addEventListener('abort',abort,{once:true});
image.src=src;
});
}
function draw(canvas,im,overlay){if(!im){canvas.width=300;canvas.height=150;return;}canvas.width=im.naturalWidth;canvas.height=im.naturalHeight;const c=canvas.getContext('2d');c.drawImage(im,0,0);if(overlay)overlay(c,canvas.width,canvas.height);}
function drawFace(c,data,w){c.strokeStyle='#22bb8f';c.lineWidth=w/180;c.strokeRect(data.box.x,data.box.y,data.box.width,data.box.height);c.fillStyle='#2460e9';for(const p of data.points){c.beginPath();c.arc(p.x,p.y,w/280,0,Math.PI*2);c.fill();}}
function redraw(){draw($('reference-canvas'),reference);draw($('probe-canvas'),probe);}
/** 样例元数据只描述输入设计;模型判定始终来自实际推理。 */
async function chooseSample(name){
if(busy)return;
cancelSampleLoad();
const generation=sampleGeneration;
const controller=new AbortController();sampleLoadController=controller;
const entry=sampleCatalog.find(item=>item.id===name&&item.task===task);
const requestedTask=task;
releaseUploadUrl('probe');releaseUploadUrl('reference');
probe=reference=null;selectedSample=entry||null;sampleLoading=true;
resetResult();redraw();renderSampleInfo();$('retry-sample').hidden=true;
status(tr(['Loading sample… You can choose another input or task.','正在加载样例……期间可选择其他图片或任务。']));syncControls();
try{
// 两张人脸图并行读取;完成一张就绘制一张,不等待较慢的另一张。
// 新场景照片使用较小的JPEG发布副本;旧样例仍按原PNG路径读取。
const jobs=[loadImage(`./samples/${entry?.image||name}.${entry?.extension||'png'}`,{signal:controller.signal}).then(image=>{
if(generation!==sampleGeneration)return;probe=image;draw($('probe-canvas'),image);
})];
if(requestedTask==='face')jobs.push(loadImage(`./samples/${entry?.reference||'face_a'}.png`,{signal:controller.signal}).then(image=>{
if(generation!==sampleGeneration)return;reference=image;draw($('reference-canvas'),image);
}));
await Promise.all(jobs);
if(generation!==sampleGeneration)return;
status(tr(['Ready. Run recognition to see real output.','已就绪,运行识别获取实际输出。']));
}catch(error){
if(generation!==sampleGeneration)return;
controller.abort();
if(error.name!=='AbortError'){status(error.message);$('retry-sample').hidden=false;}
}finally{
if(generation===sampleGeneration){sampleLoading=false;sampleLoadController=null;syncControls();}
}
}
function renderSampleInfo(){
$('sample-note').textContent=selectedSample?tr(selectedSample.label)+' · '+tr(selectedSample.note):'';
}
function renderSamples(){
const choices=sampleCatalog.filter(item=>item.task===task);
const groups=[...new Set(choices.map(item=>item.group))];
if(!groups.includes(sampleGroup))sampleGroup='starter';
$('sample-group').replaceChildren();
for(const group of groups){
const option=document.createElement('option');option.value=group;
option.textContent=tr(sampleGroups[group])+` (${choices.filter(item=>item.group===group).length})`;
$('sample-group').append(option);
}
$('sample-group').value=sampleGroup;$('examples').replaceChildren();
for(const entry of choices.filter(item=>item.group===sampleGroup)){
const button=document.createElement('button');button.dataset.sampleId=entry.id;
const image=new Image();image.src=entry.preview;image.alt='';
button.append(image,text('span',tr(entry.label)));
button.addEventListener('click',()=>chooseSample(entry.id));$('examples').append(button);
}
renderSampleInfo();syncControls();
}
function translate(){$('release-version').textContent=tr(['Build: '+APP_RELEASE,'版本:'+APP_RELEASE]);$('deployment-status').textContent=tr(deploymentMessage);document.documentElement.lang=lang==='en'?'en':'zh-CN';document.querySelectorAll('[data-i18n]').forEach(e=>e.textContent=tr(dictionary[e.dataset.i18n]));$('language').textContent=lang==='en'?'中文':'EN';const cfg=configs[task];for(const [id,key]of [['task-title','title'],['task-description','desc'],['question','question'],['experiment','experiment']])$(id).textContent=tr(cfg[key]);$('probe-caption').textContent=task==='face'?tr(['Probe','待比较图']):tr(['Input and model overlay','输入与模型叠加结果']);$('threshold-label').textContent=task==='face'?tr(['Distance threshold','距离阈值']):tr(['Gesture score threshold','手势分数阈值']);$('threshold-help').textContent=task==='face'?tr(['Lower is stricter. Distance is not confidence.','越低越严格,距离不是置信度。']):tr(['Higher is stricter. Low-scoring labels are rejected.','越高越严格,过滤低分标签。']);$('model-name').textContent=versions[task];$('gesture-processing').hidden=task!=='gesture';$('gesture-processing').textContent=tr(['Gesture recognition runs on this device and needs WebGL2 support.','手势识别在当前设备中运行,需要浏览器支持WebGL2。']);renderSamples();if(result)showResult();else resetResult();}
async function switchTask(next){if(busy)return;task=next;sampleGroup='starter';selectedSample=null;document.querySelectorAll('[data-task]').forEach(b=>b.setAttribute('aria-selected',String(b.dataset.task===task)));$('workspace').setAttribute('aria-labelledby',`tab-${task}`);$('face-controls').hidden=task!=='face';$('reference-figure').hidden=task!=='face';$('single-upload-wrap').hidden=task==='face';$('threshold-wrap').hidden=task==='ocr';$('ocr-settings').hidden=task!=='ocr';$('canvases').classList.toggle('single',task!=='face');$('threshold').value='0.6';$('threshold-value').value='0.60';resetResult();translate();await chooseSample(configs[task].samples[0][2]);}
function showResult(){const box=$('result');box.replaceChildren();if(!result)return;redraw();if(task==='face'){box.append(text('h3',tr([result.decision,result.distance<result.threshold?'当前阈值下匹配':'当前阈值下不匹配'])),text('div',result.distance.toFixed(3),'metric'),text('p',tr([`Descriptor distance · threshold ${result.threshold.toFixed(2)}. Lower means closer features.`,`特征距离 · 阈值 ${result.threshold.toFixed(2)},越小表示特征越接近。`])));draw($('reference-canvas'),reference,(c,w)=>drawFace(c,result.reference,w));draw($('probe-canvas'),probe,(c,w)=>drawFace(c,result.probe,w));}else if(task==='gesture'){box.append(text('p',tr(['Processed in this browser.','已在浏览器内处理。'])));box.append(text('h3',result.hands.length?tr(['Gesture result','手势结果']):tr(['No hand detected','未检测到手'])));for(const hand of result.hands){box.append(text('span',hand.label,'tag'),text('p',tr([`Candidate: ${hand.candidate} · score ${hand.score.toFixed(3)} · ${hand.handedness}`,`候选:${hand.candidate} · 分数 ${hand.score.toFixed(3)} · ${hand.handedness}`])));}draw($('probe-canvas'),probe,(c,w,h)=>{for(const hand of result.hands){c.strokeStyle='#2470ec';c.lineWidth=w/170;for(const [a,b]of handConnections){c.beginPath();c.moveTo(hand.points[a].x*w,hand.points[a].y*h);c.lineTo(hand.points[b].x*w,hand.points[b].y*h);c.stroke();}c.fillStyle='#17aa79';for(const p of hand.points){c.beginPath();c.arc(p.x*w,p.y*h,w/180,0,Math.PI*2);c.fill();}}});}else{box.append(text('h3',tr(['Editable transcript','可编辑文字结果'])),text('pre',result.text||tr(['No text recognized.','未识别到文字。'])),text('p',tr([`Reported confidence: ${result.confidence.toFixed(1)} / 100. Verify against the input.`,`报告置信度:${result.confidence.toFixed(1)} / 100,请与输入核对。`])));draw($('probe-canvas'),probe,(c,w)=>{c.strokeStyle='#2460e9';c.lineWidth=w/280;for(const word of result.words){const b=word.box;c.strokeRect(b.x0,b.y0,b.x1-b.x0,b.y1-b.y0);}});}box.append(text('p',result.note));$('json').textContent=JSON.stringify(result,null,2);$('details').hidden=false;$('export').disabled=false;}
async function run(){if(busy||sampleLoading||!probe||(task==='face'&&!reference))return;resetResult();redraw();setBusy(true);const start=performance.now();try{await new Promise(r=>requestAnimationFrame(r));result=task==='face'?await recognizeFace(reference,probe,Number($('threshold').value),status):task==='gesture'?await recognizeGesture(probe,Number($('threshold').value),status):await recognizeOCR(probe,$('psm').value,status);result.appBuild=APP_RELEASE;result.modelBuild=recognition.release;result.contentBuild=CONTENT_RELEASE;result.sampleId=selectedSample?.id||'uploaded';result.referenceSampleId=selectedSample?.reference||null;result.sampleGroup=selectedSample?.group||null;result.elapsedMs=Math.round(performance.now()-start);result.timestamp=new Date().toISOString();showResult();status(tr([`Finished in ${(result.elapsedMs/1000).toFixed(2)} s. First run includes model loading.`,`完成,用时 ${(result.elapsedMs/1000).toFixed(2)} 秒,首次包含模型加载。`]));}catch(e){result=null;$('result').replaceChildren(text('h3',tr(['Could not complete this run','本次运行未完成'])),text('p',e.message));status(tr(['Check the input and model files, then retry.','检查输入及模型文件后重试。']));}finally{setBusy(false);}}
async function upload(event,kind){
const f=event.target.files[0];if(!f)return;
if(!['image/png','image/jpeg','image/webp'].includes(f.type)||f.size>15*1024*1024){
status(tr(['Use a PNG, JPEG or WebP under 15 MB.','请使用小于15MB的PNG、JPEG或WebP。']));
event.target.value='';return;
}
cancelSampleLoad();$('retry-sample').hidden=true;
const url=URL.createObjectURL(f);let retained=false;setBusy(true);
try{
const im=await loadImage(url);releaseUploadUrl(kind);uploadUrls[kind]=url;retained=true;
if(kind==='reference')reference=im;else probe=im;selectedSample=null;renderSampleInfo();
resetResult();redraw();status(tr(['Image loaded. Ready to run.','图片已加载,可以运行。']));
}catch(e){status(e.message);}
finally{
// 清空文件控件才能在切换任务后再次选择同一文件并触发change事件。
event.target.value='';if(!retained)URL.revokeObjectURL(url);setBusy(false);
}
}
document.querySelectorAll('[data-task]').forEach(b=>b.addEventListener('click',()=>switchTask(b.dataset.task)));
$('sample-group').addEventListener('change',()=>{sampleGroup=$('sample-group').value;renderSamples();});
$('retry-sample').addEventListener('click',()=>chooseSample(selectedSample?.id||configs[task].samples[0][2]));
$('language').addEventListener('click',()=>{lang=lang==='en'?'zh':'en';translate();});$('run').addEventListener('click',run);
// 参数变化后清除旧输出,防止把旧参数的结果误当作新结果。
$('threshold').addEventListener('input',()=>{$('threshold-value').value=Number($('threshold').value).toFixed(2);resetResult();redraw();});$('psm').addEventListener('change',()=>{resetResult();redraw();});
$('reference-upload').addEventListener('change',e=>upload(e,'reference'));$('probe-upload').addEventListener('change',e=>upload(e,'probe'));$('single-upload').addEventListener('change',e=>upload(e,'probe'));
$('export').addEventListener('click',()=>{if(!result)return;const url=URL.createObjectURL(new Blob([JSON.stringify(result,null,2)],{type:'application/json'}));const a=document.createElement('a');a.href=url;a.download=`vision-lab-${task}-${Date.now()}.json`;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);});
// HTML、交互和识别模块使用同一发布号,避免浏览器混用旧版部署文件。
const htmlRelease=document.querySelector('meta[name="vision-lab-build"]')?.content;
if(htmlRelease!==APP_RELEASE||recognition.release!==APP_RELEASE){
setBusy(true);status('Deployment files are mixed. Upload all files from the Static package, then reopen the Space App.');
$('result').replaceChildren(text('h3','Update the complete Static package'),text('p',`HTML: ${htmlRelease||'legacy'} ? app: ${APP_RELEASE} ? models: ${recognition.release||'legacy'}`));
}else{
switchTask('face');
}