@sssxyd/face-liveness-detector 0.2.27 → 0.2.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.esm.js CHANGED
@@ -289,7 +289,6 @@ if (cvModuleImport && cvModuleImport.default) {
289
289
  }
290
290
  let webglAvailableCache = null;
291
291
  let opencvInitPromise = null;
292
- let opencvInitialized = false; // 标记是否已初始化完成
293
292
  function _isWebGLAvailable() {
294
293
  if (webglAvailableCache !== null) {
295
294
  return webglAvailableCache;
@@ -324,11 +323,6 @@ function _detectOptimalBackend() {
324
323
  * @param timeout - Maximum wait time in milliseconds (default: 30000)
325
324
  */
326
325
  async function preloadOpenCV(timeout = 30000) {
327
- // 如果已经初始化完成,直接返回
328
- if (opencvInitialized) {
329
- console.log('[OpenCV] Already initialized, skipping preload');
330
- return;
331
- }
332
326
  // 如果已经在初始化中,返回现有的 Promise
333
327
  if (opencvInitPromise) {
334
328
  console.log('[OpenCV] Already initializing, reusing existing promise');
@@ -338,15 +332,13 @@ async function preloadOpenCV(timeout = 30000) {
338
332
  // 复用 loadOpenCV 的初始化逻辑
339
333
  opencvInitPromise = _initializeOpenCV(timeout);
340
334
  try {
341
- const initTime = await opencvInitPromise;
342
- console.log('[OpenCV] Preload completed successfully ', {
343
- initTime: `${initTime.toFixed(2)}ms`,
344
- version: getOpenCVVersion()
345
- });
335
+ await opencvInitPromise;
336
+ console.log('[OpenCV] Preload completed successfully');
346
337
  }
347
338
  catch (error) {
348
339
  console.error('[OpenCV] Preload failed:', error);
349
- opencvInitPromise = null; // 失败时清除 Promise,允许重试
340
+ // 失败后清除 Promise,允许重试
341
+ opencvInitPromise = null;
350
342
  throw error;
351
343
  }
352
344
  }
@@ -356,16 +348,16 @@ async function preloadOpenCV(timeout = 30000) {
356
348
  */
357
349
  async function _initializeOpenCV(timeout) {
358
350
  const initStartTime = performance.now();
359
- console.log('Waiting for OpenCV WASM initialization...');
351
+ console.log('[FaceDetectionEngine] Waiting for OpenCV WASM initialization...');
360
352
  // 快速路径:检查是否已经初始化
361
353
  if (cvModule.Mat) {
362
354
  const initTime = performance.now() - initStartTime;
363
- console.log(`OpenCV.js already initialized, took ${initTime.toFixed(2)}ms`);
355
+ console.log(`[FaceDetectionEngine] OpenCV.js already initialized, took ${initTime.toFixed(2)}ms`);
364
356
  return cvModule;
365
357
  }
366
358
  if (typeof globalThis !== 'undefined' && globalThis.cv && globalThis.cv.Mat) {
367
359
  const initTime = performance.now() - initStartTime;
368
- console.log(`OpenCV.js already initialized (from global), took ${initTime.toFixed(2)}ms`);
360
+ console.log(`[FaceDetectionEngine] OpenCV.js already initialized (from global), took ${initTime.toFixed(2)}ms`);
369
361
  cvModule = globalThis.cv;
370
362
  return cvModule;
371
363
  }
@@ -373,84 +365,63 @@ async function _initializeOpenCV(timeout) {
373
365
  if (typeof globalThis !== 'undefined' && !globalThis.cv) {
374
366
  if (cvModule && Object.isExtensible(cvModule)) {
375
367
  globalThis.cv = cvModule;
376
- console.log('cvModule assigned to globalThis.cv');
368
+ console.log('[FaceDetectionEngine] cvModule assigned to globalThis.cv');
377
369
  }
378
370
  else {
379
- console.log('cvModule is not extensible or globalThis already has cv');
371
+ console.log('[FaceDetectionEngine] cvModule is not extensible or globalThis already has cv');
380
372
  }
381
373
  }
382
374
  return new Promise((resolve, reject) => {
383
- // 轮询检查OpenCV初始化状态的标记
384
- let pollInterval = null;
385
- // 防止多次调用 resolve/reject
386
- let finished = false;
387
375
  const timeoutId = setTimeout(() => {
388
- console.error('OpenCV.js initialization timeout after ' + timeout + 'ms');
389
- finished = true;
390
- if (pollInterval) {
391
- clearInterval(pollInterval);
392
- }
376
+ console.error('[FaceDetectionEngine] OpenCV.js initialization timeout after ' + timeout + 'ms');
393
377
  reject(new Error('OpenCV.js initialization timeout'));
394
378
  }, timeout);
379
+ let resolved = false;
395
380
  const resolveOnce = (source) => {
396
- if (finished) {
397
- console.log('[resolveOnce] Already finished, ignoring call from:', source);
381
+ if (resolved)
398
382
  return;
399
- }
400
- finished = true;
401
- console.log('[resolveOnce] Marking as finished');
402
- // 立即停止所有定时器和轮询
383
+ resolved = true;
403
384
  clearTimeout(timeoutId);
404
- if (pollInterval !== null) {
405
- clearInterval(pollInterval);
406
- pollInterval = null;
407
- console.log('[resolveOnce] Poll interval cleared');
408
- }
385
+ clearInterval(pollInterval);
409
386
  const initTime = performance.now() - initStartTime;
410
- console.log(`OpenCV.js initialized (${source}), took ${initTime.toFixed(2)}ms`);
411
- // 标记初始化完成
412
- opencvInitialized = true;
413
- // 返回简单的标记,实际的 cv 对象已经在 globalThis.cv 上了
414
- resolve(initTime);
387
+ console.log(`[FaceDetectionEngine] OpenCV.js initialized (${source}), took ${initTime.toFixed(2)}ms`);
388
+ resolve(cvModule);
415
389
  };
416
390
  // 尝试设置回调(只有在 cvModule 可扩展时才尝试)
417
391
  const canSetCallback = cvModule && Object.isExtensible(cvModule);
418
392
  if (canSetCallback) {
419
393
  try {
420
394
  const originalOnRuntimeInitialized = cvModule.onRuntimeInitialized(cvModule).onRuntimeInitialized = () => {
421
- console.log('[onRuntimeInitialized] callback triggered');
395
+ console.log('[FaceDetectionEngine] onRuntimeInitialized callback triggered');
422
396
  // 调用原始回调(如果存在)
423
397
  if (originalOnRuntimeInitialized && typeof originalOnRuntimeInitialized === 'function') {
424
398
  try {
425
399
  originalOnRuntimeInitialized();
426
400
  }
427
401
  catch (e) {
428
- console.warn('[onRuntimeInitialized] callback failed:', e);
402
+ console.warn('[FaceDetectionEngine] Original onRuntimeInitialized callback failed:', e);
429
403
  }
430
404
  }
431
405
  resolveOnce('callback');
432
406
  };
433
- console.log('[onRuntimeInitialized] callback set successfully');
407
+ console.log('[FaceDetectionEngine] onRuntimeInitialized callback set successfully');
434
408
  }
435
409
  catch (e) {
436
- console.warn('[onRuntimeInitialized] Failed to set callback, will use polling:', e);
410
+ console.warn('[FaceDetectionEngine] Failed to set onRuntimeInitialized callback, will use polling:', e);
437
411
  }
438
412
  }
439
413
  else {
440
- console.log('[polling] cvModule is not extensible, using polling mode');
414
+ console.log('[FaceDetectionEngine] cvModule is not extensible, using polling mode');
441
415
  }
442
416
  // 启动轮询作为备用方案或主要方案
443
- pollInterval = setInterval(() => {
444
- console.log('[polling] Checking for Mat class...');
417
+ const pollInterval = setInterval(() => {
445
418
  // 优先检查 cvModule 中是否有 Mat
446
419
  if (cvModule.Mat) {
447
- console.log('[polling] Found Mat in cvModule');
448
420
  resolveOnce('cvModule polling');
449
421
  return;
450
422
  }
451
423
  // 其次检查 globalThis.cv 中是否有 Mat
452
424
  if (typeof globalThis !== 'undefined' && globalThis.cv && globalThis.cv.Mat) {
453
- console.log('[polling] Found Mat in globalThis.cv');
454
425
  cvModule = globalThis.cv;
455
426
  resolveOnce('globalThis.cv polling');
456
427
  return;
@@ -464,35 +435,52 @@ async function _initializeOpenCV(timeout) {
464
435
  * @returns Promise that resolves with cv module
465
436
  */
466
437
  async function loadOpenCV(timeout = 30000) {
438
+ let cv;
439
+ console.log('[FaceDetectionEngine] Loading OpenCV.js...');
467
440
  try {
468
- // 快速检查是否已经初始化完成
469
- if (opencvInitialized) {
470
- console.log('[loadOpenCV] Already initialized, returning immediately');
471
- return getCvSync();
472
- }
473
- // 等待初始化
474
- console.log('[loadOpenCV] Waiting for initialization...');
475
- if (!opencvInitPromise) {
476
- console.log('[loadOpenCV] Starting new initialization');
441
+ // 如果已经在初始化中,复用现有的 Promise
442
+ if (opencvInitPromise) {
443
+ console.log('[FaceDetectionEngine] OpenCV initialization in progress, waiting...');
444
+ cv = await opencvInitPromise;
445
+ }
446
+ else if (cvModule.Mat) {
447
+ // 检查 cvModule 是否已经初始化
448
+ console.log('[FaceDetectionEngine] OpenCV.js already initialized');
449
+ cv = cvModule;
450
+ }
451
+ else if (typeof globalThis !== 'undefined' && globalThis.cv && globalThis.cv.Mat) {
452
+ // 检查全局 cv 是否已经初始化
453
+ console.log('[FaceDetectionEngine] OpenCV.js already initialized (global)');
454
+ cvModule = globalThis.cv;
455
+ cv = cvModule;
456
+ }
457
+ else {
458
+ // 开始新的初始化
459
+ console.log('[FaceDetectionEngine] Starting OpenCV initialization...');
477
460
  opencvInitPromise = _initializeOpenCV(timeout);
461
+ try {
462
+ cv = await opencvInitPromise;
463
+ }
464
+ catch (error) {
465
+ // 失败后清除 Promise,允许重试
466
+ opencvInitPromise = null;
467
+ throw error;
468
+ }
478
469
  }
479
- console.log('[loadOpenCV] Awaiting opencvInitPromise');
480
- const initTime = await opencvInitPromise;
481
- // 获取初始化后的 cv 对象
482
- const cv = getCvSync();
483
- if (!cv) {
484
- console.error('[loadOpenCV] getCvSync returned null');
485
- throw new Error('OpenCV module is invalid');
470
+ // 最终验证
471
+ if (!cv || !cv.Mat) {
472
+ console.error('[FaceDetectionEngine] OpenCV module is invalid:', {
473
+ hasMat: cv && cv.Mat,
474
+ type: typeof cv,
475
+ keys: cv ? Object.keys(cv).slice(0, 10) : 'N/A'
476
+ });
477
+ throw new Error('OpenCV.js loaded but module is invalid (no Mat class found)');
486
478
  }
487
- console.log('[loadOpenCV] OpenCV.js load successfully', {
488
- initTime: `${initTime.toFixed(2)}ms`,
489
- version: getOpenCVVersion()
490
- });
491
- return cv;
479
+ console.log('[FaceDetectionEngine] OpenCV.js loaded successfully');
480
+ return { cv };
492
481
  }
493
482
  catch (error) {
494
- console.error('[loadOpenCV] OpenCV.js load failed', error);
495
- opencvInitPromise = null; // 失败时清除 Promise,允许重试
483
+ console.error('[FaceDetectionEngine] Failed to load OpenCV.js:', error);
496
484
  throw error;
497
485
  }
498
486
  }
@@ -511,35 +499,6 @@ function getCvSync() {
511
499
  }
512
500
  return null;
513
501
  }
514
- /**
515
- * Extract OpenCV version from getBuildInformation
516
- * @returns version string like "4.12.0"
517
- */
518
- function getOpenCVVersion() {
519
- try {
520
- const cv = getCvSync();
521
- if (!cv || !cv.getBuildInformation) {
522
- return 'unknown';
523
- }
524
- const buildInfo = cv.getBuildInformation();
525
- // 查找 "Version control:" 或 "OpenCV" 开头的行
526
- // 格式: "Version control: 4.12.0"
527
- const versionMatch = buildInfo.match(/Version\s+control:\s+(\d+\.\d+\.\d+)/i);
528
- if (versionMatch && versionMatch[1]) {
529
- return versionMatch[1];
530
- }
531
- // 备用方案:查找 "OpenCV X.X.X" 格式
532
- const opencvMatch = buildInfo.match(/OpenCV\s+(\d+\.\d+\.\d+)/i);
533
- if (opencvMatch && opencvMatch[1]) {
534
- return opencvMatch[1];
535
- }
536
- return 'unknown';
537
- }
538
- catch (error) {
539
- console.error('[getOpenCVVersion] Failed to get version:', error);
540
- return 'unknown';
541
- }
542
- }
543
502
  /**
544
503
  * Load Human.js
545
504
  * @param modelPath - Path to model files (optional)
@@ -547,8 +506,6 @@ function getOpenCVVersion() {
547
506
  * @returns Promise that resolves with Human instance
548
507
  */
549
508
  async function loadHuman(modelPath, wasmPath) {
550
- console.log('[loadHuman] START - creating config');
551
- const initStartTime = performance.now();
552
509
  const config = {
553
510
  backend: _detectOptimalBackend(),
554
511
  face: {
@@ -571,20 +528,24 @@ async function loadHuman(modelPath, wasmPath) {
571
528
  if (wasmPath) {
572
529
  config.wasmPath = wasmPath;
573
530
  }
574
- console.log('[loadHuman] Config:', {
531
+ console.log('[FaceDetectionEngine] Human.js config:', {
575
532
  backend: config.backend,
576
533
  modelBasePath: config.modelBasePath || '(using default)',
577
534
  wasmPath: config.wasmPath || '(using default)'
578
535
  });
579
- console.log('[loadHuman] Creating Human instance...');
536
+ const initStartTime = performance.now();
537
+ console.log('[FaceDetectionEngine] Creating Human instance...');
580
538
  const human = new Human(config);
581
- console.log('[loadHuman] Human instance created, starting load...');
539
+ const instanceCreateTime = performance.now() - initStartTime;
540
+ console.log(`[FaceDetectionEngine] Human instance created, took ${instanceCreateTime.toFixed(2)}ms`);
541
+ console.log('[FaceDetectionEngine] Loading Human.js models...');
542
+ const modelLoadStartTime = performance.now();
582
543
  try {
583
- console.log('[loadHuman] Calling human.load()...');
584
544
  await human.load();
585
- console.log('[loadHuman] human.load() completed');
545
+ const loadTime = performance.now() - modelLoadStartTime;
586
546
  const totalTime = performance.now() - initStartTime;
587
- console.log('[loadHuman] Loaded successfully', {
547
+ console.log('[FaceDetectionEngine] Human.js loaded successfully', {
548
+ modelLoadTime: `${loadTime.toFixed(2)}ms`,
588
549
  totalInitTime: `${totalTime.toFixed(2)}ms`,
589
550
  version: human.version
590
551
  });
@@ -592,33 +553,37 @@ async function loadHuman(modelPath, wasmPath) {
592
553
  }
593
554
  catch (error) {
594
555
  const errorMsg = error instanceof Error ? error.message : 'Unknown error';
595
- console.error('[loadHuman] Load failed:', errorMsg);
596
- console.error('[loadHuman] Error stack:', error instanceof Error ? error.stack : 'N/A');
556
+ console.error('[FaceDetectionEngine] Human.js load failed:', errorMsg);
597
557
  throw error;
598
558
  }
599
559
  }
600
- async function loadLibraries(modelPath, wasmPath, timeout = 30000) {
601
- console.log('[loadLibraries] Starting parallel load of OpenCV and Human...');
602
- const startTime = performance.now();
560
+ /**
561
+ * Extract OpenCV version from getBuildInformation
562
+ * @returns version string like "4.12.0"
563
+ */
564
+ function getOpenCVVersion() {
603
565
  try {
604
- console.log('[loadLibraries] Launching Promise.all with OpenCV and Human...');
605
- const [cv, human] = await Promise.all([
606
- loadOpenCV(timeout),
607
- loadHuman(modelPath, wasmPath)
608
- ]);
609
- console.log('[loadLibraries] Both promises resolved');
610
- const totalTime = performance.now() - startTime;
611
- console.log('[loadLibraries] libraries loaded successfully', {
612
- totalInitTime: `${totalTime.toFixed(2)}ms`,
613
- opencvVersion: getOpenCVVersion(),
614
- humanVersion: human.version
615
- });
616
- return { cv, human };
566
+ const cv = getCvSync();
567
+ if (!cv || !cv.getBuildInformation) {
568
+ return 'unknown';
569
+ }
570
+ const buildInfo = cv.getBuildInformation();
571
+ // 查找 "Version control:" 或 "OpenCV" 开头的行
572
+ // 格式: "Version control: 4.12.0"
573
+ const versionMatch = buildInfo.match(/Version\s+control:\s+(\d+\.\d+\.\d+)/i);
574
+ if (versionMatch && versionMatch[1]) {
575
+ return versionMatch[1];
576
+ }
577
+ // 备用方案:查找 "OpenCV X.X.X" 格式
578
+ const opencvMatch = buildInfo.match(/OpenCV\s+(\d+\.\d+\.\d+)/i);
579
+ if (opencvMatch && opencvMatch[1]) {
580
+ return opencvMatch[1];
581
+ }
582
+ return 'unknown';
617
583
  }
618
584
  catch (error) {
619
- const errorMsg = error instanceof Error ? error.message : 'Unknown error';
620
- console.error('[loadLibraries] Failed to load libraries:', errorMsg);
621
- throw error;
585
+ console.error('[getOpenCVVersion] Failed to get version:', error);
586
+ return 'unknown';
622
587
  }
623
588
  }
624
589
 
@@ -1599,13 +1564,12 @@ class FaceDetectionEngine extends SimpleEventEmitter {
1599
1564
  this.isInitializing = true;
1600
1565
  this.emitDebug('initialization', 'Starting to load detection libraries...');
1601
1566
  try {
1602
- // Load Libraries
1603
- this.emitDebug('initialization', 'Loading Libraries...');
1604
- const startLoadTime = performance.now();
1605
- const { cv, human } = await loadLibraries(this.config.human_model_path, this.config.tensorflow_wasm_path, 30000);
1567
+ // Load OpenCV
1568
+ this.emitDebug('initialization', 'Loading OpenCV...');
1569
+ const { cv } = await loadOpenCV(60000); // 1 minute timeout
1606
1570
  if (!cv || !cv.Mat) {
1607
1571
  console.log('[FaceDetectionEngine] Failed to load OpenCV.js: module is null or invalid');
1608
- this.emit('detector-loaded', {
1572
+ this.emit('detector-error', {
1609
1573
  success: false,
1610
1574
  error: 'Failed to load OpenCV.js: module is null or invalid'
1611
1575
  });
@@ -1615,9 +1579,23 @@ class FaceDetectionEngine extends SimpleEventEmitter {
1615
1579
  });
1616
1580
  return;
1617
1581
  }
1618
- if (!human) {
1582
+ const cv_version = getOpenCVVersion();
1583
+ this.emitDebug('initialization', 'OpenCV loaded successfully', {
1584
+ version: cv_version
1585
+ });
1586
+ console.log('[FaceDetectionEngine] OpenCV loaded successfully', {
1587
+ version: cv_version
1588
+ });
1589
+ // Load Human.js
1590
+ console.log('[FaceDetectionEngine] Loading Human.js models...');
1591
+ this.emitDebug('initialization', 'Loading Human.js...');
1592
+ const humanStartTime = performance.now();
1593
+ this.human = await loadHuman(this.config.human_model_path, this.config.tensorflow_wasm_path);
1594
+ const humanLoadTime = performance.now() - humanStartTime;
1595
+ if (!this.human) {
1619
1596
  const errorMsg = 'Failed to load Human.js: instance is null';
1620
1597
  console.log('[FaceDetectionEngine] ' + errorMsg);
1598
+ this.emitDebug('initialization', errorMsg, { loadTime: humanLoadTime }, 'error');
1621
1599
  this.emit('detector-loaded', {
1622
1600
  success: false,
1623
1601
  error: errorMsg
@@ -1628,16 +1606,21 @@ class FaceDetectionEngine extends SimpleEventEmitter {
1628
1606
  });
1629
1607
  return;
1630
1608
  }
1631
- // Store human instance
1632
- this.human = human;
1609
+ this.emitDebug('initialization', 'Human.js loaded successfully', {
1610
+ loadTime: `${humanLoadTime.toFixed(2)}ms`,
1611
+ version: this.human.version
1612
+ });
1613
+ console.log('[FaceDetectionEngine] Human.js loaded successfully', {
1614
+ loadTime: `${humanLoadTime.toFixed(2)}ms`,
1615
+ version: this.human.version
1616
+ });
1633
1617
  this.isReady = true;
1634
1618
  const loadedData = {
1635
1619
  success: true,
1636
- opencv_version: getOpenCVVersion(),
1620
+ opencv_version: cv_version,
1637
1621
  human_version: this.human.version
1638
1622
  };
1639
1623
  console.log('[FaceDetectionEngine] Engine initialized and ready', {
1640
- initCostTime: (performance.now() - startLoadTime).toFixed(2),
1641
1624
  opencv_version: loadedData.opencv_version,
1642
1625
  human_version: loadedData.human_version
1643
1626
  });