Image_Recognition_Static / recognizers.js
ZevonLew's picture
Upload 98 files
87485e4 verified
Raw History Blame Contribute Delete
9.63 kB
/** 三个独立识别任务的模型层,仅处理当前页面内存中的图像。 */
const caches=new Map();
export const versions={face:'face-api.js 0.22.2',gesture:'MediaPipe Tasks Vision 0.10.18',ocr:'Tesseract.js 5.1.1 / English LSTM'};
// 页面和模型层必须属于同一发布版,防止上传旧整包覆盖已修好的代码。
export const release='20261013-gradio-1';
async function cached(key,factory){
// 加载失败清理缓存,允许修复文件或网络后再次尝试。
if(!caches.has(key))caches.set(key,factory().catch(e=>{caches.delete(key);throw e;}));
return caches.get(key);
}
async function loadVendor(key,src){
// 首页先呈现和读取样例;大型识别库在首次运行对应任务时再下载,失败后可重试。
return cached(`vendor:${key}`,()=>new Promise((resolve,reject)=>{
const script=document.createElement('script');script.src=src;script.async=true;
script.onload=resolve;
script.onerror=()=>{script.remove();reject(new Error(`Could not load ${key} library. Check the Space connection and retry.`));};
document.head.append(script);
}));
}
function requireReadableImage(image){
// 在进入模型之前检测同源/CORS状态,避免face-api的旧版任务链吞掉异步异常后一直等待。
if(!(image.naturalWidth||image.width)||!(image.naturalHeight||image.height))throw new Error('The image is not ready. Choose a valid image and retry.');
const canvas=document.createElement('canvas');canvas.width=canvas.height=1;
try{const ctx=canvas.getContext('2d');if(!ctx)throw new Error('A 2D canvas is unavailable.');ctx.drawImage(image,0,0,1,1);ctx.getImageData(0,0,1,1);}
catch(e){
if(e.name==='SecurityError'||/taint|cross-origin/i.test(e.message))throw new Error('This image cannot be read because it was loaded without CORS permission. Update app.js and reload the page; an external image host must allow CORS.');
throw e;
}finally{canvas.width=canvas.height=0;}
}
async function describeFace(image,settings,label,progress){
// 0.22.2的ComposableTask.then不转发拒绝,且链式检测用了不带reject的异步Promise。
// 使用同一组导出的任务类,并将父阶段结果作为普通Promise传入:保留算法,可靠传递每阶段错误。
progress(`Detecting the ${label} face…`);
const detections=await faceapi.detectAllFaces(image,settings).run();
if(detections.length!==1)throw new Error(`Use exactly one clear face per image. Found ${detections.length} in the ${label} image.`);
const detected=detections.map(detection=>faceapi.extendWithFaceDetection({},detection));
progress(`Locating landmarks in the ${label} face…`);
const landmarks=await new faceapi.DetectAllFaceLandmarksTask(Promise.resolve(detected),image,false).run();
progress(`Encoding the ${label} face descriptor…`);
const described=await new faceapi.ComputeAllFaceDescriptorsTask(Promise.resolve(landmarks),image).run();
return described[0];
}
export async function recognizeFace(reference,probe,threshold,progress){
requireReadableImage(reference);requireReadableImage(probe);
progress('Loading face detector, landmarks and descriptor model…');
await loadVendor('face-api.js','./vendor/face-api.min.js');
await cached('face',async()=>{await Promise.all([faceapi.nets.tinyFaceDetector.loadFromUri('./models/face'),faceapi.nets.faceLandmark68Net.loadFromUri('./models/face'),faceapi.nets.faceRecognitionNet.loadFromUri('./models/face')]);return true;});
const settings=new faceapi.TinyFaceDetectorOptions({inputSize:416,scoreThreshold:0.35});
const a=await describeFace(reference,settings,'reference',progress);
const b=await describeFace(probe,settings,'probe',progress);
progress('Comparing the two face descriptors…');
const distance=faceapi.euclideanDistance(a.descriptor,b.descriptor);
const pack=x=>({box:{x:x.detection.box.x,y:x.detection.box.y,width:x.detection.box.width,height:x.detection.box.height},points:x.landmarks.positions.map(p=>({x:p.x,y:p.y}))});
return {task:'face',model:versions.face,distance,threshold,decision:distance<threshold?'Match at this threshold':'No match at this threshold',reference:pack(a),probe:pack(b),note:'Distance is not a probability. A match is not proof of identity. Descriptors are not exported.'};
}
async function recognizeGestureOnCPU(image,threshold,progress){
// 网页Tasks无法绕过WebGL上传路径;后端使用相同版本和同一份task权重,不伪装成浏览器CPU。
progress('Browser graphics unavailable. Recognizing on the Space CPU…');
const canvas=document.createElement('canvas');
// 限制兼容路径的传输尺寸并维持比例,归一化关键点仍可叠加在原图上。
const scale=Math.min(1,1920/Math.max(image.naturalWidth,image.naturalHeight));
canvas.width=Math.max(1,Math.round(image.naturalWidth*scale));canvas.height=Math.max(1,Math.round(image.naturalHeight*scale));
const ctx=canvas.getContext('2d');if(!ctx)throw new Error('A 2D canvas is unavailable.');
ctx.drawImage(image,0,0,canvas.width,canvas.height);
const blob=await new Promise(resolve=>canvas.toBlob(resolve,'image/png'));canvas.width=canvas.height=0;
if(!blob)throw new Error('Could not prepare the gesture image. Choose a valid image and retry.');
const controller=new AbortController();const timer=setTimeout(()=>controller.abort(),120000);
try{
const response=await fetch(`./api/gesture?threshold=${encodeURIComponent(threshold)}`,{method:'POST',headers:{'Content-Type':'image/png'},body:blob,signal:controller.signal});
if(response.status===404||response.status===405)throw new Error('CPU compatibility is not deployed yet. Upload the complete CPU fix package, including README.md, app.py and packages.txt, to this Space and wait for the Gradio build to finish.');
let data;try{data=await response.json();}catch{throw new Error('The Space CPU did not return a recognition result. Wait for the Space to finish starting and retry.');}
if(!response.ok)throw new Error(typeof data.detail==='string'?data.detail:'The Space CPU could not complete this run. Retry shortly.');
if(data.task!=='gesture'||!Array.isArray(data.hands))throw new Error('The Space CPU returned an invalid gesture result.');
data.inputSize={width:image.naturalWidth,height:image.naturalHeight};return data;
}catch(e){if(e.name==='AbortError')throw new Error('The Space CPU took too long to respond. Wait a moment and retry.');throw e;}
finally{clearTimeout(timer);}
}
export async function recognizeGesture(image,threshold,progress){
requireReadableImage(image);
let model;
try{
model=await cached('gesture',async()=>{
// 独立HTML画布保留可用设备的浏览器推理;无WebGL时由真正的Space CPU接口接手。
const canvas=document.createElement('canvas');canvas.width=canvas.height=2;
const gl=canvas.getContext('webgl2');
if(!gl||gl.isContextLost())throw new Error('WebGL2 is unavailable.');
progress('Loading hand landmarks and gesture classifier…');
const {FilesetResolver,GestureRecognizer}=await import('./vendor/vision_bundle.mjs');
const files=await FilesetResolver.forVisionTasks('./vendor/wasm');
return GestureRecognizer.createFromOptions(files,{canvas,baseOptions:{modelAssetPath:'./models/gesture_recognizer.task',delegate:'CPU'},runningMode:'IMAGE',numHands:2});
});
progress('Recognizing the static hand pose…');
const raw=model.recognize(image);
const hands=raw.landmarks.map((points,i)=>{const g=raw.gestures[i]?.[0];const accepted=Boolean(g&&g.categoryName!=='None'&&g.score>=threshold);return {label:accepted?g.categoryName:'Unrecognized',candidate:g?.categoryName||'None',score:g?.score||0,accepted,handedness:raw.handedness[i]?.[0]?.categoryName||'Unknown',points:points.map(p=>({x:p.x,y:p.y,z:p.z}))};});
return {task:'gesture',model:versions.gesture,backend:'Browser CPU (WebGL image input)',threshold,hands,note:hands.length?'Static gesture categories; not sign-language translation.':'No hand detected. Try a clear, complete hand on a simple background.'};
}catch(e){
// 清除坏图形任务;上下文错误自动回退,其他输入/权重错误保持真实失败。
caches.delete('gesture');try{model?.close();}catch{}
if(/activeTexture|WebGL|OpenGL|context/i.test(e.message))return recognizeGestureOnCPU(image,threshold,progress);
throw e;
}
}
export async function recognizeOCR(image,psm,progress){
requireReadableImage(image);
progress('Loading OCR engine…');
await loadVendor('Tesseract.js','./vendor/tesseract.min.js');
const worker=await cached('ocr',()=>Tesseract.createWorker('eng',1,{workerPath:'./vendor/worker.min.js',corePath:'./vendor/tesseract-core',langPath:'./models',logger:m=>progress(`${m.status}${Number.isFinite(m.progress)?' '+Math.round(m.progress*100)+'%':''}`)}));
await worker.setParameters({tessedit_pageseg_mode:String(psm)});
progress('Reading printed English text…');
const {data}=await worker.recognize(image);
return {task:'ocr',model:versions.ocr,psm,text:data.text.trim(),confidence:data.confidence,words:(data.words||[]).map(w=>({text:w.text,confidence:w.confidence,box:w.bbox})),note:'Confidence is a review cue, not measured accuracy. Check every important character against the image.'};
}
export const handConnections=[[0,1],[1,2],[2,3],[3,4],[0,5],[5,6],[6,7],[7,8],[5,9],[9,10],[10,11],[11,12],[9,13],[13,14],[14,15],[15,16],[13,17],[0,17],[17,18],[18,19],[19,20]];