File size: 7,453 Bytes
7e7812a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e51808a
7e7812a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/** 三个独立识别任务的模型层,仅处理当前页面内存中的图像。 */
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='20261020-static-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 the ${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.'};
}
export async function recognizeGesture(image,threshold,progress){
  requireReadableImage(image);
  let model;
  try{
    model=await cached('gesture',async()=>{
      // 保留原浏览器模型与独立画布;Static模式只在设备内推理,不调用服务器。
      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){
    // 清除失败任务以便重试;静态网页不再请求已经不存在的CPU接口。
    caches.delete('gesture');try{model?.close();}catch{}
    if(/activeTexture|WebGL|OpenGL|context/i.test(e.message))throw new Error('This browser cannot initialize gesture graphics. Try another browser or device with WebGL2 support.');
    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]];