@sssxyd/face-liveness-detector 0.2.25 → 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,38 +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
- const cv = getCvSync();
472
- if (cv) {
473
- return { cv };
474
- }
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;
475
456
  }
476
- // 等待初始化
477
- console.log('[loadOpenCV] Waiting for initialization...');
478
- if (!opencvInitPromise) {
479
- console.log('[loadOpenCV] Starting new initialization');
457
+ else {
458
+ // 开始新的初始化
459
+ console.log('[FaceDetectionEngine] Starting OpenCV initialization...');
480
460
  opencvInitPromise = _initializeOpenCV(timeout);
461
+ try {
462
+ cv = await opencvInitPromise;
463
+ }
464
+ catch (error) {
465
+ // 失败后清除 Promise,允许重试
466
+ opencvInitPromise = null;
467
+ throw error;
468
+ }
481
469
  }
482
- console.log('[loadOpenCV] Awaiting opencvInitPromise');
483
- const initTime = await opencvInitPromise;
484
- // 获取初始化后的 cv 对象
485
- const cv = getCvSync();
486
- if (!cv) {
487
- console.error('[loadOpenCV] getCvSync returned null');
488
- 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)');
489
478
  }
490
- console.log('[loadOpenCV] OpenCV.js load successfully', {
491
- initTime: `${initTime.toFixed(2)}ms`,
492
- version: getOpenCVVersion()
493
- });
494
- return cv;
479
+ console.log('[FaceDetectionEngine] OpenCV.js loaded successfully');
480
+ return { cv };
495
481
  }
496
482
  catch (error) {
497
- console.error('[loadOpenCV] OpenCV.js load failed', error);
498
- opencvInitPromise = null; // 失败时清除 Promise,允许重试
483
+ console.error('[FaceDetectionEngine] Failed to load OpenCV.js:', error);
499
484
  throw error;
500
485
  }
501
486
  }
@@ -514,35 +499,6 @@ function getCvSync() {
514
499
  }
515
500
  return null;
516
501
  }
517
- /**
518
- * Extract OpenCV version from getBuildInformation
519
- * @returns version string like "4.12.0"
520
- */
521
- function getOpenCVVersion() {
522
- try {
523
- const cv = getCvSync();
524
- if (!cv || !cv.getBuildInformation) {
525
- return 'unknown';
526
- }
527
- const buildInfo = cv.getBuildInformation();
528
- // 查找 "Version control:" 或 "OpenCV" 开头的行
529
- // 格式: "Version control: 4.12.0"
530
- const versionMatch = buildInfo.match(/Version\s+control:\s+(\d+\.\d+\.\d+)/i);
531
- if (versionMatch && versionMatch[1]) {
532
- return versionMatch[1];
533
- }
534
- // 备用方案:查找 "OpenCV X.X.X" 格式
535
- const opencvMatch = buildInfo.match(/OpenCV\s+(\d+\.\d+\.\d+)/i);
536
- if (opencvMatch && opencvMatch[1]) {
537
- return opencvMatch[1];
538
- }
539
- return 'unknown';
540
- }
541
- catch (error) {
542
- console.error('[getOpenCVVersion] Failed to get version:', error);
543
- return 'unknown';
544
- }
545
- }
546
502
  /**
547
503
  * Load Human.js
548
504
  * @param modelPath - Path to model files (optional)
@@ -550,7 +506,6 @@ function getOpenCVVersion() {
550
506
  * @returns Promise that resolves with Human instance
551
507
  */
552
508
  async function loadHuman(modelPath, wasmPath) {
553
- const initStartTime = performance.now();
554
509
  const config = {
555
510
  backend: _detectOptimalBackend(),
556
511
  face: {
@@ -573,16 +528,24 @@ async function loadHuman(modelPath, wasmPath) {
573
528
  if (wasmPath) {
574
529
  config.wasmPath = wasmPath;
575
530
  }
576
- console.log('[loadHuman] Config:', {
531
+ console.log('[FaceDetectionEngine] Human.js config:', {
577
532
  backend: config.backend,
578
533
  modelBasePath: config.modelBasePath || '(using default)',
579
534
  wasmPath: config.wasmPath || '(using default)'
580
535
  });
536
+ const initStartTime = performance.now();
537
+ console.log('[FaceDetectionEngine] Creating Human instance...');
581
538
  const human = new Human(config);
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
544
  await human.load();
545
+ const loadTime = performance.now() - modelLoadStartTime;
584
546
  const totalTime = performance.now() - initStartTime;
585
- console.log('[loadHuman] Loaded successfully', {
547
+ console.log('[FaceDetectionEngine] Human.js loaded successfully', {
548
+ modelLoadTime: `${loadTime.toFixed(2)}ms`,
586
549
  totalInitTime: `${totalTime.toFixed(2)}ms`,
587
550
  version: human.version
588
551
  });
@@ -590,40 +553,37 @@ async function loadHuman(modelPath, wasmPath) {
590
553
  }
591
554
  catch (error) {
592
555
  const errorMsg = error instanceof Error ? error.message : 'Unknown error';
593
- console.error('[loadHuman] Load failed:', errorMsg);
556
+ console.error('[FaceDetectionEngine] Human.js load failed:', errorMsg);
594
557
  throw error;
595
558
  }
596
559
  }
597
- async function loadLibraries(modelPath, wasmPath, timeout) {
598
- console.log('[loadLibraries] Starting parallel load of OpenCV and Human...');
599
- const startTime = performance.now();
600
- if (timeout == undefined) {
601
- timeout = 30000;
602
- }
560
+ /**
561
+ * Extract OpenCV version from getBuildInformation
562
+ * @returns version string like "4.12.0"
563
+ */
564
+ function getOpenCVVersion() {
603
565
  try {
604
- const cv = await loadOpenCV(timeout);
605
- if (!cv) {
606
- throw new Error('Failed to load OpenCV');
566
+ const cv = getCvSync();
567
+ if (!cv || !cv.getBuildInformation) {
568
+ return 'unknown';
607
569
  }
608
- const human = await loadHuman(modelPath, wasmPath);
609
- if (!human) {
610
- throw new Error('Failed to load Human');
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];
611
576
  }
612
- const totalTime = performance.now() - startTime;
613
- console.log('[loadLibraries] libraries loaded successfully', {
614
- totalInitTime: `${totalTime.toFixed(2)}ms`,
615
- opencvVersion: getOpenCVVersion(),
616
- humanVersion: human.version
617
- });
618
- return {
619
- cv,
620
- human
621
- };
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';
622
583
  }
623
584
  catch (error) {
624
- const errorMsg = error instanceof Error ? error.message : 'Unknown error';
625
- console.error('[loadLibraries] Failed to load libraries:', errorMsg);
626
- throw error;
585
+ console.error('[getOpenCVVersion] Failed to get version:', error);
586
+ return 'unknown';
627
587
  }
628
588
  }
629
589
 
@@ -1604,17 +1564,66 @@ class FaceDetectionEngine extends SimpleEventEmitter {
1604
1564
  this.isInitializing = true;
1605
1565
  this.emitDebug('initialization', 'Starting to load detection libraries...');
1606
1566
  try {
1607
- // Load Libraries
1608
- this.emitDebug('initialization', 'Loading Libraries...');
1609
- const { human } = await loadLibraries(this.config.human_model_path, this.config.tensorflow_wasm_path, 30000);
1610
- // Store human instance
1611
- this.human = human;
1567
+ // Load OpenCV
1568
+ this.emitDebug('initialization', 'Loading OpenCV...');
1569
+ const { cv } = await loadOpenCV(60000); // 1 minute timeout
1570
+ if (!cv || !cv.Mat) {
1571
+ console.log('[FaceDetectionEngine] Failed to load OpenCV.js: module is null or invalid');
1572
+ this.emit('detector-error', {
1573
+ success: false,
1574
+ error: 'Failed to load OpenCV.js: module is null or invalid'
1575
+ });
1576
+ this.emit('detector-error', {
1577
+ code: ErrorCode.DETECTOR_NOT_INITIALIZED,
1578
+ message: 'Failed to load OpenCV.js: module is null or invalid'
1579
+ });
1580
+ return;
1581
+ }
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) {
1596
+ const errorMsg = 'Failed to load Human.js: instance is null';
1597
+ console.log('[FaceDetectionEngine] ' + errorMsg);
1598
+ this.emitDebug('initialization', errorMsg, { loadTime: humanLoadTime }, 'error');
1599
+ this.emit('detector-loaded', {
1600
+ success: false,
1601
+ error: errorMsg
1602
+ });
1603
+ this.emit('detector-error', {
1604
+ code: ErrorCode.DETECTOR_NOT_INITIALIZED,
1605
+ message: errorMsg
1606
+ });
1607
+ return;
1608
+ }
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
+ });
1612
1617
  this.isReady = true;
1613
1618
  const loadedData = {
1614
1619
  success: true,
1615
- opencv_version: getOpenCVVersion(),
1620
+ opencv_version: cv_version,
1616
1621
  human_version: this.human.version
1617
1622
  };
1623
+ console.log('[FaceDetectionEngine] Engine initialized and ready', {
1624
+ opencv_version: loadedData.opencv_version,
1625
+ human_version: loadedData.human_version
1626
+ });
1618
1627
  this.emit('detector-loaded', loadedData);
1619
1628
  this.emitDebug('initialization', 'Engine initialized and ready', loadedData);
1620
1629
  }