@jaak.ai/stamps 2.0.0-beta.3 → 2.0.0-beta.4

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.
Files changed (72) hide show
  1. package/README.md +216 -215
  2. package/dist/cjs/jaak-stamps-webcomponent.cjs.js +1 -1
  3. package/dist/cjs/jaak-stamps.cjs.entry.js +1786 -1052
  4. package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -1
  5. package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -1
  6. package/dist/cjs/loader.cjs.js +1 -1
  7. package/dist/collection/components/my-component/my-component.css +440 -110
  8. package/dist/collection/components/my-component/my-component.js +829 -1120
  9. package/dist/collection/components/my-component/my-component.js.map +1 -1
  10. package/dist/collection/services/CameraService.js +453 -0
  11. package/dist/collection/services/CameraService.js.map +1 -0
  12. package/dist/collection/services/DetectionService.js +369 -0
  13. package/dist/collection/services/DetectionService.js.map +1 -0
  14. package/dist/collection/services/EventBusService.js +42 -0
  15. package/dist/collection/services/EventBusService.js.map +1 -0
  16. package/dist/collection/services/LoggerService.js +40 -0
  17. package/dist/collection/services/LoggerService.js.map +1 -0
  18. package/dist/collection/services/ServiceContainer.js +66 -0
  19. package/dist/collection/services/ServiceContainer.js.map +1 -0
  20. package/dist/collection/services/StateManagerService.js +109 -0
  21. package/dist/collection/services/StateManagerService.js.map +1 -0
  22. package/dist/collection/services/factories/DeviceStrategyFactory.js +16 -0
  23. package/dist/collection/services/factories/DeviceStrategyFactory.js.map +1 -0
  24. package/dist/collection/services/interfaces/ICameraService.js +2 -0
  25. package/dist/collection/services/interfaces/ICameraService.js.map +1 -0
  26. package/dist/collection/services/interfaces/IDetectionService.js +2 -0
  27. package/dist/collection/services/interfaces/IDetectionService.js.map +1 -0
  28. package/dist/collection/services/interfaces/IEventBus.js +2 -0
  29. package/dist/collection/services/interfaces/IEventBus.js.map +1 -0
  30. package/dist/collection/services/interfaces/ILogger.js +2 -0
  31. package/dist/collection/services/interfaces/ILogger.js.map +1 -0
  32. package/dist/collection/services/interfaces/IStateManager.js +2 -0
  33. package/dist/collection/services/interfaces/IStateManager.js.map +1 -0
  34. package/dist/collection/services/strategies/HighPerformanceDeviceStrategy.js +30 -0
  35. package/dist/collection/services/strategies/HighPerformanceDeviceStrategy.js.map +1 -0
  36. package/dist/collection/services/strategies/IDeviceStrategy.js +2 -0
  37. package/dist/collection/services/strategies/IDeviceStrategy.js.map +1 -0
  38. package/dist/collection/services/strategies/LowMemoryDeviceStrategy.js +30 -0
  39. package/dist/collection/services/strategies/LowMemoryDeviceStrategy.js.map +1 -0
  40. package/dist/collection/types/component-types.js +2 -0
  41. package/dist/collection/types/component-types.js.map +1 -0
  42. package/dist/components/jaak-stamps.js +1802 -1076
  43. package/dist/components/jaak-stamps.js.map +1 -1
  44. package/dist/esm/jaak-stamps-webcomponent.js +1 -1
  45. package/dist/esm/jaak-stamps.entry.js +1786 -1052
  46. package/dist/esm/jaak-stamps.entry.js.map +1 -1
  47. package/dist/esm/loader.js +1 -1
  48. package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +1 -1
  49. package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -1
  50. package/dist/jaak-stamps-webcomponent/p-10ee2dab.entry.js +2 -0
  51. package/dist/jaak-stamps-webcomponent/p-10ee2dab.entry.js.map +1 -0
  52. package/dist/types/components/my-component/my-component.d.ts +83 -108
  53. package/dist/types/components.d.ts +23 -9
  54. package/dist/types/services/CameraService.d.ts +46 -0
  55. package/dist/types/services/DetectionService.d.ts +35 -0
  56. package/dist/types/services/EventBusService.d.ts +9 -0
  57. package/dist/types/services/LoggerService.d.ts +12 -0
  58. package/dist/types/services/ServiceContainer.d.ts +27 -0
  59. package/dist/types/services/StateManagerService.d.ts +15 -0
  60. package/dist/types/services/factories/DeviceStrategyFactory.d.ts +4 -0
  61. package/dist/types/services/interfaces/ICameraService.d.ts +34 -0
  62. package/dist/types/services/interfaces/IDetectionService.d.ts +31 -0
  63. package/dist/types/services/interfaces/IEventBus.d.ts +16 -0
  64. package/dist/types/services/interfaces/ILogger.d.ts +8 -0
  65. package/dist/types/services/interfaces/IStateManager.d.ts +35 -0
  66. package/dist/types/services/strategies/HighPerformanceDeviceStrategy.d.ts +6 -0
  67. package/dist/types/services/strategies/IDeviceStrategy.d.ts +21 -0
  68. package/dist/types/services/strategies/LowMemoryDeviceStrategy.d.ts +6 -0
  69. package/dist/types/types/component-types.d.ts +36 -0
  70. package/package.json +3 -3
  71. package/dist/jaak-stamps-webcomponent/p-14eb13d8.entry.js +0 -2
  72. package/dist/jaak-stamps-webcomponent/p-14eb13d8.entry.js.map +0 -1
@@ -2,120 +2,211 @@
2
2
 
3
3
  var index = require('./index-BfhtOB0D.js');
4
4
 
5
- const myComponentCss = ":host{display:block;width:100%;height:100%;font-family:system-ui, -apple-system, sans-serif;color:#1a1a1a}.detector-container{display:flex;flex-direction:column;align-items:center;width:100%;height:100%}h1{font-size:24px;font-weight:500;color:#333;margin:0 0 24px 0}.video-container{position:relative;width:100%;height:100%;background:#333;border:1px solid #e0e0e0;border-radius:8px;overflow:hidden}video,canvas{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,canvas.mirror{transform:rotateY(180deg)}canvas{z-index:1}video{z-index:0}.status{margin-top:16px;font-size:12px;color:#666}.overlay-mask{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10;display:block;pointer-events:none}.card-outline{position:absolute;top:var(--mask-center-y, 50%);left:var(--mask-center-x, 50%);transform:translate(-50%, -50%);width:var(--mask-width, 88%);height:var(--mask-height, 55%);border:none;border-radius:4px;background:transparent;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7);opacity:0.8}.card-outline.perfect-match{box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7)}.side{position:absolute;background:#999;transition:background-color 0.3s ease}.side.aligned{background:#28a745}.side-top{top:0;left:0;width:100%;height:3px}.side-right{top:0;right:0;width:3px;height:100%}.side-bottom{bottom:0;left:0;width:100%;height:3px}.side-left{top:0;left:0;width:3px;height:100%}.corner{position:absolute;width:20px;height:20px;border:2px solid #999;z-index:12}.corner-tl{top:-10px;left:-10px;border-right:none;border-bottom:none}.corner-tr{top:-10px;right:-10px;border-left:none;border-bottom:none}.corner-bl{bottom:-10px;left:-10px;border-right:none;border-top:none}.corner-br{bottom:-10px;right:-10px;border-left:none;border-top:none}.corner.perfect-match{border-color:#28a745}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);color:#fff;font-size:14px;font-weight:600;text-align:center;white-space:normal;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;z-index:20}.capture-animation{position:absolute;top:0;left:0;width:100%;height:100%;background:#fff;opacity:0;z-index:30;pointer-events:none;animation:captureFlash 0.6s ease-out}@keyframes captureFlash{0%{opacity:0}15%{opacity:0.8}30%{opacity:0}45%{opacity:0.4}60%{opacity:0}100%{opacity:0}}.card-outline.capturing{animation:pulseGreen 0.6s ease-out}@keyframes pulseGreen{0%{border-color:#28a745;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7), 0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7), 0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 9999px rgba(0, 0, 0, 0.7), 0 0 0 4px rgba(40, 167, 69, 0)}}.flip-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showFlipInstruction 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.id-card-icon{width:80px;height:50px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:8px;position:relative;animation:flipCard 2s ease-in-out infinite;box-shadow:0 4px 12px rgba(0, 0, 0, 0.3)}.id-card-icon::before{content:'';position:absolute;top:8px;left:8px;width:16px;height:12px;background:rgba(255, 255, 255, 0.9);border-radius:2px}.id-card-icon::after{content:'';position:absolute;top:25px;left:8px;width:64px;height:3px;background:rgba(255, 255, 255, 0.7);border-radius:1px;box-shadow:0 6px 0 rgba(255, 255, 255, 0.7), 0 12px 0 rgba(255, 255, 255, 0.7)}.flip-text{margin-top:12px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px}@keyframes showFlipInstruction{0%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}}@keyframes flipCard{0%{transform:rotateY(0deg)}50%{transform:rotateY(180deg)}100%{transform:rotateY(360deg)}}.success-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showSuccessMessage 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.check-icon{width:80px;height:80px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:50%;position:relative;animation:bounceSuccess 0.6s ease-out;box-shadow:0 4px 16px rgba(108, 117, 125, 0.4);display:flex;align-items:center;justify-content:center}.check-icon::before{content:'';position:absolute;width:20px;height:35px;border:4px solid #fff;border-top:none;border-left:none;transform:rotate(45deg);animation:drawCheck 0.4s ease-out 0.2s both}.success-text{margin-top:16px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;animation:fadeInUp 0.5s ease-out 0.4s both}@keyframes showSuccessMessage{0%{opacity:0;transform:translate(-50%, -50%) scale(0.5)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.9)}}@keyframes bounceSuccess{0%{transform:scale(0)}50%{transform:scale(1.1)}100%{transform:scale(1)}}@keyframes drawCheck{0%{width:0;height:0}50%{width:20px;height:0}100%{width:20px;height:35px}}@keyframes fadeInUp{0%{opacity:0;transform:translateY(20px)}100%{opacity:1;transform:translateY(0)}}.skip-button{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.skip-button:hover{background:#f8f9fa}.skip-button:active{background:#e9ecef;transform:translateX(-50%) translateY(0)}.camera-controls{position:absolute;top:16px;right:16px;z-index:25;display:flex;gap:8px;pointer-events:auto}.flip-camera-button{height:40px;padding:0 16px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.6);backdrop-filter:blur(12px);color:#ffffff;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s ease;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255, 255, 255, 0.1);white-space:nowrap;min-width:fit-content}.camera-selector-button{height:40px;padding:0 16px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.6);backdrop-filter:blur(12px);color:#ffffff;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s ease;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255, 255, 255, 0.1);white-space:nowrap;min-width:fit-content}.flip-camera-button:hover,.camera-selector-button:hover{background:rgba(0, 0, 0, 0.8);border-color:rgba(255, 255, 255, 0.2);transform:translateY(-1px)}.flip-camera-button:active,.camera-selector-button:active{transform:translateY(0);background:rgba(0, 0, 0, 0.9)}.camera-selector-dropdown{position:absolute;top:56px;right:16px;z-index:30;background:rgba(0, 0, 0, 0.85);backdrop-filter:blur(20px);border-radius:12px;min-width:260px;max-width:300px;border:1px solid rgba(255, 255, 255, 0.1);overflow:hidden;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-8px) scale(0.95)}100%{opacity:1;transform:translateY(0) scale(1)}}.camera-selector-header{display:flex;justify-content:space-between;align-items:center;padding:12px 16px;border-bottom:1px solid rgba(255, 255, 255, 0.1)}.camera-selector-header span{font-weight:500;color:#ffffff;font-size:13px;opacity:0.9}.close-selector{width:20px;height:20px;border:none;background:none;color:rgba(255, 255, 255, 0.7);font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all 0.2s ease}.close-selector:hover{background:rgba(255, 255, 255, 0.1);color:#ffffff}.camera-list{padding:4px 0;max-height:240px;overflow-y:auto}.camera-option{width:100%;padding:10px 16px;border:none;background:none;text-align:left;cursor:pointer;transition:all 0.2s ease;display:flex;justify-content:space-between;align-items:center;color:rgba(255, 255, 255, 0.9)}.camera-option:hover{background:rgba(255, 255, 255, 0.08)}.camera-option.selected{background:rgba(255, 255, 255, 0.12);color:#ffffff}.camera-label{font-size:13px;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-right:8px;font-weight:400}.selected-indicator{font-size:14px;color:#ffffff;opacity:0.9}.device-info{padding:8px 16px;border-top:1px solid rgba(255, 255, 255, 0.1);background:rgba(255, 255, 255, 0.05)}.device-info small{color:rgba(255, 255, 255, 0.6);font-size:11px;text-transform:capitalize;font-weight:400}@media (max-width: 480px){.camera-controls{top:12px;right:12px;gap:6px}.flip-camera-button{height:36px;padding:0 12px;font-size:11px;border-radius:6px}.camera-selector-button{height:36px;padding:0 12px;font-size:11px;border-radius:6px}.camera-selector-dropdown{right:12px;top:48px;min-width:240px;max-width:calc(100vw - 24px)}.camera-selector-header{padding:10px 14px}.camera-option{padding:8px 14px}.device-info{padding:6px 14px}}.watermark{position:absolute;bottom:12px;right:12px;z-index:15;pointer-events:none;opacity:0.7}.watermark img{height:24px;width:auto;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.8);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:20px}.loading-spinner{width:60px;height:60px;border:4px solid rgba(255, 255, 255, 0.2);border-top:4px solid #007bff;border-radius:50%;animation:spin 1s linear infinite;margin-bottom:20px}.loading-text{color:white;font-size:16px;font-weight:500;text-align:center;opacity:0.9}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}";
5
+ class LoggerService {
6
+ debugMode;
7
+ constructor(debug = false) {
8
+ this.debugMode = debug;
9
+ }
10
+ setDebugMode(debug) {
11
+ this.debugMode = debug;
12
+ }
13
+ info(...args) {
14
+ if (this.debugMode) {
15
+ console.log(`[JAAK-STAMPS] [INFO] [${new Date().toLocaleTimeString()}]`, ...args);
16
+ }
17
+ }
18
+ warn(...args) {
19
+ if (this.debugMode) {
20
+ console.warn(`[JAAK-STAMPS] [WARN] [${new Date().toLocaleTimeString()}]`, ...args);
21
+ }
22
+ }
23
+ error(...args) {
24
+ if (this.debugMode) {
25
+ console.error(`[JAAK-STAMPS] [ERROR] [${new Date().toLocaleTimeString()}]`, ...args);
26
+ }
27
+ }
28
+ debug(...args) {
29
+ if (this.debugMode) {
30
+ console.debug(`[JAAK-STAMPS] [DEBUG] [${new Date().toLocaleTimeString()}]`, ...args);
31
+ }
32
+ }
33
+ state(state, data) {
34
+ if (this.debugMode) {
35
+ console.log(`[JAAK-STAMPS] [STATE] [${new Date().toLocaleTimeString()}] ${state}`, data || '');
36
+ }
37
+ }
38
+ performance(operation, duration) {
39
+ if (this.debugMode) {
40
+ console.log(`[JAAK-STAMPS] [PERF] [${new Date().toLocaleTimeString()}] ${operation}: ${duration}ms`);
41
+ }
42
+ }
43
+ }
6
44
 
7
- const JaakStamps = class {
8
- constructor(hostRef) {
9
- index.registerInstance(this, hostRef);
10
- this.captureCompleted = index.createEvent(this, "captureCompleted");
11
- this.isReady = index.createEvent(this, "isReady");
45
+ class EventBusService {
46
+ events = new Map();
47
+ on(event, callback) {
48
+ if (!this.events.has(event)) {
49
+ this.events.set(event, []);
50
+ }
51
+ this.events.get(event).push(callback);
12
52
  }
13
- get el() { return index.getElement(this); }
14
- debug = false;
15
- alignmentTolerance = 10; // Tolerancia en píxeles para considerar un lado alineado (escalado para 320x320)
16
- maskSize = 90; // Porcentaje del video que ocupará la máscara (default 90%)
17
- cropMargin = 0; // Margen en píxeles para el recorte del documento (default 0)
18
- useDocumentClassification = false; // Habilita la clasificación automática de documentos para determinar si solicitar reverso
19
- preferredCamera = 'auto'; // Define qué cámara usar: 'auto' (automático según dispositivo), 'front' (frontal), 'back' (trasera)
20
- captureCompleted;
21
- isReady;
22
- isVideoActive = false;
23
- statusMessage = 'Presione el botón para activar la cámara';
24
- statusColor = '#aaa';
25
- bestScore = 0;
26
- capturedFullFrame = null;
27
- capturedCroppedId = null;
28
- capturedBackFullFrame = null;
29
- capturedBackCroppedId = null;
30
- captureStep = 'front';
31
- isCapturing = false;
32
- showFlipAnimation = false;
33
- showSuccessAnimation = false;
34
- shouldMirrorVideo = true;
35
- sideAlignment = {
36
- top: false,
37
- right: false,
38
- bottom: false,
39
- left: false
40
- };
41
- isDetectionPaused = false;
42
- isLoading = false;
43
- isModelPreloaded = false;
44
- isMaskReady = false;
45
- availableCameras = [];
46
- selectedCameraId = null;
47
- showCameraSelector = false;
48
- isMultipleCamerasAvailable = false;
49
- videoRef;
50
- canvasRef;
51
- session;
52
- startTime;
53
- videoStream;
54
- animationId;
55
- hasScreenshotTaken = false;
56
- lastDetectedBox;
57
- mobileNetSession;
58
- mobileNetClassMap;
59
- // Camera management properties
60
- deviceType = 'desktop';
61
- preferredCameraFacing = null;
62
- // Performance optimization properties
63
- frameSkipCounter = 0;
64
- FRAME_SKIP = 2; // Process every 3rd frame (reduces CPU by ~66%)
65
- consecutiveFailures = 0;
66
- MAX_FAILURES = 30; // 0.5 seconds without detection
67
- lastInferenceTime = 0;
68
- MIN_INFERENCE_INTERVAL = 50; // Minimum 50ms between inferences
69
- // Canvas pooling for memory optimization
70
- preprocessCanvas;
71
- preprocessCtx;
72
- captureCanvas;
73
- captureCtx;
74
- MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v1.onnx";
75
- MOBILENET_MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.onnx";
76
- MOBILENET_CLASSES_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";
77
- INPUT_SIZE = 320;
78
- CONFIDENCE_THRESHOLD = 0.6;
79
- // ISO/IEC 7810 ID-1 standard dimensions (85.60mm x 53.98mm)
80
- ID1_ASPECT_RATIO = 85.60 / 53.98; // 1.5863320574...
81
- debugLog(...args) {
82
- if (this.debug) {
83
- console.log(...args);
53
+ off(event, callback) {
54
+ const callbacks = this.events.get(event);
55
+ if (callbacks) {
56
+ const index = callbacks.indexOf(callback);
57
+ if (index > -1) {
58
+ callbacks.splice(index, 1);
59
+ }
84
60
  }
85
61
  }
86
- validateMaskSize() {
87
- if (this.maskSize < 50 || this.maskSize > 100) {
88
- console.warn(`maskSize debe estar entre 50 y 100. Valor actual: ${this.maskSize}. Usando valor por defecto: 90`);
89
- this.maskSize = 90;
62
+ emit(event, data) {
63
+ const callbacks = this.events.get(event);
64
+ if (callbacks) {
65
+ callbacks.forEach(callback => {
66
+ try {
67
+ callback(data);
68
+ }
69
+ catch (error) {
70
+ console.error(`Error in event callback for ${event}:`, error);
71
+ }
72
+ });
90
73
  }
91
74
  }
92
- validateCropMargin() {
93
- if (this.cropMargin < 0 || this.cropMargin > 100) {
94
- console.warn(`cropMargin debe estar entre 0 y 100. Valor actual: ${this.cropMargin}. Usando valor por defecto: 0`);
95
- this.cropMargin = 0;
75
+ once(event, callback) {
76
+ const onceCallback = (data) => {
77
+ callback(data);
78
+ this.off(event, onceCallback);
79
+ };
80
+ this.on(event, onceCallback);
81
+ }
82
+ clear() {
83
+ this.events.clear();
84
+ }
85
+ }
86
+
87
+ class StateManagerService {
88
+ eventBus;
89
+ captureState = {
90
+ step: 'front',
91
+ isCapturing: false,
92
+ isDetectionPaused: false,
93
+ isVideoActive: false,
94
+ isLoading: false,
95
+ showFlipAnimation: false,
96
+ showSuccessAnimation: false,
97
+ bestScore: 0,
98
+ hasScreenshotTaken: false
99
+ };
100
+ capturedImages = {
101
+ front: {
102
+ fullFrame: null,
103
+ cropped: null
104
+ },
105
+ back: {
106
+ fullFrame: null,
107
+ cropped: null
108
+ },
109
+ metadata: {
110
+ totalImages: 0,
111
+ processCompleted: false,
112
+ backCaptureSkipped: false
96
113
  }
114
+ };
115
+ constructor(eventBus) {
116
+ this.eventBus = eventBus;
97
117
  }
98
- validatePreferredCamera() {
99
- const validOptions = ['auto', 'front', 'back'];
100
- if (!validOptions.includes(this.preferredCamera)) {
101
- console.warn(`preferredCamera debe ser uno de: ${validOptions.join(', ')}. Valor actual: ${this.preferredCamera}. Usando valor por defecto: 'auto'`);
102
- this.preferredCamera = 'auto';
118
+ getCaptureState() {
119
+ return { ...this.captureState };
120
+ }
121
+ updateCaptureState(updates) {
122
+ const previousState = { ...this.captureState };
123
+ this.captureState = { ...this.captureState, ...updates };
124
+ // Emit state change event
125
+ this.eventBus.emit('state-changed', {
126
+ previous: previousState,
127
+ current: this.captureState,
128
+ changes: updates
129
+ });
130
+ }
131
+ getCapturedImages() {
132
+ return JSON.parse(JSON.stringify(this.capturedImages));
133
+ }
134
+ setCapturedImages(images) {
135
+ this.capturedImages = {
136
+ ...this.capturedImages,
137
+ ...images,
138
+ metadata: {
139
+ ...this.capturedImages.metadata,
140
+ ...images.metadata
141
+ }
142
+ };
143
+ // Update total images count
144
+ let totalImages = 0;
145
+ if (this.capturedImages.front.fullFrame && this.capturedImages.front.cropped) {
146
+ totalImages += 2;
147
+ }
148
+ if (this.capturedImages.back.fullFrame && this.capturedImages.back.cropped) {
149
+ totalImages += 2;
103
150
  }
151
+ this.capturedImages.metadata.totalImages = totalImages;
104
152
  }
105
- emitReadyEvent() {
106
- const isDocumentReady = !!window.ort && this.isModelPreloaded;
107
- this.isReady.emit(isDocumentReady);
108
- this.debugLog('🟢 isReady event emitted:', isDocumentReady);
153
+ reset() {
154
+ this.captureState = {
155
+ step: 'front',
156
+ isCapturing: false,
157
+ isDetectionPaused: false,
158
+ isVideoActive: false,
159
+ isLoading: false,
160
+ showFlipAnimation: false,
161
+ showSuccessAnimation: false,
162
+ bestScore: 0,
163
+ hasScreenshotTaken: false
164
+ };
165
+ this.capturedImages = {
166
+ front: {
167
+ fullFrame: null,
168
+ cropped: null
169
+ },
170
+ back: {
171
+ fullFrame: null,
172
+ cropped: null
173
+ },
174
+ metadata: {
175
+ totalImages: 0,
176
+ processCompleted: false,
177
+ backCaptureSkipped: false
178
+ }
179
+ };
180
+ this.eventBus.emit('state-changed', {
181
+ previous: null,
182
+ current: this.captureState,
183
+ changes: { reset: true }
184
+ });
109
185
  }
110
- isRearCamera(stream) {
111
- const videoTrack = stream.getVideoTracks()[0];
112
- if (!videoTrack)
113
- return false;
114
- const settings = videoTrack.getSettings();
115
- return settings.facingMode === 'environment';
186
+ isProcessCompleted() {
187
+ return this.captureState.step === 'completed';
188
+ }
189
+ canProceedToBack() {
190
+ return this.captureState.step === 'front' &&
191
+ this.capturedImages.front.fullFrame !== null &&
192
+ this.capturedImages.front.cropped !== null;
116
193
  }
117
- async detectDeviceTypeAndCameras() {
118
- // Detect device type
194
+ }
195
+
196
+ class CameraService {
197
+ logger;
198
+ eventBus;
199
+ availableCameras = [];
200
+ selectedCameraId = null;
201
+ deviceType = 'desktop';
202
+ preferredCameraFacing = null;
203
+ preferredCamera = 'auto';
204
+ constructor(logger, eventBus, preferredCamera = 'auto') {
205
+ this.logger = logger;
206
+ this.eventBus = eventBus;
207
+ this.preferredCamera = preferredCamera;
208
+ }
209
+ async detectDeviceType() {
119
210
  const userAgent = navigator.userAgent;
120
211
  const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
121
212
  const isTablet = /iPad|Android/i.test(userAgent) && window.innerWidth >= 768;
@@ -128,288 +219,1157 @@ const JaakStamps = class {
128
219
  else {
129
220
  this.deviceType = 'desktop';
130
221
  }
131
- this.debugLog('📱 Device type detected:', this.deviceType);
132
- // Enumerate available cameras
133
- await this.enumerateAndDetectCameras();
134
- // Load user preference
135
- this.loadCameraPreference();
222
+ this.logger.state('DISPOSITIVO_DETECTADO', {
223
+ deviceType: this.deviceType,
224
+ userAgent: navigator.userAgent,
225
+ screenDimensions: { width: window.innerWidth, height: window.innerHeight }
226
+ });
227
+ return this.deviceType;
136
228
  }
137
- async enumerateAndDetectCameras() {
229
+ async enumerateDevices() {
138
230
  try {
139
- // First, check if we have permission to enumerate devices
140
231
  const permissionStatus = await this.checkCameraPermission();
141
232
  if (permissionStatus === 'denied') {
142
- this.debugLog(' Camera permission denied');
143
- this.statusMessage = "Permiso de cámara denegado";
144
- this.statusColor = "#ff6b6b";
145
- return;
233
+ this.logger.error('Permiso de cámara denegado por el usuario');
234
+ return [];
146
235
  }
147
- // Request minimal permission to get device labels
148
236
  if (permissionStatus === 'prompt') {
149
237
  const tempStream = await navigator.mediaDevices.getUserMedia({ video: true });
150
238
  tempStream.getTracks().forEach(track => track.stop());
151
239
  }
152
- // Now enumerate devices with labels
153
240
  const devices = await navigator.mediaDevices.enumerateDevices();
154
241
  this.availableCameras = devices.filter(device => device.kind === 'videoinput');
155
- this.isMultipleCamerasAvailable = this.availableCameras.length > 1;
156
- this.debugLog('📹 Available cameras:', {
242
+ this.logger.state('CAMARAS_DETECTADAS', {
157
243
  count: this.availableCameras.length,
158
- isMultipleCamerasAvailable: this.isMultipleCamerasAvailable,
159
244
  cameras: this.availableCameras.map(cam => ({
160
245
  id: cam.deviceId,
161
246
  label: cam.label || 'Unknown Camera'
162
247
  }))
163
248
  });
164
- // Set initial camera preference based on device type
165
249
  this.setInitialCameraPreference();
250
+ this.eventBus.emit('camera-changed', this.selectedCameraId);
251
+ return this.availableCameras;
166
252
  }
167
253
  catch (error) {
168
- this.debugLog('Error enumerating cameras:', error);
254
+ this.logger.error('Error al enumerar cámaras disponibles:', error);
169
255
  this.handleCameraPermissionError(error);
256
+ return [];
257
+ }
258
+ }
259
+ getAvailableCameras() {
260
+ return [...this.availableCameras];
261
+ }
262
+ isMultipleCamerasAvailable() {
263
+ return this.availableCameras.length > 1;
264
+ }
265
+ getSelectedCameraId() {
266
+ return this.selectedCameraId;
267
+ }
268
+ async setSelectedCamera(cameraId) {
269
+ const camera = this.availableCameras.find(cam => cam.deviceId === cameraId);
270
+ if (!camera) {
271
+ throw new Error(`Camera with ID ${cameraId} not found`);
272
+ }
273
+ this.selectedCameraId = cameraId;
274
+ this.updatePreferredFacing(camera);
275
+ this.savePreference();
276
+ this.eventBus.emit('camera-changed', cameraId);
277
+ }
278
+ getPreferredFacing() {
279
+ return this.preferredCameraFacing;
280
+ }
281
+ async setupCamera(constraints) {
282
+ const finalConstraints = constraints || await this.getMaxResolution();
283
+ const stream = await navigator.mediaDevices.getUserMedia({
284
+ video: finalConstraints,
285
+ audio: false
286
+ });
287
+ return stream;
288
+ }
289
+ async switchCamera(cameraId) {
290
+ const selectedCamera = this.availableCameras.find(cam => cam.deviceId === cameraId);
291
+ if (!selectedCamera) {
292
+ this.logger.warn('Cámara seleccionada no encontrada, re-enumerando dispositivos...');
293
+ await this.enumerateDevices();
294
+ return;
295
+ }
296
+ await this.setSelectedCamera(cameraId);
297
+ this.logger.state('CAMARA_CAMBIADA', {
298
+ label: selectedCamera.label,
299
+ deviceId: selectedCamera.deviceId
300
+ });
301
+ }
302
+ async flipToNextCamera() {
303
+ if (!this.isMultipleCamerasAvailable())
304
+ return;
305
+ const currentIndex = this.availableCameras.findIndex(camera => camera.deviceId === this.selectedCameraId);
306
+ const nextIndex = (currentIndex + 1) % this.availableCameras.length;
307
+ const nextCamera = this.availableCameras[nextIndex];
308
+ await this.switchCamera(nextCamera.deviceId);
309
+ }
310
+ savePreference() {
311
+ try {
312
+ const preference = {
313
+ cameraId: this.selectedCameraId,
314
+ facing: this.preferredCameraFacing,
315
+ timestamp: Date.now()
316
+ };
317
+ localStorage.setItem('jaak-stamps-camera-preference', JSON.stringify(preference));
318
+ this.logger.state('PREFERENCIA_CAMARA_GUARDADA', preference);
319
+ }
320
+ catch (error) {
321
+ this.logger.warn('Error al guardar preferencia de cámara:', error);
322
+ }
323
+ }
324
+ loadPreference() {
325
+ try {
326
+ const saved = localStorage.getItem('jaak-stamps-camera-preference');
327
+ if (saved) {
328
+ const preference = JSON.parse(saved);
329
+ const isStillAvailable = this.availableCameras.some(camera => camera.deviceId === preference.cameraId);
330
+ if (isStillAvailable) {
331
+ this.selectedCameraId = preference.cameraId;
332
+ this.preferredCameraFacing = preference.facing;
333
+ this.logger.state('PREFERENCIA_CAMARA_CARGADA', preference);
334
+ }
335
+ }
336
+ }
337
+ catch (error) {
338
+ this.logger.warn('Error al cargar preferencia de cámara:', error);
170
339
  }
171
340
  }
341
+ isRearCamera(stream) {
342
+ const videoTrack = stream.getVideoTracks()[0];
343
+ if (!videoTrack)
344
+ return false;
345
+ const settings = videoTrack.getSettings();
346
+ return settings.facingMode === 'environment';
347
+ }
348
+ getCameraInfo() {
349
+ return {
350
+ availableCameras: this.availableCameras.map(camera => ({
351
+ id: camera.deviceId,
352
+ label: camera.label || 'Unknown Camera',
353
+ selected: camera.deviceId === this.selectedCameraId
354
+ })),
355
+ selectedCameraId: this.selectedCameraId,
356
+ deviceType: this.deviceType,
357
+ isMultipleCamerasAvailable: this.isMultipleCamerasAvailable(),
358
+ preferredFacing: this.preferredCameraFacing
359
+ };
360
+ }
172
361
  async checkCameraPermission() {
173
362
  try {
174
363
  if (!navigator.permissions) {
175
- return 'prompt'; // Assume we need to prompt on older browsers
364
+ return 'prompt';
176
365
  }
177
366
  const permission = await navigator.permissions.query({ name: 'camera' });
178
367
  return permission.state;
179
368
  }
180
369
  catch (error) {
181
- this.debugLog('⚠️ Could not check camera permission:', error);
370
+ this.logger.warn('No se pudo verificar permisos de cámara:', error);
182
371
  return 'prompt';
183
372
  }
184
373
  }
185
374
  handleCameraPermissionError(error) {
186
- if (error.name === 'NotAllowedError') {
187
- this.statusMessage = "Permiso de cámara denegado. Active el permiso en configuración.";
188
- this.statusColor = "#ff6b6b";
189
- this.availableCameras = [];
190
- this.isMultipleCamerasAvailable = false;
191
- }
192
- else if (error.name === 'NotFoundError') {
193
- this.statusMessage = "No se encontraron cámaras disponibles.";
194
- this.statusColor = "#ff6b6b";
195
- this.availableCameras = [];
196
- this.isMultipleCamerasAvailable = false;
197
- }
198
- else if (error.name === 'NotReadableError') {
199
- this.statusMessage = "Cámara en uso por otra aplicación.";
200
- this.statusColor = "#ff6b6b";
201
- this.availableCameras = [];
202
- this.isMultipleCamerasAvailable = false;
203
- }
204
- else {
205
- this.statusMessage = "Error al acceder a las cámaras.";
206
- this.statusColor = "#ff6b6b";
207
- this.availableCameras = [];
208
- this.isMultipleCamerasAvailable = false;
209
- }
375
+ this.availableCameras = [];
376
+ this.eventBus.emit('error', new Error(`Camera permission error: ${error.message}`));
210
377
  }
211
378
  setInitialCameraPreference() {
212
379
  if (this.availableCameras.length === 0)
213
380
  return;
214
- // Apply user preference for camera selection
215
381
  if (this.preferredCamera === 'front') {
216
- // User explicitly wants front camera
217
- this.preferredCameraFacing = 'user';
218
- const frontCamera = this.availableCameras.find(camera => camera.label.toLowerCase().includes('front') ||
219
- camera.label.toLowerCase().includes('user') ||
220
- camera.label.toLowerCase().includes('selfie') ||
221
- !camera.label.toLowerCase().includes('back') && !camera.label.toLowerCase().includes('rear'));
222
- if (frontCamera) {
223
- this.selectedCameraId = frontCamera.deviceId;
224
- this.debugLog('👤 User selected front camera:', frontCamera.label);
225
- }
226
- else {
227
- this.selectedCameraId = this.availableCameras[0].deviceId;
228
- this.debugLog('⚠️ Front camera not found, using first available:', this.availableCameras[0].label);
229
- }
382
+ this.selectFrontCamera();
230
383
  }
231
384
  else if (this.preferredCamera === 'back') {
232
- // User explicitly wants back camera
233
- this.preferredCameraFacing = 'environment';
234
- const backCamera = this.availableCameras.find(camera => camera.label.toLowerCase().includes('back') ||
235
- camera.label.toLowerCase().includes('rear') ||
236
- camera.label.toLowerCase().includes('environment'));
237
- if (backCamera) {
238
- this.selectedCameraId = backCamera.deviceId;
239
- this.debugLog('📷 User selected back camera:', backCamera.label);
385
+ this.selectBackCamera();
386
+ }
387
+ else {
388
+ this.selectAutoCamera();
389
+ }
390
+ }
391
+ selectFrontCamera() {
392
+ this.preferredCameraFacing = 'user';
393
+ const frontCamera = this.availableCameras.find(camera => camera.label.toLowerCase().includes('front') ||
394
+ camera.label.toLowerCase().includes('user') ||
395
+ camera.label.toLowerCase().includes('selfie') ||
396
+ !camera.label.toLowerCase().includes('back') && !camera.label.toLowerCase().includes('rear'));
397
+ this.selectedCameraId = frontCamera ? frontCamera.deviceId : this.availableCameras[0].deviceId;
398
+ this.logger.state('CAMARA_FRONTAL_SELECCIONADA', {
399
+ label: frontCamera?.label || this.availableCameras[0].label,
400
+ deviceId: this.selectedCameraId
401
+ });
402
+ }
403
+ selectBackCamera() {
404
+ this.preferredCameraFacing = 'environment';
405
+ const backCamera = this.availableCameras.find(camera => camera.label.toLowerCase().includes('back') ||
406
+ camera.label.toLowerCase().includes('rear') ||
407
+ camera.label.toLowerCase().includes('environment'));
408
+ this.selectedCameraId = backCamera ? backCamera.deviceId : this.availableCameras[0].deviceId;
409
+ this.logger.state('CAMARA_TRASERA_SELECCIONADA', {
410
+ label: backCamera?.label || this.availableCameras[0].label,
411
+ deviceId: this.selectedCameraId
412
+ });
413
+ }
414
+ selectAutoCamera() {
415
+ if (this.deviceType === 'mobile' || this.deviceType === 'tablet') {
416
+ this.selectBackCamera();
417
+ this.logger.state('CAMARA_AUTO_SELECCIONADA_MOBILE', { type: 'rear' });
418
+ }
419
+ else {
420
+ this.selectedCameraId = this.availableCameras[0].deviceId;
421
+ this.logger.state('CAMARA_AUTO_SELECCIONADA_DESKTOP', {
422
+ label: this.availableCameras[0].label,
423
+ deviceId: this.selectedCameraId
424
+ });
425
+ }
426
+ }
427
+ updatePreferredFacing(camera) {
428
+ const isRearCamera = camera.label.toLowerCase().includes('back') ||
429
+ camera.label.toLowerCase().includes('rear') ||
430
+ camera.label.toLowerCase().includes('environment');
431
+ this.preferredCameraFacing = isRearCamera ? 'environment' : 'user';
432
+ }
433
+ async getMaxResolution() {
434
+ try {
435
+ const videoConstraints = {};
436
+ if (this.selectedCameraId) {
437
+ videoConstraints.deviceId = { exact: this.selectedCameraId };
438
+ }
439
+ else if (this.preferredCameraFacing) {
440
+ videoConstraints.facingMode = this.preferredCameraFacing;
240
441
  }
241
442
  else {
242
- this.selectedCameraId = this.availableCameras[0].deviceId;
243
- this.debugLog('⚠️ Back camera not found, using first available:', this.availableCameras[0].label);
443
+ videoConstraints.facingMode = "environment";
244
444
  }
245
- }
246
- else {
247
- // Auto mode - use device type to determine best camera
248
- if (this.deviceType === 'mobile' || this.deviceType === 'tablet') {
249
- // For mobile/tablet, prefer rear camera for document scanning
250
- this.preferredCameraFacing = 'environment';
251
- const rearCamera = this.availableCameras.find(camera => camera.label.toLowerCase().includes('back') ||
252
- camera.label.toLowerCase().includes('rear') ||
253
- camera.label.toLowerCase().includes('environment'));
254
- if (rearCamera) {
255
- this.selectedCameraId = rearCamera.deviceId;
256
- this.debugLog('📱 Auto-selected rear camera for mobile:', rearCamera.label);
445
+ const tempStream = await navigator.mediaDevices.getUserMedia({
446
+ video: videoConstraints
447
+ });
448
+ const videoTrack = tempStream.getVideoTracks()[0];
449
+ const capabilities = videoTrack.getCapabilities();
450
+ tempStream.getTracks().forEach(track => track.stop());
451
+ const constraints = { ...videoConstraints };
452
+ // Enhanced focus and image quality settings
453
+ this.applyAdvancedCameraSettings(constraints, capabilities);
454
+ if (capabilities.width && capabilities.height) {
455
+ const maxWidth = Math.min(capabilities.width.max, 1920);
456
+ const maxHeight = Math.min(capabilities.height.max, 1080);
457
+ const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
458
+ if (isTablet) {
459
+ constraints.width = { ideal: Math.min(maxWidth, 1280) };
460
+ constraints.height = { ideal: Math.min(maxHeight, 720) };
257
461
  }
258
462
  else {
259
- this.selectedCameraId = this.availableCameras[0].deviceId;
260
- this.debugLog('📱 Rear camera not found, using first available:', this.availableCameras[0].label);
463
+ constraints.width = { ideal: maxWidth };
464
+ constraints.height = { ideal: maxHeight };
261
465
  }
262
466
  }
467
+ this.logger.state('CONFIGURACION_CAMARA_OPTIMIZADA', {
468
+ constraints,
469
+ capabilities: this.getCapabilitiesSummary(capabilities)
470
+ });
471
+ return constraints;
472
+ }
473
+ catch (err) {
474
+ this.logger.warn('No se pudieron obtener capacidades de cámara, usando configuración de respaldo');
475
+ const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
476
+ const fallbackConstraints = {
477
+ width: { ideal: isTablet ? 1280 : 1920 },
478
+ height: { ideal: isTablet ? 720 : 1080 }
479
+ };
480
+ // Apply basic focus settings even for fallback
481
+ this.applyBasicFocusSettings(fallbackConstraints);
482
+ if (this.selectedCameraId) {
483
+ fallbackConstraints.deviceId = { exact: this.selectedCameraId };
484
+ }
485
+ else if (this.preferredCameraFacing) {
486
+ fallbackConstraints.facingMode = this.preferredCameraFacing;
487
+ }
263
488
  else {
264
- // For desktop, use first available camera (usually the only one)
265
- this.selectedCameraId = this.availableCameras[0].deviceId;
266
- this.debugLog('💻 Auto-selected desktop camera:', this.availableCameras[0].label);
489
+ fallbackConstraints.facingMode = "environment";
267
490
  }
491
+ return fallbackConstraints;
268
492
  }
269
493
  }
270
- loadCameraPreference() {
271
- try {
272
- const saved = localStorage.getItem('jaak-stamps-camera-preference');
273
- if (saved) {
274
- const preference = JSON.parse(saved);
275
- // Validate that the saved camera is still available
276
- const isStillAvailable = this.availableCameras.some(camera => camera.deviceId === preference.cameraId);
277
- if (isStillAvailable) {
278
- this.selectedCameraId = preference.cameraId;
279
- this.preferredCameraFacing = preference.facing;
280
- this.debugLog('💾 Loaded camera preference:', preference);
281
- }
494
+ applyAdvancedCameraSettings(constraints, capabilities) {
495
+ // Apply standard camera settings that are widely supported
496
+ // Frame rate optimization
497
+ if (capabilities.frameRate) {
498
+ constraints.frameRate = {
499
+ ideal: 30,
500
+ min: 15,
501
+ max: 60
502
+ };
503
+ }
504
+ // Width and height constraints for optimal resolution
505
+ if (capabilities.width && capabilities.height) {
506
+ constraints.width = {
507
+ ideal: Math.min(1920, capabilities.width.max || 1920),
508
+ min: 640
509
+ };
510
+ constraints.height = {
511
+ ideal: Math.min(1080, capabilities.height.max || 1080),
512
+ min: 480
513
+ };
514
+ }
515
+ // Apply enhanced constraints through advanced array for better browser compatibility
516
+ const advancedConstraints = [];
517
+ // Try to set optimal settings through advanced constraints
518
+ const advanced = {};
519
+ // Focus mode - use 'any' type to bypass TypeScript limitations
520
+ if (capabilities.focusMode) {
521
+ if (capabilities.focusMode.includes('continuous')) {
522
+ advanced.focusMode = 'continuous';
523
+ }
524
+ else if (capabilities.focusMode.includes('single-shot')) {
525
+ advanced.focusMode = 'single-shot';
282
526
  }
283
527
  }
284
- catch (error) {
285
- this.debugLog('⚠️ Error loading camera preference:', error);
528
+ // Focus distance for close objects
529
+ if (capabilities.focusDistance) {
530
+ advanced.focusDistance = {
531
+ ideal: 0.4, // 40cm - optimal for document capture
532
+ min: 0.2,
533
+ max: 1.0
534
+ };
286
535
  }
287
- }
288
- saveCameraPreference() {
289
- try {
290
- const preference = {
291
- cameraId: this.selectedCameraId,
292
- facing: this.preferredCameraFacing,
293
- timestamp: Date.now()
536
+ // Zoom control
537
+ if (capabilities.zoom) {
538
+ advanced.zoom = {
539
+ ideal: 1.0,
540
+ min: capabilities.zoom.min,
541
+ max: Math.min(capabilities.zoom.max, 3.0)
294
542
  };
295
- localStorage.setItem('jaak-stamps-camera-preference', JSON.stringify(preference));
296
- this.debugLog('💾 Saved camera preference:', preference);
297
543
  }
298
- catch (error) {
299
- this.debugLog('⚠️ Error saving camera preference:', error);
544
+ // Add advanced constraints if any were set
545
+ if (Object.keys(advanced).length > 0) {
546
+ advancedConstraints.push(advanced);
547
+ }
548
+ if (advancedConstraints.length > 0) {
549
+ constraints.advanced = advancedConstraints;
300
550
  }
301
551
  }
302
- async switchCamera(cameraId) {
303
- if (!this.isVideoActive || this.selectedCameraId === cameraId)
304
- return;
552
+ applyBasicFocusSettings(constraints) {
553
+ // Apply basic focus settings when capabilities are not available
554
+ // Use advanced constraints for non-standard properties
555
+ const advanced = {
556
+ focusMode: 'continuous',
557
+ exposureMode: 'continuous',
558
+ whiteBalanceMode: 'continuous'
559
+ };
560
+ if (!constraints.advanced) {
561
+ constraints.advanced = [];
562
+ }
563
+ constraints.advanced.push(advanced);
564
+ constraints.frameRate = { ideal: 30 };
565
+ }
566
+ getCapabilitiesSummary(capabilities) {
567
+ return {
568
+ hasAutoFocus: !!capabilities.focusMode,
569
+ hasFocusDistance: !!capabilities.focusDistance,
570
+ hasExposureControl: !!capabilities.exposureMode,
571
+ hasWhiteBalance: !!capabilities.whiteBalanceMode,
572
+ hasZoom: !!capabilities.zoom,
573
+ hasTorch: capabilities.torch !== undefined,
574
+ hasImageControls: !!(capabilities.brightness || capabilities.contrast || capabilities.saturation || capabilities.sharpness),
575
+ resolutionRange: capabilities.width && capabilities.height ?
576
+ `${capabilities.width.min}x${capabilities.height.min} - ${capabilities.width.max}x${capabilities.height.max}` : 'unknown'
577
+ };
578
+ }
579
+ // New method to enable torch/flash for better illumination
580
+ async setTorchEnabled(enabled, stream) {
305
581
  try {
306
- // Check if the selected camera is still available
307
- const selectedCamera = this.availableCameras.find(cam => cam.deviceId === cameraId);
308
- if (!selectedCamera) {
309
- this.debugLog('❌ Selected camera not found, re-enumerating...');
310
- await this.enumerateAndDetectCameras();
311
- return;
582
+ if (!stream) {
583
+ this.logger.warn('No hay stream disponible para controlar el flash');
584
+ return false;
312
585
  }
313
- // Show loading state
314
- this.statusMessage = "Cambiando cámara...";
315
- this.statusColor = "#007bff";
316
- // Stop current stream
317
- if (this.videoStream) {
318
- this.videoStream.getTracks().forEach(track => track.stop());
586
+ const videoTrack = stream.getVideoTracks()[0];
587
+ if (!videoTrack) {
588
+ this.logger.warn('No hay track de video disponible');
589
+ return false;
590
+ }
591
+ const capabilities = videoTrack.getCapabilities();
592
+ if (capabilities.torch === undefined) {
593
+ this.logger.warn('El dispositivo no soporta control de flash');
594
+ return false;
319
595
  }
320
- // Update selected camera
321
- this.selectedCameraId = cameraId;
322
- // Update facing mode preference
323
- const isRearCamera = selectedCamera.label.toLowerCase().includes('back') ||
324
- selectedCamera.label.toLowerCase().includes('rear') ||
325
- selectedCamera.label.toLowerCase().includes('environment');
326
- this.preferredCameraFacing = isRearCamera ? 'environment' : 'user';
327
- // Save preference
328
- this.saveCameraPreference();
329
- // Setup new camera with error handling
330
- await this.setupCameraWithRetry();
331
- this.debugLog('🔄 Switched to camera:', selectedCamera.label);
596
+ await videoTrack.applyConstraints({
597
+ advanced: [{ torch: enabled }]
598
+ });
599
+ this.logger.state('FLASH_CONTROLADO', { enabled });
600
+ return true;
332
601
  }
333
602
  catch (error) {
334
- this.debugLog('Error switching camera:', error);
335
- this.handleCameraPermissionError(error);
603
+ this.logger.error('Error al controlar el flash:', error);
604
+ return false;
605
+ }
606
+ }
607
+ // Method to manually trigger focus on a specific point
608
+ async focusAtPoint(x, y, stream) {
609
+ try {
610
+ if (!stream) {
611
+ this.logger.warn('No hay stream disponible para enfocar');
612
+ return false;
613
+ }
614
+ const videoTrack = stream.getVideoTracks()[0];
615
+ if (!videoTrack) {
616
+ this.logger.warn('No hay track de video disponible');
617
+ return false;
618
+ }
619
+ const capabilities = videoTrack.getCapabilities();
620
+ if (!capabilities.focusMode || !capabilities.focusMode.includes('single-shot')) {
621
+ this.logger.warn('El dispositivo no soporta enfoque manual');
622
+ return false;
623
+ }
624
+ // Trigger single-shot focus
625
+ await videoTrack.applyConstraints({
626
+ advanced: [{ focusMode: 'single-shot' }]
627
+ });
628
+ // Return to continuous focus after a short delay
629
+ setTimeout(async () => {
630
+ try {
631
+ await videoTrack.applyConstraints({
632
+ advanced: [{ focusMode: 'continuous' }]
633
+ });
634
+ }
635
+ catch (error) {
636
+ this.logger.warn('Error al volver a enfoque continuo:', error);
637
+ }
638
+ }, 1000);
639
+ this.logger.state('ENFOQUE_MANUAL_ACTIVADO', { x, y });
640
+ return true;
641
+ }
642
+ catch (error) {
643
+ this.logger.error('Error al enfocar manualmente:', error);
644
+ return false;
645
+ }
646
+ }
647
+ }
648
+
649
+ class LowMemoryDeviceStrategy {
650
+ getDeviceInfo() {
651
+ const nav = navigator;
652
+ const memory = nav.deviceMemory || nav.hardwareConcurrency || 4;
653
+ const connection = nav.connection || nav.mozConnection || nav.webkitConnection;
654
+ const isSlowConnection = connection && (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g');
655
+ return {
656
+ estimatedRAM: memory,
657
+ isLowMemory: true,
658
+ isSlowConnection: isSlowConnection
659
+ };
660
+ }
661
+ getSessionOptions(_debug) {
662
+ return {
663
+ executionProviders: ['wasm'],
664
+ graphOptimizationLevel: 'basic',
665
+ logSeverityLevel: 4,
666
+ logVerbosityLevel: 0,
667
+ enableCpuMemArena: false,
668
+ enableMemPattern: false,
669
+ executionMode: 'sequential',
670
+ interOpNumThreads: 1,
671
+ intraOpNumThreads: 1,
672
+ };
673
+ }
674
+ shouldUseSequentialLoading() {
675
+ return true;
676
+ }
677
+ }
678
+
679
+ class HighPerformanceDeviceStrategy {
680
+ getDeviceInfo() {
681
+ const nav = navigator;
682
+ const memory = nav.deviceMemory || nav.hardwareConcurrency || 4;
683
+ const connection = nav.connection || nav.mozConnection || nav.webkitConnection;
684
+ const isSlowConnection = connection && (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g');
685
+ return {
686
+ estimatedRAM: memory,
687
+ isLowMemory: false,
688
+ isSlowConnection: isSlowConnection
689
+ };
690
+ }
691
+ getSessionOptions(debug) {
692
+ return {
693
+ executionProviders: ['webgl', 'wasm'],
694
+ graphOptimizationLevel: 'all',
695
+ logSeverityLevel: debug ? 2 : 4,
696
+ logVerbosityLevel: 0,
697
+ enableCpuMemArena: true,
698
+ enableMemPattern: true,
699
+ executionMode: 'parallel',
700
+ interOpNumThreads: 2,
701
+ intraOpNumThreads: 2,
702
+ };
703
+ }
704
+ shouldUseSequentialLoading() {
705
+ return false;
706
+ }
707
+ }
708
+
709
+ class DeviceStrategyFactory {
710
+ static createStrategy() {
711
+ const nav = navigator;
712
+ const memory = nav.deviceMemory || nav.hardwareConcurrency || 4;
713
+ const isLowMemory = memory <= 4;
714
+ if (isLowMemory) {
715
+ return new LowMemoryDeviceStrategy();
716
+ }
717
+ else {
718
+ return new HighPerformanceDeviceStrategy();
719
+ }
720
+ }
721
+ }
722
+
723
+ class DetectionService {
724
+ logger;
725
+ debug;
726
+ useDocumentClassification;
727
+ session;
728
+ mobileNetSession;
729
+ mobileNetClassMap;
730
+ modelLoaded = false;
731
+ deviceStrategy;
732
+ MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v2.onnx";
733
+ MOBILENET_MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.onnx";
734
+ MOBILENET_CLASSES_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";
735
+ INPUT_SIZE = 320;
736
+ CONFIDENCE_THRESHOLD = 0.6;
737
+ // Canvas pool for optimization
738
+ preprocessCanvas;
739
+ preprocessCtx;
740
+ captureCanvas;
741
+ constructor(logger, debug = false, useDocumentClassification = false) {
742
+ this.logger = logger;
743
+ this.debug = debug;
744
+ this.useDocumentClassification = useDocumentClassification;
745
+ this.deviceStrategy = DeviceStrategyFactory.createStrategy();
746
+ this.initializeCanvasPool();
747
+ }
748
+ async loadModel() {
749
+ if (this.modelLoaded || this.session) {
750
+ this.logger.state('MODELO_YA_PRECARGADO', {
751
+ sessionExists: !!this.session,
752
+ modelPreloaded: this.modelLoaded
753
+ });
754
+ return;
755
+ }
756
+ try {
757
+ this.logger.state('PRECARGANDO_MODELO_DETECCION', { modelPath: this.MODEL_PATH });
758
+ const sessionOptions = this.deviceStrategy.getSessionOptions(this.debug);
759
+ try {
760
+ this.session = await window.ort.InferenceSession.create(this.MODEL_PATH, sessionOptions);
761
+ }
762
+ catch (error) {
763
+ if (error.message.includes('failed to allocate a buffer')) {
764
+ this.logger.warn('Fallo en asignación de buffer durante precarga, intentando con configuración mínima');
765
+ const fallbackOptions = {
766
+ executionProviders: ['wasm'],
767
+ graphOptimizationLevel: 'disabled',
768
+ logSeverityLevel: 4,
769
+ enableCpuMemArena: false,
770
+ enableMemPattern: false,
771
+ executionMode: 'sequential',
772
+ interOpNumThreads: 1,
773
+ intraOpNumThreads: 1,
774
+ };
775
+ this.session = await window.ort.InferenceSession.create(this.MODEL_PATH, fallbackOptions);
776
+ }
777
+ else {
778
+ throw error;
779
+ }
780
+ }
781
+ this.modelLoaded = true;
782
+ this.logger.state('MODELO_DETECCION_CARGADO_EXITOSAMENTE', { sessionCreated: !!this.session });
783
+ }
784
+ catch (error) {
785
+ this.logger.error('Error al precargar modelo de detección:', error);
786
+ throw error;
787
+ }
788
+ }
789
+ async loadClassificationModel() {
790
+ if (!this.useDocumentClassification) {
791
+ return;
792
+ }
793
+ try {
794
+ this.logger.state('CARGANDO_MODELO_MOBILENET', { path: this.MOBILENET_MODEL_PATH });
795
+ // Load class map
796
+ const classResponse = await fetch(this.MOBILENET_CLASSES_PATH);
797
+ if (!classResponse.ok) {
798
+ throw new Error(`Failed to load class map: ${this.MOBILENET_CLASSES_PATH}`);
799
+ }
800
+ this.mobileNetClassMap = await classResponse.json();
801
+ this.logger.state('CLASES_MOBILENET_CARGADAS', {
802
+ classCount: Object.keys(this.mobileNetClassMap).length
803
+ });
804
+ // Load model
805
+ const sessionOptions = this.deviceStrategy.getSessionOptions(this.debug);
806
+ try {
807
+ this.mobileNetSession = await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, sessionOptions);
808
+ }
809
+ catch (error) {
810
+ if (error.message.includes('failed to allocate a buffer')) {
811
+ this.logger.warn('Fallo en asignación de buffer de MobileNet, intentando con configuración mínima');
812
+ const fallbackOptions = {
813
+ executionProviders: ['wasm'],
814
+ graphOptimizationLevel: 'disabled',
815
+ logSeverityLevel: 4,
816
+ enableCpuMemArena: false,
817
+ enableMemPattern: false,
818
+ executionMode: 'sequential',
819
+ interOpNumThreads: 1,
820
+ intraOpNumThreads: 1,
821
+ };
822
+ this.mobileNetSession = await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, fallbackOptions);
823
+ }
824
+ else {
825
+ throw error;
826
+ }
827
+ }
828
+ this.logger.state('MODELO_MOBILENET_CARGADO_EXITOSAMENTE', {
829
+ sessionCreated: !!this.mobileNetSession
830
+ });
831
+ }
832
+ catch (error) {
833
+ this.logger.error('Error al cargar modelo MobileNet:', error);
834
+ throw error;
835
+ }
836
+ }
837
+ isModelLoaded() {
838
+ return this.modelLoaded && !!this.session;
839
+ }
840
+ preprocess(video) {
841
+ if (!this.preprocessCanvas || !this.preprocessCtx) {
842
+ this.initializeCanvasPool();
843
+ }
844
+ this.preprocessCtx.clearRect(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
845
+ this.preprocessCtx.drawImage(video, 0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
846
+ const imageData = this.preprocessCtx.getImageData(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
847
+ const [R, G, B] = [[], [], []];
848
+ const { data } = imageData;
849
+ for (let i = 0; i < data.length; i += 4) {
850
+ R.push(data[i] / 255);
851
+ G.push(data[i + 1] / 255);
852
+ B.push(data[i + 2] / 255);
853
+ }
854
+ const transposedData = new Float32Array(R.concat(G, B));
855
+ const float16Data = new Uint16Array(transposedData.length);
856
+ for (let i = 0; i < transposedData.length; i++) {
857
+ float16Data[i] = this.float32ToFloat16(transposedData[i]);
858
+ }
859
+ return new window.ort.Tensor("float16", float16Data, [1, 3, this.INPUT_SIZE, this.INPUT_SIZE]);
860
+ }
861
+ async runInference(inputTensor) {
862
+ if (!this.session) {
863
+ throw new Error('Detection model not loaded');
864
+ }
865
+ const feeds = { [this.session.inputNames[0]]: inputTensor };
866
+ const results = await this.session.run(feeds);
867
+ const output = results[this.session.outputNames[0]].data;
868
+ const detections = [];
869
+ for (let i = 0; i < output.length; i += 6) {
870
+ const [x1, y1, x2, y2, score, classId] = output.slice(i, i + 6);
871
+ if (score > this.CONFIDENCE_THRESHOLD) {
872
+ detections.push({
873
+ x: x1,
874
+ y: y1,
875
+ w: x2 - x1,
876
+ h: y2 - y1,
877
+ score,
878
+ classId
879
+ });
880
+ }
881
+ }
882
+ return detections;
883
+ }
884
+ async classifyDocument(canvas) {
885
+ if (!this.mobileNetSession || !this.mobileNetClassMap) {
886
+ this.logger.warn('Modelo MobileNet no está cargado, saltando clasificación');
887
+ return null;
888
+ }
889
+ try {
890
+ this.logger.state('CLASIFICANDO_DOCUMENTO', { timestamp: Date.now() });
891
+ const inputTensor = this.preprocessMobileNet(canvas);
892
+ const feeds = { input: inputTensor };
893
+ const results = await this.mobileNetSession.run(feeds);
894
+ const output = results[Object.keys(results)[0]].data;
895
+ const maxIdx = output.reduce((bestIdx, val, idx, arr) => val > arr[bestIdx] ? idx : bestIdx, 0);
896
+ const confidence = output[maxIdx];
897
+ const className = this.mobileNetClassMap[maxIdx.toString()] || "unknown";
898
+ this.logger.state('DOCUMENTO_CLASIFICADO', {
899
+ class: className,
900
+ confidence: confidence.toFixed(3),
901
+ classIndex: maxIdx,
902
+ timestamp: Date.now()
903
+ });
904
+ return {
905
+ class: className,
906
+ confidence: confidence,
907
+ classIndex: maxIdx
908
+ };
909
+ }
910
+ catch (error) {
911
+ this.logger.error('Error al clasificar documento:', error);
912
+ return null;
913
+ }
914
+ }
915
+ checkSideAlignment(box, maskConfig) {
916
+ const { INPUT_SIZE, ID1_ASPECT_RATIO, shouldMirrorVideo, alignmentTolerance, maskSize, videoRef } = maskConfig;
917
+ if (!videoRef) {
918
+ return { top: false, right: false, bottom: false, left: false };
919
+ }
920
+ // Get video dimensions to calculate actual mask boundaries in model space
921
+ const videoWidth = videoRef.videoWidth;
922
+ const videoHeight = videoRef.videoHeight;
923
+ if (videoWidth === 0 || videoHeight === 0) {
924
+ return { top: false, right: false, bottom: false, left: false };
925
+ }
926
+ // Calculate video aspect ratio
927
+ const videoAspectRatio = videoWidth / videoHeight;
928
+ // The model sees video stretched to 320x320, but we need to calculate where
929
+ // the mask should be in this distorted space to match the visual mask
930
+ // In the visual display, we calculate mask size based on the limiting dimension
931
+ // We need to replicate this logic but account for the distortion in model space
932
+ // Calculate the "display" dimensions (what the visual mask calculations use)
933
+ const containerAspectRatio = 1; // Assume square container for simplicity
934
+ let displayedVideoWidth, displayedVideoHeight;
935
+ if (videoAspectRatio > containerAspectRatio) {
936
+ // Video is wider - letterboxed in display
937
+ displayedVideoWidth = INPUT_SIZE;
938
+ displayedVideoHeight = INPUT_SIZE / videoAspectRatio;
939
+ }
940
+ else {
941
+ // Video is taller - pillarboxed in display
942
+ displayedVideoHeight = INPUT_SIZE;
943
+ displayedVideoWidth = INPUT_SIZE * videoAspectRatio;
944
+ }
945
+ // Calculate mask dimensions using the same logic as updateMaskDimensions
946
+ const maxWidthByHeight = displayedVideoHeight * ID1_ASPECT_RATIO;
947
+ let visualMaskWidth, visualMaskHeight;
948
+ const sizeRatio = maskSize / 100;
949
+ if (maxWidthByHeight <= displayedVideoWidth) {
950
+ // Video height is the limiting factor
951
+ visualMaskHeight = displayedVideoHeight * sizeRatio;
952
+ visualMaskWidth = visualMaskHeight * ID1_ASPECT_RATIO;
953
+ }
954
+ else {
955
+ // Video width is the limiting factor
956
+ visualMaskWidth = displayedVideoWidth * sizeRatio;
957
+ visualMaskHeight = visualMaskWidth / ID1_ASPECT_RATIO;
958
+ }
959
+ // Now map these visual mask dimensions to the distorted model space
960
+ // The model stretches video to 320x320, so we need to apply the inverse transformation
961
+ const modelMaskWidth = visualMaskWidth * (INPUT_SIZE / displayedVideoWidth);
962
+ const modelMaskHeight = visualMaskHeight * (INPUT_SIZE / displayedVideoHeight);
963
+ // Calculate mask boundaries in model coordinate system (always centered in 320x320)
964
+ const maskCenterX = INPUT_SIZE / 2;
965
+ const maskCenterY = INPUT_SIZE / 2;
966
+ const maskLeft = maskCenterX - (modelMaskWidth / 2);
967
+ const maskRight = maskCenterX + (modelMaskWidth / 2);
968
+ const maskTop = maskCenterY - (modelMaskHeight / 2);
969
+ const maskBottom = maskCenterY + (modelMaskHeight / 2);
970
+ // Obtener las coordenadas del documento detectado
971
+ let docLeft = box.x;
972
+ let docRight = box.x + box.w;
973
+ const docTop = box.y;
974
+ const docBottom = box.y + box.h;
975
+ // Si el video está en modo mirror, invertir las coordenadas horizontales
976
+ if (shouldMirrorVideo) {
977
+ const originalDocLeft = docLeft;
978
+ const originalDocRight = docRight;
979
+ docLeft = INPUT_SIZE - originalDocRight;
980
+ docRight = INPUT_SIZE - originalDocLeft;
981
+ }
982
+ // Tolerancia para considerar que un lado está alineado (en píxeles)
983
+ const tolerance = alignmentTolerance;
984
+ // Verificar alineación de esquinas más estricta
985
+ // Una esquina está alineada solo si AMBOS bordes que la forman están alineados
986
+ const topAligned = Math.abs(docTop - maskTop) <= tolerance;
987
+ const rightAligned = Math.abs(docRight - maskRight) <= tolerance;
988
+ const bottomAligned = Math.abs(docBottom - maskBottom) <= tolerance;
989
+ const leftAligned = Math.abs(docLeft - maskLeft) <= tolerance;
990
+ return {
991
+ top: topAligned && leftAligned, // Esquina superior izquierda: borde top Y left alineados
992
+ right: topAligned && rightAligned, // Esquina superior derecha: borde top Y right alineados
993
+ bottom: bottomAligned && leftAligned, // Esquina inferior izquierda: borde bottom Y left alineados
994
+ left: bottomAligned && rightAligned // Esquina inferior derecha: borde bottom Y right alineados
995
+ };
996
+ }
997
+ isCardInFrame(box) {
998
+ const cardCenterX = box.x + box.w / 2;
999
+ const cardCenterY = box.y + box.h / 2;
1000
+ const frameCenterX = this.INPUT_SIZE / 2;
1001
+ const frameCenterY = this.INPUT_SIZE / 2;
1002
+ const toleranceX = 40;
1003
+ const toleranceY = 30;
1004
+ const isCentered = Math.abs(cardCenterX - frameCenterX) < toleranceX &&
1005
+ Math.abs(cardCenterY - frameCenterY) < toleranceY;
1006
+ const isGoodSize = box.w > 150 && box.w < 300 && box.h > 90 && box.h < 200;
1007
+ return isCentered && isGoodSize;
1008
+ }
1009
+ areAllSidesAligned(alignment) {
1010
+ return alignment.top && alignment.right && alignment.bottom && alignment.left;
1011
+ }
1012
+ cleanup() {
1013
+ this.cleanupCanvasPool();
1014
+ if (this.session) {
1015
+ this.session.release?.();
1016
+ this.session = undefined;
1017
+ }
1018
+ if (this.mobileNetSession) {
1019
+ this.mobileNetSession.release?.();
1020
+ this.mobileNetSession = undefined;
1021
+ }
1022
+ this.mobileNetClassMap = undefined;
1023
+ this.modelLoaded = false;
1024
+ this.logger.state('DETECCION_SERVICE_LIMPIADO', { timestamp: Date.now() });
1025
+ }
1026
+ initializeCanvasPool() {
1027
+ this.preprocessCanvas = document.createElement('canvas');
1028
+ this.preprocessCanvas.width = this.INPUT_SIZE;
1029
+ this.preprocessCanvas.height = this.INPUT_SIZE;
1030
+ this.preprocessCtx = this.preprocessCanvas.getContext('2d', {
1031
+ alpha: false,
1032
+ willReadFrequently: true
1033
+ });
1034
+ this.captureCanvas = document.createElement('canvas');
1035
+ this.logger.state('CANVAS_POOL_INICIALIZADO', {
1036
+ preprocessCanvasSize: this.INPUT_SIZE
1037
+ });
1038
+ }
1039
+ cleanupCanvasPool() {
1040
+ if (this.preprocessCanvas) {
1041
+ this.preprocessCtx = undefined;
1042
+ this.preprocessCanvas = undefined;
1043
+ }
1044
+ if (this.captureCanvas) {
1045
+ this.captureCanvas = undefined;
1046
+ }
1047
+ }
1048
+ float32ToFloat16(value) {
1049
+ const buffer = new ArrayBuffer(4);
1050
+ const view = new DataView(buffer);
1051
+ view.setFloat32(0, value, true);
1052
+ const f = view.getUint32(0, true);
1053
+ const sign = (f >> 31) & 0x1;
1054
+ const exp = (f >> 23) & 0xFF;
1055
+ const frac = f & 0x7FFFFF;
1056
+ let newExp = exp - 127 + 15;
1057
+ if (exp === 0) {
1058
+ newExp = 0;
1059
+ }
1060
+ else if (exp === 0xFF) {
1061
+ newExp = 0x1F;
1062
+ }
1063
+ else if (newExp >= 0x1F) {
1064
+ newExp = 0x1F;
1065
+ return (sign << 15) | (newExp << 10);
1066
+ }
1067
+ else if (newExp <= 0) {
1068
+ return (sign << 15);
1069
+ }
1070
+ return (sign << 15) | (newExp << 10) | (frac >> 13);
1071
+ }
1072
+ preprocessMobileNet(canvas) {
1073
+ const tempCanvas = document.createElement('canvas');
1074
+ tempCanvas.width = 224;
1075
+ tempCanvas.height = 224;
1076
+ const tempCtx = tempCanvas.getContext('2d');
1077
+ tempCtx.drawImage(canvas, 0, 0, 224, 224);
1078
+ const imageData = tempCtx.getImageData(0, 0, 224, 224);
1079
+ const data = imageData.data;
1080
+ const hw = 224 * 224;
1081
+ const arr = new Float32Array(3 * hw);
1082
+ for (let i = 0; i < hw; i++) {
1083
+ arr[i] = (data[i * 4 + 0] / 255 - 0.5) / 0.5;
1084
+ arr[hw + i] = (data[i * 4 + 1] / 255 - 0.5) / 0.5;
1085
+ arr[2 * hw + i] = (data[i * 4 + 2] / 255 - 0.5) / 0.5;
1086
+ }
1087
+ return new window.ort.Tensor('float32', arr, [1, 3, 224, 224]);
1088
+ }
1089
+ }
1090
+
1091
+ class ServiceContainer {
1092
+ services = new Map();
1093
+ constructor(config) {
1094
+ this.initializeServices(config);
1095
+ }
1096
+ initializeServices(config) {
1097
+ // Initialize services in dependency order
1098
+ const eventBus = new EventBusService();
1099
+ const logger = new LoggerService(config.debug);
1100
+ const stateManager = new StateManagerService(eventBus);
1101
+ const cameraService = new CameraService(logger, eventBus, config.preferredCamera);
1102
+ const detectionService = new DetectionService(logger, config.debug, config.useDocumentClassification);
1103
+ // Register services
1104
+ this.services.set('eventBus', eventBus);
1105
+ this.services.set('logger', logger);
1106
+ this.services.set('stateManager', stateManager);
1107
+ this.services.set('cameraService', cameraService);
1108
+ this.services.set('detectionService', detectionService);
1109
+ }
1110
+ get(serviceName) {
1111
+ const service = this.services.get(serviceName);
1112
+ if (!service) {
1113
+ throw new Error(`Service ${serviceName} not found`);
1114
+ }
1115
+ return service;
1116
+ }
1117
+ getLogger() {
1118
+ return this.get('logger');
1119
+ }
1120
+ getEventBus() {
1121
+ return this.get('eventBus');
1122
+ }
1123
+ getStateManager() {
1124
+ return this.get('stateManager');
1125
+ }
1126
+ getCameraService() {
1127
+ return this.get('cameraService');
1128
+ }
1129
+ getDetectionService() {
1130
+ return this.get('detectionService');
1131
+ }
1132
+ updateConfig(config) {
1133
+ if (config.debug !== undefined) {
1134
+ const logger = this.services.get('logger');
1135
+ logger.setDebugMode(config.debug);
1136
+ }
1137
+ }
1138
+ cleanup() {
1139
+ // Cleanup services in reverse order
1140
+ this.getDetectionService().cleanup();
1141
+ this.getEventBus().clear();
1142
+ this.services.clear();
1143
+ }
1144
+ }
1145
+
1146
+ const myComponentCss = ":host{display:block;width:100%;height:100%;font-family:system-ui, -apple-system, sans-serif;color:#1a1a1a}.detector-container{display:flex;flex-direction:column;align-items:center;width:100%;height:100%}h1{font-size:24px;font-weight:500;color:#333;margin:0 0 24px 0}.video-container{position:relative;width:100%;height:100%;background:#333;border:1px solid #e0e0e0;border-radius:8px;overflow:hidden}video,.detection-overlay{position:absolute;width:100%;height:100%;border-radius:8px}video.mirror,.detection-overlay.mirror{transform:rotateY(180deg)}.detection-overlay{z-index:1;pointer-events:none}video{z-index:0}.detection-box{transition:opacity 0.2s ease}.status{margin-top:16px;font-size:12px;color:#666}.overlay-mask{position:absolute;top:0;left:0;width:100%;height:100%;z-index:10;display:block;pointer-events:none}.card-outline{position:absolute;top:var(--mask-center-y, 50%);left:var(--mask-center-x, 50%);transform:translate(-50%, -50%);width:var(--mask-width, 88%);height:var(--mask-height, 55%);border:none;border-radius:4px;background:transparent;opacity:0.8}.side{position:absolute;background:#999;transition:background-color 0.3s ease;border-radius:1px}.side-top.aligned{border-left-color:#28a745;border-top-color:#28a745}.side-right.aligned{border-right-color:#28a745;border-top-color:#28a745}.side-bottom.aligned{border-left-color:#28a745;border-bottom-color:#28a745}.side-left.aligned{border-right-color:#28a745;border-bottom-color:#28a745}.side-top{top:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-right{top:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-top:6px solid #ffffff;background:transparent}.side-bottom{bottom:-3px;left:-3px;width:30px;height:30px;border-left:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.side-left{bottom:-3px;right:-3px;width:30px;height:30px;border-right:6px solid #ffffff;border-bottom:6px solid #ffffff;background:transparent}.guide-text{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);color:#fff;font-size:14px;font-weight:600;text-align:center;white-space:normal;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;z-index:20}.quality-indicator{position:absolute;top:20px;right:20px;display:flex;align-items:center;gap:8px;background:rgba(0, 0, 0, 0.8);padding:8px 12px;border-radius:20px;z-index:25;transition:all 0.3s ease}.quality-indicator.warning{background:rgba(255, 152, 0, 0.9)}.quality-indicator.good{background:rgba(76, 175, 80, 0.9)}.quality-score{color:#fff;font-size:12px;font-weight:600;min-width:30px;text-align:center}.quality-status{width:20px;height:20px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;font-weight:bold;color:#fff;transition:all 0.3s ease}.quality-status.ready{background:#4CAF50}.quality-status.not-ready{background:#f44336}.card-outline.quality-warning{animation:qualityWarning 1s ease-in-out infinite alternate}@keyframes qualityWarning{0%{box-shadow:0 0 0 3px rgba(255, 152, 0, 0.6)}100%{box-shadow:0 0 0 6px rgba(255, 152, 0, 0.3)}}.capture-animation{position:absolute;top:0;left:0;width:100%;height:100%;background:#fff;opacity:0;z-index:30;pointer-events:none;animation:captureFlash 0.6s ease-out}@keyframes captureFlash{0%{opacity:0}15%{opacity:0.8}30%{opacity:0}45%{opacity:0.4}60%{opacity:0}100%{opacity:0}}.card-outline.capturing{animation:pulseGreen 0.6s ease-out}@keyframes pulseGreen{0%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}50%{border-color:#28a745;box-shadow:0 0 0 8px rgba(40, 167, 69, 0.6)}100%{border-color:#28a745;box-shadow:0 0 0 4px rgba(40, 167, 69, 0)}}.flip-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showFlipInstruction 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.id-card-icon{width:80px;height:50px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:8px;position:relative;animation:flipCard 2s ease-in-out infinite;box-shadow:0 4px 12px rgba(0, 0, 0, 0.3)}.id-card-icon::before{content:'';position:absolute;top:8px;left:8px;width:16px;height:12px;background:rgba(255, 255, 255, 0.9);border-radius:2px}.id-card-icon::after{content:'';position:absolute;top:25px;left:8px;width:64px;height:3px;background:rgba(255, 255, 255, 0.7);border-radius:1px;box-shadow:0 6px 0 rgba(255, 255, 255, 0.7), 0 12px 0 rgba(255, 255, 255, 0.7)}.flip-text{margin-top:12px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px}@keyframes showFlipInstruction{0%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.8)}}@keyframes flipCard{0%{transform:rotateY(0deg)}50%{transform:rotateY(180deg)}100%{transform:rotateY(360deg)}}.success-animation{position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);z-index:35;pointer-events:none;opacity:0;animation:showSuccessMessage 3s ease-in-out;display:flex;flex-direction:column;align-items:center;justify-content:center}.check-icon{width:80px;height:80px;background:linear-gradient(135deg, #6c757d 0%, #495057 100%);border-radius:50%;position:relative;animation:bounceSuccess 0.6s ease-out;box-shadow:0 4px 16px rgba(108, 117, 125, 0.4);display:flex;align-items:center;justify-content:center}.check-icon::before{content:'';position:absolute;width:20px;height:35px;border:4px solid #fff;border-top:none;border-left:none;transform:rotate(45deg);animation:drawCheck 0.4s ease-out 0.2s both}.success-text{margin-top:16px;color:#fff;font-size:14px;font-weight:600;text-align:center;background:rgba(128, 128, 128, 0.8);padding:12px 20px;border-radius:20px;max-width:300px;animation:fadeInUp 0.5s ease-out 0.4s both}@keyframes showSuccessMessage{0%{opacity:0;transform:translate(-50%, -50%) scale(0.5)}15%{opacity:1;transform:translate(-50%, -50%) scale(1)}85%{opacity:1;transform:translate(-50%, -50%) scale(1)}100%{opacity:0;transform:translate(-50%, -50%) scale(0.9)}}@keyframes bounceSuccess{0%{transform:scale(0)}50%{transform:scale(1.1)}100%{transform:scale(1)}}@keyframes drawCheck{0%{width:0;height:0}50%{width:20px;height:0}100%{width:20px;height:35px}}@keyframes fadeInUp{0%{opacity:0;transform:translateY(20px)}100%{opacity:1;transform:translateY(0)}}.skip-button{position:absolute;bottom:20px;left:50%;transform:translateX(-50%);z-index:25;pointer-events:auto;background:#fff;color:#333;border:none;border-radius:25px;padding:12px 24px;font-size:14px;font-weight:600;cursor:pointer;transition:all 0.3s ease}.skip-button:hover{background:#f8f9fa}.skip-button:active{background:#e9ecef;transform:translateX(-50%) translateY(0)}.camera-controls{position:absolute;top:16px;right:16px;z-index:25;display:flex;gap:8px;pointer-events:auto}.camera-selector-button{height:32px;padding:0 10px;border:none;border-radius:8px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(12px);color:#ffffff;font-size:12px;font-weight:500;cursor:pointer;transition:all 0.2s ease;display:flex;align-items:center;justify-content:center;border:1px solid rgba(255, 255, 255, 0.1);white-space:nowrap;min-width:fit-content}.camera-selector-button:hover{background:rgba(0, 0, 0, 0.8);border-color:rgba(255, 255, 255, 0.2);transform:translateY(-1px)}.camera-selector-button:active{transform:translateY(0);background:rgba(0, 0, 0, 0.9)}.camera-selector-button:disabled,.camera-selector-button.loading{opacity:0.7;cursor:not-allowed;pointer-events:none}.camera-selector-button:disabled:hover,.camera-selector-button.loading:hover{transform:none;background:rgba(0, 0, 0, 0.6);border-color:rgba(255, 255, 255, 0.1)}.button-spinner{width:16px;height:16px;border:2px solid rgba(255, 255, 255, 0.3);border-top:2px solid #ffffff;border-radius:50%;animation:spin 1s linear infinite}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.camera-selector-dropdown{position:absolute;top:56px;right:16px;z-index:30;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;min-width:260px;max-width:300px;border:1px solid rgba(255, 255, 255, 0.1);overflow:hidden;pointer-events:auto;animation:slideInFromTop 0.3s ease-out}@keyframes slideInFromTop{0%{opacity:0;transform:translateY(-8px) scale(0.95)}100%{opacity:1;transform:translateY(0) scale(1)}}.camera-selector-header{display:flex;justify-content:space-between;align-items:center;padding:8px 12px;border-bottom:1px solid rgba(255, 255, 255, 0.1)}.camera-selector-header span{font-weight:500;color:#ffffff;font-size:13px;opacity:0.9}.close-selector{width:20px;height:20px;border:none;background:none;color:rgba(255, 255, 255, 0.7);font-size:16px;cursor:pointer;display:flex;align-items:center;justify-content:center;border-radius:4px;transition:all 0.2s ease}.close-selector:hover{background:rgba(255, 255, 255, 0.1);color:#ffffff}.camera-list{padding:4px 0;max-height:240px;overflow-y:auto}.camera-option{width:100%;padding:8px 12px;border:none;background:none;text-align:left;cursor:pointer;transition:all 0.2s ease;display:flex;justify-content:space-between;align-items:center;color:rgba(255, 255, 255, 0.9)}.camera-option:hover{background:rgba(255, 255, 255, 0.08)}.camera-option.selected{background:rgba(255, 255, 255, 0.12);color:#ffffff}.camera-label{font-size:13px;flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;margin-right:8px;font-weight:400}.selected-indicator{font-size:14px;color:#ffffff;opacity:0.9}.device-info{padding:6px 12px;border-top:1px solid rgba(255, 255, 255, 0.1);background:rgba(255, 255, 255, 0.05)}.device-info small{color:rgba(255, 255, 255, 0.6);font-size:11px;text-transform:capitalize;font-weight:400}@media (max-width: 480px){.camera-controls{top:12px;right:12px;gap:6px}.camera-selector-button{height:36px;padding:0 12px;font-size:11px;border-radius:6px}.camera-selector-dropdown{right:12px;top:48px;min-width:240px;max-width:calc(100vw - 24px)}.camera-selector-header{padding:6px 10px}.camera-option{padding:6px 10px}.device-info{padding:4px 10px}}.watermark{position:absolute;bottom:12px;right:12px;z-index:15;pointer-events:none;opacity:0.7}.watermark img{height:24px;width:auto;filter:drop-shadow(0 1px 2px rgba(0, 0, 0, 0.3))}.component-status{position:absolute;top:16px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);display:flex;align-items:center;gap:6px;padding:6px 10px;z-index:40;height:32px;width:fit-content;animation:slideInFromTop 0.3s ease-out}.status-spinner{width:16px;height:16px;border:1px solid rgba(255, 255, 255, 0.3);border-top:1px solid #ffffff;border-radius:50%;animation:statusSpin 1s linear infinite;flex-shrink:0}.status-content{display:flex;flex-direction:column;gap:1px}.status-message{color:#ffffff;font-size:12px;font-weight:500;margin:0}.status-description{color:rgba(255, 255, 255, 0.7);font-size:10px;line-height:1.2;margin:0}@keyframes statusSpin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}@media (max-width: 480px){.component-status{top:12px;left:12px;padding:4px 8px;gap:4px;height:28px;border-radius:8px}.status-spinner{width:14px;height:14px}.status-message{font-size:11px}.status-description{font-size:9px}}.loading-overlay{position:absolute;top:0;left:0;width:100%;height:100%;background:rgba(0, 0, 0, 0.85);backdrop-filter:blur(4px);display:flex;flex-direction:column;align-items:center;justify-content:center;z-index:30;border-radius:8px}.loading-spinner{width:50px;height:50px;border:3px solid rgba(255, 255, 255, 0.15);border-top:3px solid #28a745;border-radius:50%;animation:spin 1s ease-in-out infinite;margin-bottom:16px}.loading-text{color:#ffffff;font-size:14px;font-weight:500;text-align:center;opacity:0.9;margin-bottom:4px}.loading-description{color:rgba(255, 255, 255, 0.7);font-size:12px;text-align:center;opacity:0.8}@keyframes spin{0%{transform:rotate(0deg)}100%{transform:rotate(360deg)}}.performance-monitor{position:absolute;top:70px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromLeft 0.3s ease-out;transition:all 0.3s ease}@keyframes slideInFromLeft{0%{opacity:0;transform:translateX(-20px) scale(0.95)}100%{opacity:1;transform:translateX(0) scale(1)}}.performance-expanded{padding:6px 10px}.metrics-row{display:flex;gap:8px;margin-bottom:4px}.metrics-row:last-child{margin-bottom:0}.metric-compact{display:flex;flex-direction:column;align-items:center;gap:2px;min-width:50px}.metric-label{font-size:9px;color:rgba(255, 255, 255, 0.6);font-weight:500;text-transform:uppercase;letter-spacing:0.3px}.metric-value{font-size:10px;font-weight:600;font-family:'Monaco', 'Menlo', 'Consolas', monospace;padding:2px 4px;border-radius:3px;text-align:center;white-space:nowrap}.metric-value.good{color:#4ade80;background:rgba(74, 222, 128, 0.1);border:1px solid rgba(74, 222, 128, 0.2)}.metric-value.warning{color:#fbbf24;background:rgba(251, 191, 36, 0.1);border:1px solid rgba(251, 191, 36, 0.2)}.metric-value.danger{color:#f87171;background:rgba(248, 113, 113, 0.1);border:1px solid rgba(248, 113, 113, 0.2)}@media (max-width: 480px){.performance-monitor{top:60px;left:12px;width:fit-content}.performance-expanded{padding:4px 8px}.metrics-row{gap:6px;margin-bottom:3px}.metric-compact{min-width:45px;gap:1px}.metric-label{font-size:8px}.metric-value{font-size:9px;padding:1px 3px}}.quality-monitor{position:absolute;top:200px;left:16px;background:rgba(0, 0, 0, 0.25);backdrop-filter:blur(20px);border-radius:12px;border:1px solid rgba(255, 255, 255, 0.1);z-index:35;width:fit-content;animation:slideInFromLeft 0.3s ease-out;transition:all 0.3s ease}.quality-text{padding:6px 10px;font-size:11px;color:white;font-family:'Monaco', 'Menlo', 'Consolas', monospace;line-height:1.4}.quality-fail{color:#ff9999}@keyframes pulse{0%,100%{opacity:1}50%{opacity:0.7}}.metric-value.danger{animation:pulse 2s infinite}@media (max-width: 480px){.quality-monitor{top:160px;left:12px}.quality-text{padding:4px 8px;font-size:10px}}";
1147
+
1148
+ const JaakStamps = class {
1149
+ constructor(hostRef) {
1150
+ index.registerInstance(this, hostRef);
1151
+ this.captureCompleted = index.createEvent(this, "captureCompleted");
1152
+ this.isReady = index.createEvent(this, "isReady");
1153
+ }
1154
+ get el() { return index.getElement(this); }
1155
+ debug = false;
1156
+ alignmentTolerance = 15;
1157
+ maskSize = 80;
1158
+ cropMargin = 20;
1159
+ useDocumentClassification = false;
1160
+ preferredCamera = 'auto';
1161
+ captureDelay = 1500;
1162
+ captureCompleted;
1163
+ isReady;
1164
+ // State derived from services
1165
+ detectionBoxes = [];
1166
+ sideAlignment = {
1167
+ top: false, right: false, bottom: false, left: false
1168
+ };
1169
+ isMaskReady = false;
1170
+ shouldMirrorVideo = true;
1171
+ showCameraSelector = false;
1172
+ isSwitchingCamera = false;
1173
+ hasDocumentDetected = false;
1174
+ currentStatus = {
1175
+ message: 'Inicializando componente...',
1176
+ description: 'Configurando servicios y cargando recursos',
1177
+ type: 'initializing',
1178
+ isInitialized: false
1179
+ };
1180
+ performanceData = {
1181
+ fps: 0,
1182
+ inferenceTime: 0,
1183
+ memoryUsage: 0,
1184
+ onnxLoadTime: 0,
1185
+ frameProcessingTime: 0,
1186
+ totalDetections: 0,
1187
+ successfulDetections: 0,
1188
+ detectionRate: 0
1189
+ };
1190
+ // Services
1191
+ serviceContainer;
1192
+ logger;
1193
+ eventBus;
1194
+ stateManager;
1195
+ cameraService;
1196
+ detectionService;
1197
+ // UI References
1198
+ videoRef;
1199
+ detectionContainer;
1200
+ videoStream;
1201
+ animationId;
1202
+ // Detection state
1203
+ lastDetectedBox;
1204
+ startTime;
1205
+ hasScreenshotTaken = false;
1206
+ alignmentStartTime;
1207
+ alignmentTimer;
1208
+ // Performance monitoring
1209
+ performanceMetrics = {
1210
+ fps: 0,
1211
+ inferenceTime: 0,
1212
+ memoryUsage: 0,
1213
+ cpuUsage: 0,
1214
+ onnxLoadTime: 0,
1215
+ frameProcessingTime: 0,
1216
+ totalDetections: 0,
1217
+ successfulDetections: 0,
1218
+ detectionRate: 0,
1219
+ lastUpdateTime: 0
1220
+ };
1221
+ performanceUpdateInterval;
1222
+ // Performance optimization
1223
+ frameSkipCounter = 0;
1224
+ FRAME_SKIP = 2;
1225
+ consecutiveFailures = 0;
1226
+ MAX_FAILURES = 30;
1227
+ lastInferenceTime = 0;
1228
+ MIN_INFERENCE_INTERVAL = 50;
1229
+ async componentDidLoad() {
1230
+ this.updateStatus('Iniciando servicios...', 'Configurando módulos internos', 'initializing');
1231
+ await this.initializeServices();
1232
+ this.updateStatus('Configurando eventos...', 'Preparando comunicación entre servicios', 'initializing');
1233
+ await this.setupEventListeners();
1234
+ this.updateStatus('Inicializando cámara...', 'Detectando dispositivos disponibles', 'initializing');
1235
+ await this.initializeComponent();
1236
+ if (this.debug) {
1237
+ this.initializePerformanceMonitor();
336
1238
  }
337
1239
  }
338
- async setupCameraWithRetry(maxRetries = 3) {
339
- for (let attempt = 1; attempt <= maxRetries; attempt++) {
340
- try {
341
- await this.setupCamera();
342
- return; // Success
343
- }
344
- catch (error) {
345
- this.debugLog(`❌ Camera setup attempt ${attempt} failed:`, error);
346
- if (attempt === maxRetries) {
347
- // Last attempt failed, handle the error
348
- this.handleCameraPermissionError(error);
349
- throw error;
350
- }
351
- // Wait before retrying
352
- await new Promise(resolve => setTimeout(resolve, 500 * attempt));
353
- }
354
- }
1240
+ async initializeServices() {
1241
+ const config = {
1242
+ debug: this.debug,
1243
+ alignmentTolerance: this.alignmentTolerance,
1244
+ maskSize: this.maskSize,
1245
+ cropMargin: this.cropMargin,
1246
+ useDocumentClassification: this.useDocumentClassification,
1247
+ preferredCamera: this.preferredCamera,
1248
+ captureDelay: this.captureDelay
1249
+ };
1250
+ this.serviceContainer = new ServiceContainer(config);
1251
+ this.logger = this.serviceContainer.getLogger();
1252
+ this.eventBus = this.serviceContainer.getEventBus();
1253
+ this.stateManager = this.serviceContainer.getStateManager();
1254
+ this.cameraService = this.serviceContainer.getCameraService();
1255
+ this.detectionService = this.serviceContainer.getDetectionService();
1256
+ this.logger.state('SERVICIOS_INICIALIZADOS', { timestamp: Date.now() });
355
1257
  }
356
- toggleCameraSelector() {
357
- this.showCameraSelector = !this.showCameraSelector;
358
- this.debugLog('📹 Camera selector toggled:', {
359
- showCameraSelector: this.showCameraSelector,
360
- isMultipleCamerasAvailable: this.isMultipleCamerasAvailable,
361
- availableCameras: this.availableCameras.length,
362
- isVideoActive: this.isVideoActive
1258
+ async setupEventListeners() {
1259
+ this.eventBus.on('state-changed', (data) => {
1260
+ this.handleStateChange(data);
1261
+ });
1262
+ this.eventBus.on('camera-changed', (cameraId) => {
1263
+ this.logger.state('CAMARA_CAMBIADA_EVENT', { cameraId });
1264
+ });
1265
+ this.eventBus.on('error', (error) => {
1266
+ this.logger.error('Error en servicio:', error);
363
1267
  });
364
1268
  }
365
- async flipCamera() {
366
- if (!this.isMultipleCamerasAvailable)
367
- return;
368
- const currentIndex = this.availableCameras.findIndex(camera => camera.deviceId === this.selectedCameraId);
369
- const nextIndex = (currentIndex + 1) % this.availableCameras.length;
370
- const nextCamera = this.availableCameras[nextIndex];
371
- await this.switchCamera(nextCamera.deviceId);
1269
+ async initializeComponent() {
1270
+ this.logger.state('COMPONENTE_INICIALIZANDO', {
1271
+ debug: this.debug,
1272
+ maskSize: this.maskSize,
1273
+ cropMargin: this.cropMargin,
1274
+ useDocumentClassification: this.useDocumentClassification,
1275
+ preferredCamera: this.preferredCamera,
1276
+ captureDelay: this.captureDelay
1277
+ });
1278
+ this.validateProps();
1279
+ if (this.debug) {
1280
+ this.stateManager.updateCaptureState({ isLoading: true });
1281
+ await new Promise(resolve => setTimeout(resolve, 500));
1282
+ }
1283
+ this.updateStatus('Detectando cámaras...', 'Buscando dispositivos de captura', 'initializing');
1284
+ await this.cameraService.detectDeviceType();
1285
+ await this.cameraService.enumerateDevices();
1286
+ this.updateStatus('Cargando modelo IA...', 'Preparando reconocimiento de documentos', 'initializing');
1287
+ await this.loadOnnxRuntime();
1288
+ this.initializeResizeObserver();
372
1289
  }
373
- async componentDidLoad() {
374
- this.validateMaskSize();
375
- this.validateCropMargin();
376
- this.validatePreferredCamera();
377
- await this.detectDeviceTypeAndCameras();
1290
+ validateProps() {
1291
+ if (this.maskSize < 50 || this.maskSize > 100) {
1292
+ this.logger.warn(`Propiedad maskSize inválida. Valor: ${this.maskSize}, esperado: 50-100. Usando valor por defecto: 90`);
1293
+ this.maskSize = 90;
1294
+ }
1295
+ if (this.cropMargin < 0 || this.cropMargin > 100) {
1296
+ this.logger.warn(`Propiedad cropMargin inválida. Valor: ${this.cropMargin}, esperado: 0-100. Usando valor por defecto: 0`);
1297
+ this.cropMargin = 0;
1298
+ }
1299
+ const validOptions = ['auto', 'front', 'back'];
1300
+ if (!validOptions.includes(this.preferredCamera)) {
1301
+ this.logger.warn(`Propiedad preferredCamera inválida. Valor: ${this.preferredCamera}, esperado: ${validOptions.join(', ')}. Usando valor por defecto: 'auto'`);
1302
+ this.preferredCamera = 'auto';
1303
+ }
1304
+ if (this.captureDelay < 0 || this.captureDelay > 10000) {
1305
+ this.logger.warn(`Propiedad captureDelay inválida. Valor: ${this.captureDelay}, esperado: 0-10000. Usando valor por defecto: 1500`);
1306
+ this.captureDelay = 1500;
1307
+ }
1308
+ }
1309
+ async loadOnnxRuntime() {
378
1310
  if (!window.ort) {
1311
+ this.updateStatus('Descargando librerías...', 'Obteniendo recursos de reconocimiento', 'initializing');
379
1312
  const script = document.createElement('script');
380
1313
  script.src = 'https://cdn.jsdelivr.net/npm/onnxruntime-web/dist/ort.min.js';
381
1314
  document.head.appendChild(script);
382
- // Wait for ONNX runtime to load before emitting ready event
383
- script.onload = () => {
384
- this.emitReadyEvent();
385
- };
1315
+ await new Promise((resolve) => {
1316
+ script.onload = () => {
1317
+ setTimeout(() => {
1318
+ this.finalizeInitialization();
1319
+ resolve(undefined);
1320
+ }, 300);
1321
+ };
1322
+ });
386
1323
  }
387
1324
  else {
388
- // ONNX runtime already loaded
389
- this.emitReadyEvent();
1325
+ setTimeout(() => {
1326
+ this.finalizeInitialization();
1327
+ }, 300);
390
1328
  }
391
- // Initialize canvas pool for better performance
392
- this.initializeCanvasPool();
393
- this.setupResizeObserver();
394
1329
  }
395
- setupResizeObserver() {
396
- if ('ResizeObserver' in window && this.canvasRef) {
1330
+ finalizeInitialization() {
1331
+ this.stateManager.updateCaptureState({ isLoading: false });
1332
+ this.currentStatus = {
1333
+ message: 'Listo para capturar',
1334
+ description: '',
1335
+ type: 'ready',
1336
+ isInitialized: true
1337
+ };
1338
+ this.emitReadyEvent();
1339
+ }
1340
+ updateStatus(message, description, type = 'loading') {
1341
+ this.currentStatus = {
1342
+ message,
1343
+ description,
1344
+ type,
1345
+ isInitialized: this.currentStatus.isInitialized
1346
+ };
1347
+ }
1348
+ emitReadyEvent() {
1349
+ const isDocumentReady = !!window.ort && this.detectionService.isModelLoaded();
1350
+ this.isReady.emit(isDocumentReady);
1351
+ this.logger.state('COMPONENTE_LISTO', {
1352
+ ortLibraryLoaded: !!window.ort,
1353
+ modelPreloaded: this.detectionService.isModelLoaded(),
1354
+ isReady: isDocumentReady
1355
+ });
1356
+ }
1357
+ handleStateChange(data) {
1358
+ }
1359
+ initializeResizeObserver() {
1360
+ if ('ResizeObserver' in window && this.detectionContainer) {
397
1361
  const resizeObserver = new ResizeObserver(() => {
398
1362
  this.handleResize();
399
1363
  });
400
- resizeObserver.observe(this.canvasRef.parentElement);
1364
+ resizeObserver.observe(this.detectionContainer.parentElement);
401
1365
  }
402
1366
  }
403
1367
  handleResize() {
404
- if (this.canvasRef) {
405
- const container = this.canvasRef.parentElement;
1368
+ if (this.detectionContainer) {
1369
+ const container = this.detectionContainer.parentElement;
406
1370
  const rect = container.getBoundingClientRect();
407
- // Set canvas size to match container
408
- this.canvasRef.width = rect.width;
409
- this.canvasRef.height = rect.height;
410
- // Update mask positioning based on container and video dimensions
411
1371
  this.updateMaskDimensions(rect);
412
- this.debugLog('📐 Canvas resized:', { width: rect.width, height: rect.height });
1372
+ this.logger.debug('Container redimensionado:', { width: rect.width, height: rect.height });
413
1373
  }
414
1374
  }
415
1375
  updateMaskDimensions(containerRect) {
@@ -426,32 +1386,27 @@ const JaakStamps = class {
426
1386
  let displayedVideoWidth, displayedVideoHeight;
427
1387
  let videoOffsetX = 0, videoOffsetY = 0;
428
1388
  if (videoAspectRatio > containerAspectRatio) {
429
- // Video is wider - letterboxed (black bars top/bottom)
430
1389
  displayedVideoWidth = containerRect.width;
431
1390
  displayedVideoHeight = containerRect.width / videoAspectRatio;
432
1391
  videoOffsetY = (containerRect.height - displayedVideoHeight) / 2;
433
1392
  }
434
1393
  else {
435
- // Video is taller - pillarboxed (black bars left/right)
436
1394
  displayedVideoHeight = containerRect.height;
437
1395
  displayedVideoWidth = containerRect.height * videoAspectRatio;
438
1396
  videoOffsetX = (containerRect.width - displayedVideoWidth) / 2;
439
1397
  }
440
- // Calculate maximum possible mask size while preserving exact ID-1 aspect ratio
441
- // Determine the limiting dimension based on video orientation and ID-1 proportions
442
- // Calculate what would be the max width if limited by video height
443
- const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;
1398
+ // Calculate mask dimensions with ID-1 aspect ratio
1399
+ const ID1_ASPECT_RATIO = 85.60 / 53.98;
1400
+ const maxWidthByHeight = displayedVideoHeight * ID1_ASPECT_RATIO;
444
1401
  let maskWidthInVideo, maskHeightInVideo;
445
1402
  const sizeRatio = this.maskSize / 100;
446
1403
  if (maxWidthByHeight <= displayedVideoWidth) {
447
- // Video height is the limiting factor
448
1404
  maskHeightInVideo = displayedVideoHeight * sizeRatio;
449
- maskWidthInVideo = maskHeightInVideo * this.ID1_ASPECT_RATIO;
1405
+ maskWidthInVideo = maskHeightInVideo * ID1_ASPECT_RATIO;
450
1406
  }
451
1407
  else {
452
- // Video width is the limiting factor
453
1408
  maskWidthInVideo = displayedVideoWidth * sizeRatio;
454
- maskHeightInVideo = maskWidthInVideo / this.ID1_ASPECT_RATIO;
1409
+ maskHeightInVideo = maskWidthInVideo / ID1_ASPECT_RATIO;
455
1410
  }
456
1411
  // Convert to percentages of the container
457
1412
  const maskWidthPercent = (maskWidthInVideo / containerRect.width) * 100;
@@ -467,9 +1422,8 @@ const JaakStamps = class {
467
1422
  this.el.style.setProperty('--mask-height', `${maskHeightPercent}%`);
468
1423
  this.el.style.setProperty('--mask-center-x', `${videoCenterXPercent}%`);
469
1424
  this.el.style.setProperty('--mask-center-y', `${videoCenterYPercent}%`);
470
- // Mark mask as ready now that dimensions are calculated
471
1425
  this.isMaskReady = true;
472
- this.debugLog('🎯 Mask dimensions updated:', {
1426
+ this.logger.state('DIMENSIONES_MASCARA_ACTUALIZADAS', {
473
1427
  video: { width: videoWidth, height: videoHeight },
474
1428
  displayed: { width: displayedVideoWidth, height: displayedVideoHeight },
475
1429
  mask: { widthPercent: maskWidthPercent, heightPercent: maskHeightPercent },
@@ -477,46 +1431,16 @@ const JaakStamps = class {
477
1431
  offset: { x: videoOffsetX, y: videoOffsetY }
478
1432
  });
479
1433
  }
480
- initializeCanvasPool() {
481
- // Preprocess canvas - reused for every inference
482
- this.preprocessCanvas = document.createElement('canvas');
483
- this.preprocessCanvas.width = this.INPUT_SIZE;
484
- this.preprocessCanvas.height = this.INPUT_SIZE;
485
- this.preprocessCtx = this.preprocessCanvas.getContext('2d', {
486
- alpha: false, // No transparency needed
487
- willReadFrequently: true // Optimize for frequent getImageData calls
488
- });
489
- // Capture canvas - reused for screenshots
490
- this.captureCanvas = document.createElement('canvas');
491
- this.captureCtx = this.captureCanvas.getContext('2d', {
492
- alpha: false
493
- });
494
- this.debugLog('🎨 Canvas pool initialized for performance');
495
- }
496
- disconnectedCallback() {
497
- this.cleanup();
498
- }
1434
+ // PUBLIC METHODS
499
1435
  async getCapturedImages() {
500
- if (this.captureStep !== 'completed') {
1436
+ const state = this.stateManager.getCaptureState();
1437
+ if (state.step !== 'completed') {
501
1438
  throw new Error('El proceso de captura no ha sido completado');
502
1439
  }
503
- return {
504
- front: {
505
- fullFrame: this.capturedFullFrame,
506
- cropped: this.capturedCroppedId
507
- },
508
- back: {
509
- fullFrame: this.capturedBackFullFrame,
510
- cropped: this.capturedBackCroppedId
511
- },
512
- metadata: {
513
- hasBackCapture: !!(this.capturedBackFullFrame && this.capturedBackCroppedId),
514
- totalImages: (this.capturedBackFullFrame && this.capturedBackCroppedId) ? 4 : 2
515
- }
516
- };
1440
+ return this.stateManager.getCapturedImages();
517
1441
  }
518
1442
  async isProcessCompleted() {
519
- return this.captureStep === 'completed';
1443
+ return this.stateManager.isProcessCompleted();
520
1444
  }
521
1445
  async startCapture() {
522
1446
  await this.startDetection();
@@ -525,454 +1449,252 @@ const JaakStamps = class {
525
1449
  this.exitSession();
526
1450
  }
527
1451
  async resetCapture() {
528
- this.resetDetection();
529
- }
530
- async getStatus() {
531
- return {
532
- isVideoActive: this.isVideoActive,
533
- captureStep: this.captureStep,
534
- statusMessage: this.statusMessage,
535
- hasImages: !!(this.capturedFullFrame || this.capturedBackFullFrame),
536
- isProcessCompleted: this.captureStep === 'completed',
537
- isModelPreloaded: this.isModelPreloaded
538
- };
539
- }
540
- async preloadModel() {
541
- if (this.isModelPreloaded || this.session) {
542
- this.debugLog('🚀 Model already preloaded or session exists');
543
- return { success: true, message: 'Model already loaded' };
544
- }
545
- try {
546
- this.isLoading = true;
547
- this.statusMessage = "Precargando modelos...";
548
- this.statusColor = "#007bff";
549
- const modelPath = this.MODEL_PATH;
550
- this.debugLog('🤖 Preloading detection model:', modelPath);
551
- // Configure ONNX Runtime with device-specific optimizations
552
- const sessionOptions = this.getSessionOptions();
553
- this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
554
- // Preload MobileNet model and classes only if classification is enabled
555
- if (this.useDocumentClassification) {
556
- await this.loadMobileNetModel();
557
- }
558
- this.isModelPreloaded = true;
559
- this.isLoading = false;
560
- this.statusMessage = "Modelos precargados. Listo para comenzar detección";
561
- this.statusColor = "#28a745";
562
- this.emitReadyEvent();
563
- this.debugLog('✅ Models preloaded successfully');
564
- return { success: true, message: 'Models preloaded successfully' };
565
- }
566
- catch (error) {
567
- this.debugLog('❌ Error preloading models:', error);
568
- this.isLoading = false;
569
- this.statusMessage = "Error al precargar los modelos";
570
- this.statusColor = "#ff6b6b";
571
- return { success: false, error: error.message };
572
- }
573
- }
574
- async skipBackCapture() {
575
- if (this.captureStep === 'back' && this.capturedFullFrame) {
576
- this.completeProcess(true);
577
- }
578
- }
579
- async getCameraInfo() {
580
- return {
581
- availableCameras: this.availableCameras.map(camera => ({
582
- id: camera.deviceId,
583
- label: camera.label || 'Unknown Camera',
584
- selected: camera.deviceId === this.selectedCameraId
585
- })),
586
- selectedCameraId: this.selectedCameraId,
587
- deviceType: this.deviceType,
588
- isMultipleCamerasAvailable: this.isMultipleCamerasAvailable,
589
- preferredFacing: this.preferredCameraFacing,
590
- userPreferredCamera: this.preferredCamera
591
- };
592
- }
593
- async setPreferredCamera(camera) {
594
- this.preferredCamera = camera;
595
- this.debugLog('🎯 Camera preference changed to:', camera);
596
- // Re-detect and apply new camera preference
597
- await this.enumerateAndDetectCameras();
598
- // If video is active, switch to the new preferred camera
599
- if (this.isVideoActive && this.selectedCameraId) {
600
- await this.switchCamera(this.selectedCameraId);
601
- }
602
- return {
603
- success: true,
604
- selectedCamera: this.selectedCameraId,
605
- availableCameras: this.availableCameras.length
606
- };
607
- }
608
- async loadMobileNetModel() {
609
- try {
610
- this.debugLog('🤖 Loading MobileNet model...');
611
- // Load class map
612
- const classResponse = await fetch(this.MOBILENET_CLASSES_PATH);
613
- if (!classResponse.ok) {
614
- throw new Error(`Failed to load class map: ${this.MOBILENET_CLASSES_PATH}`);
615
- }
616
- this.mobileNetClassMap = await classResponse.json();
617
- this.debugLog('📋 MobileNet classes loaded:', this.mobileNetClassMap);
618
- // Load model
619
- const sessionOptions = this.getSessionOptions();
620
- this.mobileNetSession = await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, sessionOptions);
621
- this.debugLog('✅ MobileNet model loaded successfully');
622
- }
623
- catch (error) {
624
- this.debugLog('❌ Error loading MobileNet model:', error);
625
- throw error;
626
- }
627
- }
628
- preprocessMobileNet(canvas) {
629
- // Create a temporary canvas for MobileNet preprocessing (224x224)
630
- const tempCanvas = document.createElement('canvas');
631
- tempCanvas.width = 224;
632
- tempCanvas.height = 224;
633
- const tempCtx = tempCanvas.getContext('2d');
634
- // Draw the cropped image onto the 224x224 canvas
635
- tempCtx.drawImage(canvas, 0, 0, 224, 224);
636
- // Get image data and preprocess for MobileNet
637
- const imageData = tempCtx.getImageData(0, 0, 224, 224);
638
- const data = imageData.data;
639
- const hw = 224 * 224;
640
- const arr = new Float32Array(3 * hw);
641
- // Normalize pixels: (pixel/255 - 0.5) / 0.5 = (pixel - 127.5) / 127.5
642
- for (let i = 0; i < hw; i++) {
643
- arr[i] = (data[i * 4 + 0] / 255 - 0.5) / 0.5; // R
644
- arr[hw + i] = (data[i * 4 + 1] / 255 - 0.5) / 0.5; // G
645
- arr[2 * hw + i] = (data[i * 4 + 2] / 255 - 0.5) / 0.5; // B
646
- }
647
- return new window.ort.Tensor('float32', arr, [1, 3, 224, 224]);
648
- }
649
- async classifyDocument(canvas) {
650
- if (!this.mobileNetSession || !this.mobileNetClassMap) {
651
- this.debugLog('⚠️ MobileNet model not loaded');
652
- return null;
653
- }
654
- try {
655
- this.debugLog('🔍 Classifying document...');
656
- // Preprocess image for MobileNet
657
- const inputTensor = this.preprocessMobileNet(canvas);
658
- // Run inference
659
- const feeds = { input: inputTensor };
660
- const results = await this.mobileNetSession.run(feeds);
661
- const output = results[Object.keys(results)[0]].data;
662
- // Find the class with highest confidence
663
- const maxIdx = output.reduce((bestIdx, val, idx, arr) => val > arr[bestIdx] ? idx : bestIdx, 0);
664
- const confidence = output[maxIdx];
665
- const className = this.mobileNetClassMap[maxIdx.toString()] || "unknown";
666
- this.debugLog('📄 Document classification result:', {
667
- class: className,
668
- confidence: confidence.toFixed(3),
669
- classIndex: maxIdx
670
- });
671
- return {
672
- class: className,
673
- confidence: confidence,
674
- classIndex: maxIdx
675
- };
676
- }
677
- catch (error) {
678
- this.debugLog('❌ Error classifying document:', error);
679
- return null;
680
- }
681
- }
682
- cleanup() {
683
- if (this.animationId) {
684
- cancelAnimationFrame(this.animationId);
685
- }
686
- if (this.videoStream) {
687
- this.videoStream.getTracks().forEach(track => track.stop());
688
- }
689
- // Limpiar canvas en cleanup general
690
- if (this.canvasRef) {
691
- const ctx = this.canvasRef.getContext("2d");
692
- if (ctx) {
693
- ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
694
- }
695
- }
696
- // OPTIMIZATION: Clean up canvas pool
697
- this.cleanupCanvasPool();
698
- }
699
- cleanupCanvasPool() {
700
- // Release canvas references for garbage collection
701
- if (this.preprocessCanvas) {
702
- this.preprocessCtx = undefined;
703
- this.preprocessCanvas = undefined;
704
- }
705
- if (this.captureCanvas) {
706
- this.captureCtx = undefined;
707
- this.captureCanvas = undefined;
708
- }
709
- // Disposed ONNX sessions
710
- if (this.session) {
711
- this.session.release?.();
712
- this.session = undefined;
713
- }
714
- if (this.mobileNetSession) {
715
- this.mobileNetSession.release?.();
716
- this.mobileNetSession = undefined;
717
- }
718
- this.mobileNetClassMap = undefined;
719
- this.isModelPreloaded = false;
720
- this.debugLog('🧹 Canvas pool cleaned up');
721
- }
722
- async getMaxResolution() {
723
- try {
724
- // Build constraints with selected camera if available
725
- const videoConstraints = {};
726
- if (this.selectedCameraId) {
727
- videoConstraints.deviceId = { exact: this.selectedCameraId };
728
- }
729
- else if (this.preferredCameraFacing) {
730
- videoConstraints.facingMode = this.preferredCameraFacing;
731
- }
732
- else {
733
- videoConstraints.facingMode = "environment";
734
- }
735
- // Get temporary stream to access capabilities
736
- const tempStream = await navigator.mediaDevices.getUserMedia({
737
- video: videoConstraints
738
- });
739
- const videoTrack = tempStream.getVideoTracks()[0];
740
- const capabilities = videoTrack.getCapabilities();
741
- // Detener el stream temporal
742
- tempStream.getTracks().forEach(track => track.stop());
743
- // Build constraints with resolution optimized for tablets
744
- const constraints = {};
745
- // Set camera selection constraints
746
- if (this.selectedCameraId) {
747
- constraints.deviceId = { exact: this.selectedCameraId };
748
- }
749
- else if (this.preferredCameraFacing) {
750
- constraints.facingMode = this.preferredCameraFacing;
751
- }
752
- else {
753
- constraints.facingMode = "environment";
754
- }
755
- if (capabilities.width && capabilities.height) {
756
- // Limitar resolución máxima para tablets para evitar problemas de rendimiento
757
- const maxWidth = Math.min(capabilities.width.max, 1920);
758
- const maxHeight = Math.min(capabilities.height.max, 1080);
759
- // Para tablets, usar resolución moderada en lugar de máxima
760
- const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
761
- if (isTablet) {
762
- constraints.width = { ideal: Math.min(maxWidth, 1280) };
763
- constraints.height = { ideal: Math.min(maxHeight, 720) };
764
- }
765
- else {
766
- constraints.width = { ideal: maxWidth };
767
- constraints.height = { ideal: maxHeight };
768
- }
769
- this.debugLog('📐 Resolution capabilities:', {
770
- maxWidth: capabilities.width.max,
771
- maxHeight: capabilities.height.max,
772
- selectedWidth: constraints.width.ideal,
773
- selectedHeight: constraints.height.ideal,
774
- isTablet
775
- });
776
- }
777
- return constraints;
778
- }
779
- catch (err) {
780
- this.debugLog('⚠️ Could not get capabilities, using fallback');
781
- // Optimized fallback for tablets
782
- const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
783
- const fallbackConstraints = {
784
- width: { ideal: isTablet ? 1280 : 1920 },
785
- height: { ideal: isTablet ? 720 : 1080 }
786
- };
787
- // Add camera selection to fallback
788
- if (this.selectedCameraId) {
789
- fallbackConstraints.deviceId = { exact: this.selectedCameraId };
790
- }
791
- else if (this.preferredCameraFacing) {
792
- fallbackConstraints.facingMode = this.preferredCameraFacing;
793
- }
794
- else {
795
- fallbackConstraints.facingMode = "environment";
796
- }
797
- return fallbackConstraints;
1452
+ this.resetDetection();
1453
+ }
1454
+ async skipBackCapture() {
1455
+ const captureState = this.stateManager.getCaptureState();
1456
+ const capturedImages = this.stateManager.getCapturedImages();
1457
+ if (captureState.step === 'back' && capturedImages.front.fullFrame) {
1458
+ this.completeProcess(true);
798
1459
  }
799
1460
  }
800
- async setupCamera() {
1461
+ async getStatus() {
1462
+ const captureState = this.stateManager.getCaptureState();
1463
+ const capturedImages = this.stateManager.getCapturedImages();
1464
+ return {
1465
+ isVideoActive: captureState.isVideoActive,
1466
+ captureStep: captureState.step,
1467
+ hasImages: !!(capturedImages.front.fullFrame || capturedImages.back.fullFrame),
1468
+ isProcessCompleted: this.stateManager.isProcessCompleted(),
1469
+ isModelPreloaded: this.detectionService.isModelLoaded()
1470
+ };
1471
+ }
1472
+ async preloadModel() {
1473
+ if (this.detectionService.isModelLoaded()) {
1474
+ this.logger.state('MODELO_YA_PRECARGADO');
1475
+ this.updateStatus('Modelos ya cargados', '', 'ready');
1476
+ return { success: true, message: 'Model already loaded' };
1477
+ }
801
1478
  try {
802
- const constraints = await this.getMaxResolution();
803
- const stream = await navigator.mediaDevices.getUserMedia({
804
- video: constraints,
805
- audio: false
806
- });
807
- if (this.videoRef) {
808
- this.videoRef.srcObject = stream;
809
- this.videoStream = stream;
810
- // Determine if video should be mirrored
811
- const isRear = this.isRearCamera(stream);
812
- this.shouldMirrorVideo = !isRear;
813
- this.debugLog('📹 Rear camera:', isRear);
814
- this.debugLog('🪞 Should mirror video:', this.shouldMirrorVideo);
815
- return new Promise((resolve) => {
816
- this.videoRef.onloadedmetadata = async () => {
817
- await this.videoRef.play();
818
- this.isVideoActive = true;
819
- // Update mask dimensions once video is loaded
820
- if (this.canvasRef) {
821
- const container = this.canvasRef.parentElement;
822
- const rect = container.getBoundingClientRect();
823
- this.updateMaskDimensions(rect);
824
- }
825
- resolve();
826
- };
827
- });
1479
+ const loadStartTime = performance.now();
1480
+ this.updateStatus('Descargando modelo de detección...', 'Obteniendo red neuronal para reconocimiento de documentos', 'loading');
1481
+ this.stateManager.updateCaptureState({ isLoading: true });
1482
+ await this.detectionService.loadModel();
1483
+ this.updateStatus('Cargando clasificador...', 'Preparando modelo de clasificación de tipos de documento', 'loading');
1484
+ await this.detectionService.loadClassificationModel();
1485
+ const loadEndTime = performance.now();
1486
+ const loadTime = loadEndTime - loadStartTime;
1487
+ // Record ONNX load time
1488
+ if (this.debug) {
1489
+ this.recordOnnxPerformance(loadTime, 0);
828
1490
  }
1491
+ this.updateStatus('Optimizando modelos...', 'Configurando parámetros de rendimiento', 'loading');
1492
+ await new Promise(resolve => setTimeout(resolve, 300));
1493
+ this.updateStatus('Modelos precargados', '', 'ready');
1494
+ this.stateManager.updateCaptureState({ isLoading: false });
1495
+ this.emitReadyEvent();
1496
+ this.logger.state('MODELOS_PRECARGADOS_EXITOSAMENTE', { loadTime: Math.round(loadTime) });
1497
+ return { success: true, message: 'Models preloaded successfully' };
829
1498
  }
830
- catch (err) {
831
- this.debugLog("❌ No se pudo acceder a la cámara:", err);
832
- this.handleCameraPermissionError(err);
1499
+ catch (error) {
1500
+ this.logger.error('Error al precargar modelos:', error);
1501
+ this.updateStatus('Error al cargar modelos', 'No se pudieron descargar los recursos necesarios', 'error');
1502
+ this.stateManager.updateCaptureState({ isLoading: false });
1503
+ return { success: false, error: error.message };
833
1504
  }
834
1505
  }
835
- preprocess(video) {
836
- // OPTIMIZATION: Reuse canvas instead of creating new ones
837
- if (!this.preprocessCanvas || !this.preprocessCtx) {
838
- this.initializeCanvasPool();
1506
+ async getCameraInfo() {
1507
+ return this.cameraService.getCameraInfo();
1508
+ }
1509
+ async setPreferredCamera(camera) {
1510
+ this.preferredCamera = camera;
1511
+ this.serviceContainer.updateConfig({ preferredCamera: camera });
1512
+ await this.cameraService.enumerateDevices();
1513
+ const captureState = this.stateManager.getCaptureState();
1514
+ if (captureState.isVideoActive) {
1515
+ const selectedCameraId = this.cameraService.getSelectedCameraId();
1516
+ if (selectedCameraId) {
1517
+ await this.cameraService.switchCamera(selectedCameraId);
1518
+ }
839
1519
  }
840
- // Clear and redraw on reused canvas
841
- this.preprocessCtx.clearRect(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
842
- this.preprocessCtx.drawImage(video, 0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
843
- const imageData = this.preprocessCtx.getImageData(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
844
- const [R, G, B] = [[], [], []];
845
- const { data } = imageData;
846
- // Optimized pixel processing
847
- for (let i = 0; i < data.length; i += 4) {
848
- R.push(data[i] / 255);
849
- G.push(data[i + 1] / 255);
850
- B.push(data[i + 2] / 255);
1520
+ return {
1521
+ success: true,
1522
+ selectedCamera: this.cameraService.getSelectedCameraId(),
1523
+ availableCameras: this.cameraService.getAvailableCameras().length
1524
+ };
1525
+ }
1526
+ async setCaptureDelay(delay) {
1527
+ if (delay < 0 || delay > 10000) {
1528
+ throw new Error('Capture delay must be between 0 and 10000 milliseconds');
851
1529
  }
852
- const transposedData = new Float32Array(R.concat(G, B));
853
- return new window.ort.Tensor("float32", transposedData, [1, 3, this.INPUT_SIZE, this.INPUT_SIZE]);
1530
+ this.captureDelay = delay;
1531
+ this.serviceContainer.updateConfig({ captureDelay: delay });
1532
+ return {
1533
+ success: true,
1534
+ captureDelay: this.captureDelay
1535
+ };
1536
+ }
1537
+ async getCaptureDelay() {
1538
+ return this.captureDelay;
854
1539
  }
855
- getSessionOptions() {
1540
+ async setTorchEnabled(enabled) {
1541
+ const torchEnabled = await this.cameraService.setTorchEnabled(enabled, this.videoStream);
856
1542
  return {
857
- executionProviders: [
858
- // Try WebGL first for GPU acceleration, fallback to WASM
859
- 'webgl',
860
- 'wasm'
861
- ],
862
- graphOptimizationLevel: 'all', // Maximum optimization
863
- logSeverityLevel: this.debug ? 2 : 4, // Reduce logging overhead in production
864
- logVerbosityLevel: 0,
865
- enableCpuMemArena: true,
866
- enableMemPattern: true,
867
- executionMode: 'parallel',
868
- interOpNumThreads: 2,
869
- intraOpNumThreads: 2,
1543
+ success: torchEnabled,
1544
+ enabled: torchEnabled ? enabled : false
870
1545
  };
871
1546
  }
1547
+ async focusAtPoint(x, y) {
1548
+ const focused = await this.cameraService.focusAtPoint(x, y, this.videoStream);
1549
+ return {
1550
+ success: focused,
1551
+ coordinates: { x, y }
1552
+ };
1553
+ }
1554
+ // DETECTION METHODS
872
1555
  async startDetection() {
1556
+ this.logger.state('INICIANDO_DETECCION');
873
1557
  try {
874
- // Check if model is already preloaded
875
- if (!this.session) {
876
- this.isLoading = true;
877
- this.statusMessage = "Cargando modelos...";
878
- this.statusColor = "#007bff";
879
- const modelPath = this.MODEL_PATH;
880
- this.debugLog('🤖 Loading detection model:', modelPath);
881
- const sessionOptions = this.getSessionOptions();
882
- this.session = await window.ort.InferenceSession.create(modelPath, sessionOptions);
883
- // Load MobileNet model if classification is enabled and not already loaded
884
- if (this.useDocumentClassification && !this.mobileNetSession) {
885
- await this.loadMobileNetModel();
1558
+ // Paso 1: Verificar y cargar modelos si es necesario
1559
+ if (!this.detectionService.isModelLoaded()) {
1560
+ const loadStartTime = performance.now();
1561
+ this.updateStatus('Cargando modelo de detección...', 'Descargando red neuronal para reconocimiento', 'loading');
1562
+ this.stateManager.updateCaptureState({ isLoading: true });
1563
+ await this.detectionService.loadModel();
1564
+ this.updateStatus('Cargando clasificador...', 'Preparando modelo de clasificación de documentos', 'loading');
1565
+ await this.detectionService.loadClassificationModel();
1566
+ const loadEndTime = performance.now();
1567
+ const loadTime = loadEndTime - loadStartTime;
1568
+ // Record ONNX load time
1569
+ if (this.debug) {
1570
+ this.recordOnnxPerformance(loadTime, 0);
886
1571
  }
887
- this.isModelPreloaded = true;
888
- this.emitReadyEvent();
1572
+ this.logger.state('MODELOS_CARGADOS_EN_DETECCION', { loadTime: Math.round(loadTime) });
889
1573
  }
890
- else {
891
- this.debugLog('🚀 Using preloaded models');
892
- this.statusMessage = "Usando modelos precargados...";
893
- this.statusColor = "#007bff";
1574
+ // Paso 2: Detectar y configurar dispositivos
1575
+ this.updateStatus('Detectando cámaras...', 'Buscando dispositivos de captura disponibles', 'loading');
1576
+ await this.cameraService.enumerateDevices();
1577
+ // Paso 3: Configurar cámara seleccionada
1578
+ this.updateStatus('Configurando cámara...', 'Estableciendo resolución y parámetros óptimos', 'loading');
1579
+ const stream = await this.cameraService.setupCamera();
1580
+ // Paso 4: Inicializar video y ocultar estado inmediatamente
1581
+ this.updateStatus('Captura activa', 'Buscando documento en el marco de captura', 'active');
1582
+ await this.initializeVideoStream(stream);
1583
+ // Paso 5: Calibrar máscara
1584
+ if (this.detectionContainer) {
1585
+ const container = this.detectionContainer.parentElement;
1586
+ const rect = container.getBoundingClientRect();
1587
+ this.updateMaskDimensions(rect);
894
1588
  }
895
- this.statusMessage = "Configurando cámara...";
896
- await this.setupCamera();
1589
+ // Finalizar e iniciar captura
897
1590
  this.startTime = Date.now();
898
- this.isLoading = false;
1591
+ this.stateManager.updateCaptureState({ isLoading: false });
899
1592
  this.detectFrame();
900
1593
  }
901
1594
  catch (err) {
902
- this.debugLog("Error al inicializar:", err);
903
- this.statusMessage = "Error al inicializar el detector";
904
- this.statusColor = "#ff6b6b";
905
- this.isLoading = false;
1595
+ this.logger.error('Error al inicializar detección:', err);
1596
+ this.updateStatus('Error al iniciar captura', 'No se pudo completar la inicialización', 'error');
1597
+ this.stateManager.updateCaptureState({ isLoading: false });
1598
+ }
1599
+ }
1600
+ async initializeVideoStream(stream) {
1601
+ if (this.videoRef) {
1602
+ this.videoRef.srcObject = stream;
1603
+ this.videoStream = stream;
1604
+ const isRear = this.cameraService.isRearCamera(stream);
1605
+ this.shouldMirrorVideo = !isRear;
1606
+ this.logger.state('CAMARA_CONFIGURADA', {
1607
+ isRearCamera: isRear,
1608
+ shouldMirrorVideo: this.shouldMirrorVideo
1609
+ });
1610
+ return new Promise((resolve) => {
1611
+ this.videoRef.onloadedmetadata = async () => {
1612
+ await this.videoRef.play();
1613
+ this.stateManager.updateCaptureState({ isVideoActive: true });
1614
+ resolve();
1615
+ };
1616
+ });
1617
+ }
1618
+ else {
1619
+ throw new Error('Video element not available');
906
1620
  }
907
1621
  }
908
1622
  async detectFrame() {
909
1623
  try {
910
- if (!this.videoRef || !this.canvasRef || !this.session)
1624
+ const frameStartTime = performance.now();
1625
+ const captureState = this.stateManager.getCaptureState();
1626
+ if (!this.videoRef || !this.detectionContainer || !this.detectionService.isModelLoaded())
911
1627
  return;
912
- // Pausar detección si está marcado como pausado
913
- if (this.isDetectionPaused) {
914
- // Solo continuar el bucle sin procesar detección
915
- if (this.captureStep !== 'completed') {
1628
+ if (captureState.isDetectionPaused) {
1629
+ if (captureState.step !== 'completed') {
916
1630
  this.animationId = requestAnimationFrame(() => this.detectFrame());
917
1631
  }
918
1632
  return;
919
1633
  }
920
- // OPTIMIZATION 1: Frame skipping for performance
1634
+ // Frame skipping for performance
921
1635
  this.frameSkipCounter++;
922
1636
  if (this.frameSkipCounter <= this.FRAME_SKIP) {
923
- if (this.captureStep !== 'completed') {
1637
+ if (captureState.step !== 'completed') {
924
1638
  this.animationId = requestAnimationFrame(() => this.detectFrame());
925
1639
  }
926
1640
  return;
927
1641
  }
928
1642
  this.frameSkipCounter = 0;
929
- // OPTIMIZATION 2: Throttle inference based on time
1643
+ // Throttle inference
930
1644
  const currentTime = Date.now();
931
1645
  if (currentTime - this.lastInferenceTime < this.MIN_INFERENCE_INTERVAL) {
932
- if (this.captureStep !== 'completed') {
1646
+ if (captureState.step !== 'completed') {
933
1647
  this.animationId = requestAnimationFrame(() => this.detectFrame());
934
1648
  }
935
1649
  return;
936
1650
  }
937
1651
  this.lastInferenceTime = currentTime;
938
- const ctx = this.canvasRef.getContext("2d");
939
- const inputTensor = this.preprocess(this.videoRef);
940
- const feeds = { [this.session.inputNames[0]]: inputTensor };
941
- const results = await this.session.run(feeds);
942
- const output = results[this.session.outputNames[0]].data;
943
- const finalBoxes = [];
944
- for (let i = 0; i < output.length; i += 6) {
945
- const [x1, y1, x2, y2, score, classId] = output.slice(i, i + 6);
946
- if (score > this.CONFIDENCE_THRESHOLD) {
947
- finalBoxes.push({ x: x1, y: y1, w: x2 - x1, h: y2 - y1, score, classId });
948
- if (this.startTime && Date.now() - this.startTime < 5000) {
949
- const currentBox = { x: x1, y: y1, w: x2 - x1, h: y2 - y1, score };
950
- const isWellPositioned = this.isCardInFrame(currentBox);
951
- const effectiveScore = isWellPositioned ? score * 1.2 : score;
952
- if (effectiveScore > this.bestScore) {
953
- this.bestScore = effectiveScore;
954
- }
1652
+ // Measure preprocessing and inference time
1653
+ const inferenceStartTime = performance.now();
1654
+ const inputTensor = this.detectionService.preprocess(this.videoRef);
1655
+ // Standard detection without quality validation
1656
+ const detections = await this.detectionService.runInference(inputTensor);
1657
+ const inferenceTime = performance.now() - inferenceStartTime;
1658
+ // Record ONNX performance metrics
1659
+ if (this.debug) {
1660
+ this.recordOnnxPerformance(0, inferenceTime);
1661
+ }
1662
+ // Update best score logic
1663
+ if (this.startTime && Date.now() - this.startTime < 5000) {
1664
+ detections.forEach((detection) => {
1665
+ const isWellPositioned = this.detectionService.isCardInFrame(detection);
1666
+ const effectiveScore = isWellPositioned ? detection.score * 1.2 : detection.score;
1667
+ if (effectiveScore > captureState.bestScore) {
1668
+ this.stateManager.updateCaptureState({ bestScore: effectiveScore });
955
1669
  }
956
- }
1670
+ });
957
1671
  }
958
- // OPTIMIZATION 3: Adaptive frame rate based on detection success
959
- if (finalBoxes.length === 0) {
1672
+ // Update document detection state
1673
+ this.hasDocumentDetected = detections.length > 0;
1674
+ // Adaptive frame rate
1675
+ if (detections.length === 0) {
960
1676
  this.consecutiveFailures++;
961
1677
  }
962
1678
  else {
963
1679
  this.consecutiveFailures = 0;
964
1680
  }
965
- ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
1681
+ // Update detection boxes for debug
1682
+ if (this.debug) {
1683
+ this.updateDetectionBoxes(detections);
1684
+ }
1685
+ else {
1686
+ this.detectionBoxes = [];
1687
+ }
1688
+ this.updateMaskColor(detections);
1689
+ // Record frame processing metrics
966
1690
  if (this.debug) {
967
- this.drawDetections(ctx, finalBoxes);
1691
+ const frameEndTime = performance.now();
1692
+ const totalFrameTime = frameEndTime - frameStartTime;
1693
+ this.recordFrameProcessing(totalFrameTime, detections.length);
968
1694
  }
969
- this.updateGuidanceStatus(finalBoxes);
970
- this.updateMaskColor(finalBoxes);
971
- // Solo continuar si no hemos completado el proceso
972
- if (this.captureStep !== 'completed') {
973
- // OPTIMIZATION 4: Reduce frame rate when no detection for better battery life
1695
+ // Continue detection loop
1696
+ if (captureState.step !== 'completed') {
974
1697
  if (this.consecutiveFailures > this.MAX_FAILURES) {
975
- // Reduce to ~5fps when no detection for 0.5 seconds
976
1698
  setTimeout(() => this.detectFrame(), 200);
977
1699
  }
978
1700
  else {
@@ -981,102 +1703,97 @@ const JaakStamps = class {
981
1703
  }
982
1704
  }
983
1705
  catch (e) {
984
- this.debugLog("Error en inferencia:", e);
985
- // Solo continuar si no hemos completado el proceso
986
- if (this.captureStep !== 'completed') {
987
- // On error, wait longer before retrying
1706
+ this.logger.error('Error en inferencia de modelo:', e);
1707
+ const captureState = this.stateManager.getCaptureState();
1708
+ if (captureState.step !== 'completed') {
988
1709
  setTimeout(() => this.detectFrame(), 100);
989
1710
  }
990
1711
  }
991
1712
  }
992
- isCardInFrame(box) {
993
- const cardCenterX = box.x + box.w / 2;
994
- const cardCenterY = box.y + box.h / 2;
995
- const frameCenterX = this.INPUT_SIZE / 2;
996
- const frameCenterY = this.INPUT_SIZE / 2;
997
- const toleranceX = 40;
998
- const toleranceY = 30;
999
- const isCentered = Math.abs(cardCenterX - frameCenterX) < toleranceX &&
1000
- Math.abs(cardCenterY - frameCenterY) < toleranceY;
1001
- const isGoodSize = box.w > 150 && box.w < 300 && box.h > 90 && box.h < 200;
1002
- return isCentered && isGoodSize;
1713
+ // ... (continuing with remaining methods)
1714
+ // Due to length constraints, I'll provide the key architectural changes
1715
+ disconnectedCallback() {
1716
+ this.cleanup();
1003
1717
  }
1004
- checkSideAlignment(box) {
1005
- if (!this.videoRef)
1006
- return { top: false, right: false, bottom: false, left: false };
1007
- // Get video dimensions to calculate actual mask boundaries in model space
1718
+ cleanup() {
1719
+ if (this.animationId) {
1720
+ cancelAnimationFrame(this.animationId);
1721
+ }
1722
+ if (this.videoStream) {
1723
+ this.videoStream.getTracks().forEach(track => track.stop());
1724
+ }
1725
+ if (this.alignmentTimer) {
1726
+ clearTimeout(this.alignmentTimer);
1727
+ this.alignmentTimer = undefined;
1728
+ }
1729
+ if (this.performanceUpdateInterval) {
1730
+ clearInterval(this.performanceUpdateInterval);
1731
+ this.performanceUpdateInterval = undefined;
1732
+ }
1733
+ this.detectionBoxes = [];
1734
+ this.alignmentStartTime = undefined;
1735
+ this.hasDocumentDetected = false;
1736
+ this.serviceContainer?.cleanup();
1737
+ }
1738
+ render() {
1739
+ const captureState = this.stateManager?.getCaptureState() || {
1740
+ isVideoActive: false,
1741
+ showFlipAnimation: false,
1742
+ showSuccessAnimation: false,
1743
+ step: 'front',
1744
+ isCapturing: false
1745
+ };
1746
+ const cameraInfo = this.cameraService?.getCameraInfo() || {
1747
+ availableCameras: [],
1748
+ selectedCameraId: null,
1749
+ deviceType: 'desktop'};
1750
+ return (index.h("div", { key: '7af79a0ff25b51790a9477cd7b338a0584172fc2', class: "detector-container" }, index.h("div", { key: 'ebf6a3811e0e599f29e98325b975a645e3bfb5e0', class: "video-container" }, index.h("video", { key: '5208fc9574fa78b1149be5839bc26d04bf9bcdfc', ref: el => this.videoRef = el, autoplay: true, muted: true, playsinline: true, class: this.shouldMirrorVideo ? 'mirror' : '', style: { display: captureState.isVideoActive ? 'block' : 'none' } }), index.h("div", { key: 'b507c786eccbd21acdd884ef50bc6ec280b9d437', ref: el => this.detectionContainer = el, class: `detection-overlay ${this.shouldMirrorVideo ? 'mirror' : ''}` }, this.debug && this.detectionBoxes.map((box, index$1) => (index.h("div", { key: index$1, class: "detection-box", style: {
1751
+ position: 'absolute',
1752
+ left: `${box.x}px`,
1753
+ top: `${box.y}px`,
1754
+ width: `${box.w}px`,
1755
+ height: `${box.h}px`,
1756
+ border: '2px solid #32406C',
1757
+ pointerEvents: 'none',
1758
+ boxSizing: 'border-box'
1759
+ } })))), this.isMaskReady && (index.h("div", { key: '53066c626b23daae351ea9a80409e8882434b0dd', class: "overlay-mask" }, index.h("div", { key: '77bb4048d43e328e57a5c7e1909e0a59c8957217', class: "card-outline" }, index.h("div", { key: 'ea0f2610d903f985286856ab69f8be24fd42148e', class: "side side-top" }), index.h("div", { key: 'dc671111ef4adf33aa41f4457fdf344ede23eb80', class: "side side-right" }), index.h("div", { key: '2475ec41577dca92b425542c8861c570ed7ecd3b', class: "side side-bottom" }), index.h("div", { key: 'a06171c8eb1bd6353a6464485604560d73ac04b7', class: "side side-left" }), !captureState.showFlipAnimation && !captureState.showSuccessAnimation && (index.h("div", { key: 'ecfd98f36d457fe7282b26f6a0efef5361380c76', class: "guide-text" }, "Alinee su identificaci\u00F3n con el marco"))), captureState.step === 'back' && !captureState.showFlipAnimation && !captureState.showSuccessAnimation && (index.h("button", { key: 'f3c7b66500110437e9e4a7442cb327f2fdc6d71f', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")), captureState.isVideoActive && (index.h("div", { key: 'b5b2a8dfc6dbcf381c32c4caa562c27ced2e3e56', class: "camera-controls" }, index.h("button", { key: '6b40d4649dfa22c5ea8ca90cacce35cd0ca53ff3', class: `camera-selector-button ${this.isSwitchingCamera ? 'loading' : ''}`, onClick: () => this.toggleCameraSelector(), type: "button", title: "Seleccionar c\u00E1mara", disabled: this.isSwitchingCamera }, this.isSwitchingCamera ? (index.h("div", { class: "button-spinner" })) : ('Cámaras')))), this.showCameraSelector && cameraInfo.availableCameras.length > 0 && (index.h("div", { key: '41feec90287510b08bd1090ad15586b323007c30', class: "camera-selector-dropdown" }, index.h("div", { key: '8310ebe3db842c463ad428b973f841053315a76f', class: "camera-selector-header" }, index.h("span", { key: '6693bdfa33643dfe73798d4f25b0c2d9de7aac7c' }, "Seleccionar C\u00E1mara"), index.h("button", { key: '8552d45e1482c570d7ff85588d4404eec7c369d7', class: "close-selector", onClick: () => this.toggleCameraSelector(), type: "button" }, "\u00D7")), index.h("div", { key: '5333ec0e5fb2c50a07a7c0b7d4dfb1bb4ee0df1c', class: "camera-list" }, cameraInfo.availableCameras.map((camera) => (index.h("button", { key: camera.id, class: `camera-option ${cameraInfo.selectedCameraId === camera.id ? 'selected' : ''}`, onClick: () => this.handleCameraSwitch(camera.id), type: "button" }, index.h("span", { class: "camera-label" }, camera.label || `Cámara ${cameraInfo.availableCameras.indexOf(camera) + 1}`), cameraInfo.selectedCameraId === camera.id && (index.h("span", { class: "selected-indicator" }, "\u2713")))))), index.h("div", { key: '8adf70b0e632c56a4784dec44621688809a3ff56', class: "device-info" }, index.h("small", { key: '2ea23922386ecda4a9011b50faba5efe4b4e60bb' }, "Dispositivo: ", cameraInfo.deviceType)))))), captureState.isCapturing && (index.h("div", { key: '8e693db67fe1e6ae8f11082b8993682b6d19b11d', class: "capture-animation" })), captureState.showFlipAnimation && (index.h("div", { key: '474489ed7848cdc163c492a5e19f5f13231e17b3', class: "flip-animation" }, index.h("div", { key: 'a9bd24ca21330882f001b7811077630eb1c30f50', class: "id-card-icon" }), index.h("div", { key: 'ffadb660a61e0f5e3e29bdc473d987e87dc4ad8a', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), captureState.showSuccessAnimation && (index.h("div", { key: 'd2522ee33aa159d49f040a293775892fb1cb81b5', class: "success-animation" }, index.h("div", { key: 'e7f899fac58bc9a3d51cf2cb89ee33bb320b241f', class: "check-icon" }), index.h("div", { key: 'd5d0ee1f37dbc659ca625ad03cbce325be0cf0a6', class: "success-text" }, "\u00A1Proceso completado!"))), index.h("div", { key: '425d347666032c3982a660ebee13b47670b996cb', class: `component-status status-${this.currentStatus.type}` }, (this.currentStatus.type === 'loading' || this.currentStatus.type === 'initializing') && (index.h("div", { key: '4d396fa107872f9a1e526fd59dc4edf279a05792', class: "status-spinner" })), index.h("div", { key: '232e9ae24c8cf5ef8ac0e3442e45a920799c724d', class: "status-content" }, index.h("div", { key: 'fe9dc0ca6d8e8276052bac7d2d44f1c7c9730364', class: "status-message" }, this.currentStatus.message), this.currentStatus.description && (index.h("div", { key: '6910c7ac78fd89e6fa1165446ec6d46fb356035c', class: "status-description" }, this.currentStatus.description)))), this.debug && (index.h("div", { key: '7282b8afaf03da53b01a23d04babd772528c3c14', class: "performance-monitor" }, index.h("div", { key: 'b582b3124fed13387cd70a02a34ab2bb541f3bfc', class: "performance-expanded" }, index.h("div", { key: '764bac2d61224b9a5f306f50934d410e1bd27787', class: "metrics-row" }, index.h("div", { key: '261563f8314a9f6069b1ac6362eb9c38936a9dc7', class: "metric-compact" }, index.h("span", { key: '4feea98eff86620c1bc90eb65d9799102423109d', class: "metric-label" }, "FPS"), index.h("span", { key: 'eb15f13b27b8aa50701ad3d11c4cf87200010b67', class: `metric-value ${this.performanceData.fps < 15 ? 'warning' : this.performanceData.fps < 10 ? 'danger' : 'good'}` }, this.performanceData.fps)), index.h("div", { key: '0813c35c2c33286f2276bfb5adce59b32c7bb597', class: "metric-compact" }, index.h("span", { key: '201e7bcb556e63b141e42a3ffc3419eb4284bfa8', class: "metric-label" }, "MEM"), index.h("span", { key: '4f6703cbe0128440d0f2f22f631035ab85422c64', class: `metric-value ${this.performanceData.memoryUsage > 100 ? 'warning' : this.performanceData.memoryUsage > 200 ? 'danger' : 'good'}` }, this.performanceData.memoryUsage, "MB"))), index.h("div", { key: '6343c361c93138b9ea66e8ae8acd361b93333f8c', class: "metrics-row" }, index.h("div", { key: 'd3c81fe597004bf380fae2d32f3a8314317e7769', class: "metric-compact" }, index.h("span", { key: 'fce572af3e200a611974dceef4da02f6aecedffc', class: "metric-label" }, "INF"), index.h("span", { key: '18dd78d54dcecfb70ddf59b782f87f8c6f208b0f', class: `metric-value ${this.performanceData.inferenceTime > 100 ? 'warning' : this.performanceData.inferenceTime > 200 ? 'danger' : 'good'}` }, this.performanceData.inferenceTime, "ms")), index.h("div", { key: '4c31ebfd835b017fd3e41b23d6bd9b19add511aa', class: "metric-compact" }, index.h("span", { key: '66b1a380b9479a8fc1e8c2385cb72aa4158dc74e', class: "metric-label" }, "FRAME"), index.h("span", { key: '3c6e41f7f11123c524d3a9df409345929d63f352', class: `metric-value ${this.performanceData.frameProcessingTime > 50 ? 'warning' : this.performanceData.frameProcessingTime > 100 ? 'danger' : 'good'}` }, this.performanceData.frameProcessingTime, "ms"))), index.h("div", { key: '3b522e2cdfe4bd9f1dd6eb0f91ee3577dc43e490', class: "metrics-row" }, index.h("div", { key: 'fa1e6f687b43aa2582b8b3426feb03a16c6493fc', class: "metric-compact" }, index.h("span", { key: 'a9355091e71a33a6a0d7cc6c11171dcda2e51b22', class: "metric-label" }, "DET"), index.h("span", { key: 'beca5a7ccf4853675cf8366bcf577ebfbd46c4f0', class: "metric-value good" }, this.performanceData.successfulDetections, "/", this.performanceData.totalDetections)), index.h("div", { key: '4b07fc9b3d35f99bc6e77c8726192cde0476a787', class: "metric-compact" }, index.h("span", { key: 'a1674b538f45328ee0afb00e582c07e0b4ccf553', class: "metric-label" }, "RATE"), index.h("span", { key: 'fd384a5137bc3df6c939d3d698a3ef80e9087030', class: `metric-value ${this.performanceData.detectionRate < 30 ? 'danger' : this.performanceData.detectionRate < 60 ? 'warning' : 'good'}` }, this.performanceData.detectionRate, "%")))))), index.h("div", { key: 'ebbaf15a0ad96e4da5bbf746c32d7a4abb51b973', class: "watermark" }, index.h("img", { key: '8e7d274b529d1f7020ec4a7225579792763f871a', src: "https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png", alt: "Powered by Jaak" })))));
1760
+ }
1761
+ // Utility methods
1762
+ updateDetectionBoxes(boxes) {
1763
+ if (!this.videoRef || !this.detectionContainer)
1764
+ return;
1008
1765
  const videoWidth = this.videoRef.videoWidth;
1009
1766
  const videoHeight = this.videoRef.videoHeight;
1010
- if (videoWidth === 0 || videoHeight === 0) {
1011
- return { top: false, right: false, bottom: false, left: false };
1012
- }
1013
- // Calculate video aspect ratio
1767
+ const container = this.detectionContainer.parentElement;
1768
+ const containerRect = container.getBoundingClientRect();
1769
+ const containerWidth = containerRect.width;
1770
+ const containerHeight = containerRect.height;
1771
+ if (videoWidth === 0 || videoHeight === 0)
1772
+ return;
1014
1773
  const videoAspectRatio = videoWidth / videoHeight;
1015
- // The model sees video stretched to 320x320, but we need to calculate where
1016
- // the mask should be in this distorted space to match the visual mask
1017
- // In the visual display, we calculate mask size based on the limiting dimension
1018
- // We need to replicate this logic but account for the distortion in model space
1019
- // Calculate the "display" dimensions (what the visual mask calculations use)
1020
- const containerAspectRatio = 1; // Assume square container for simplicity
1774
+ const containerAspectRatio = containerWidth / containerHeight;
1021
1775
  let displayedVideoWidth, displayedVideoHeight;
1776
+ let videoOffsetX = 0, videoOffsetY = 0;
1022
1777
  if (videoAspectRatio > containerAspectRatio) {
1023
- // Video is wider - letterboxed in display
1024
- displayedVideoWidth = this.INPUT_SIZE;
1025
- displayedVideoHeight = this.INPUT_SIZE / videoAspectRatio;
1026
- }
1027
- else {
1028
- // Video is taller - pillarboxed in display
1029
- displayedVideoHeight = this.INPUT_SIZE;
1030
- displayedVideoWidth = this.INPUT_SIZE * videoAspectRatio;
1031
- }
1032
- // Calculate mask dimensions using the same logic as updateMaskDimensions
1033
- const maxWidthByHeight = displayedVideoHeight * this.ID1_ASPECT_RATIO;
1034
- let visualMaskWidth, visualMaskHeight;
1035
- const sizeRatio = this.maskSize / 100;
1036
- if (maxWidthByHeight <= displayedVideoWidth) {
1037
- // Video height is the limiting factor
1038
- visualMaskHeight = displayedVideoHeight * sizeRatio;
1039
- visualMaskWidth = visualMaskHeight * this.ID1_ASPECT_RATIO;
1778
+ displayedVideoWidth = containerWidth;
1779
+ displayedVideoHeight = containerWidth / videoAspectRatio;
1780
+ videoOffsetY = (containerHeight - displayedVideoHeight) / 2;
1040
1781
  }
1041
1782
  else {
1042
- // Video width is the limiting factor
1043
- visualMaskWidth = displayedVideoWidth * sizeRatio;
1044
- visualMaskHeight = visualMaskWidth / this.ID1_ASPECT_RATIO;
1045
- }
1046
- // Now map these visual mask dimensions to the distorted model space
1047
- // The model stretches video to 320x320, so we need to apply the inverse transformation
1048
- const modelMaskWidth = visualMaskWidth * (this.INPUT_SIZE / displayedVideoWidth);
1049
- const modelMaskHeight = visualMaskHeight * (this.INPUT_SIZE / displayedVideoHeight);
1050
- // Calculate mask boundaries in model coordinate system (always centered in 320x320)
1051
- const maskCenterX = this.INPUT_SIZE / 2;
1052
- const maskCenterY = this.INPUT_SIZE / 2;
1053
- const maskLeft = maskCenterX - (modelMaskWidth / 2);
1054
- const maskRight = maskCenterX + (modelMaskWidth / 2);
1055
- const maskTop = maskCenterY - (modelMaskHeight / 2);
1056
- const maskBottom = maskCenterY + (modelMaskHeight / 2);
1057
- // Obtener las coordenadas del documento detectado
1058
- let docLeft = box.x;
1059
- let docRight = box.x + box.w;
1060
- const docTop = box.y;
1061
- const docBottom = box.y + box.h;
1062
- // Si el video está en modo mirror, invertir las coordenadas horizontales
1063
- if (this.shouldMirrorVideo) {
1064
- const originalDocLeft = docLeft;
1065
- const originalDocRight = docRight;
1066
- docLeft = this.INPUT_SIZE - originalDocRight;
1067
- docRight = this.INPUT_SIZE - originalDocLeft;
1783
+ displayedVideoHeight = containerHeight;
1784
+ displayedVideoWidth = containerHeight * videoAspectRatio;
1785
+ videoOffsetX = (containerWidth - displayedVideoWidth) / 2;
1068
1786
  }
1069
- // Tolerancia para considerar que un lado está alineado (en píxeles)
1070
- const tolerance = this.alignmentTolerance;
1071
- return {
1072
- top: Math.abs(docTop - maskTop) <= tolerance,
1073
- right: Math.abs(docRight - maskRight) <= tolerance,
1074
- bottom: Math.abs(docBottom - maskBottom) <= tolerance,
1075
- left: Math.abs(docLeft - maskLeft) <= tolerance
1076
- };
1077
- }
1078
- areAllSidesAligned(alignment) {
1079
- return alignment.top && alignment.right && alignment.bottom && alignment.left;
1787
+ const INPUT_SIZE = 320;
1788
+ const scaleX = displayedVideoWidth / INPUT_SIZE;
1789
+ const scaleY = displayedVideoHeight / INPUT_SIZE;
1790
+ this.detectionBoxes = boxes.map(det => ({
1791
+ x: det.x * scaleX + videoOffsetX,
1792
+ y: det.y * scaleY + videoOffsetY,
1793
+ w: det.w * scaleX,
1794
+ h: det.h * scaleY,
1795
+ score: det.score
1796
+ }));
1080
1797
  }
1081
1798
  updateMaskColor(boxes) {
1082
1799
  const cardOutline = this.el.shadowRoot?.querySelector('.card-outline');
@@ -1089,310 +1806,327 @@ const JaakStamps = class {
1089
1806
  let currentAlignment = { top: false, right: false, bottom: false, left: false };
1090
1807
  if (boxes.length > 0) {
1091
1808
  bestBox = boxes.reduce((best, current) => current.score > best.score ? current : best);
1092
- currentAlignment = this.checkSideAlignment(bestBox);
1809
+ const maskConfig = {
1810
+ INPUT_SIZE: 320,
1811
+ ID1_ASPECT_RATIO: 85.60 / 53.98,
1812
+ shouldMirrorVideo: this.shouldMirrorVideo,
1813
+ alignmentTolerance: this.alignmentTolerance,
1814
+ maskSize: this.maskSize,
1815
+ videoRef: this.videoRef
1816
+ };
1817
+ currentAlignment = this.detectionService.checkSideAlignment(bestBox, maskConfig);
1093
1818
  this.sideAlignment = currentAlignment;
1094
1819
  }
1095
1820
  else {
1096
- // Reset alignment when no detection
1097
1821
  this.sideAlignment = { top: false, right: false, bottom: false, left: false };
1098
1822
  }
1099
- // Actualizar colores de cada lado individualmente
1100
1823
  topSide?.classList.toggle('aligned', currentAlignment.top);
1101
1824
  rightSide?.classList.toggle('aligned', currentAlignment.right);
1102
1825
  bottomSide?.classList.toggle('aligned', currentAlignment.bottom);
1103
1826
  leftSide?.classList.toggle('aligned', currentAlignment.left);
1104
- // Verificar si todos los lados están alineados
1105
- const allSidesAligned = this.areAllSidesAligned(currentAlignment);
1827
+ const allSidesAligned = this.detectionService.areAllSidesAligned(currentAlignment);
1106
1828
  if (allSidesAligned && bestBox) {
1107
1829
  cardOutline?.classList.add('perfect-match');
1108
1830
  corners?.forEach(corner => corner.classList.add('perfect-match'));
1831
+ // Debug logging
1832
+ this.logger.state('CAPTURE_EVALUATION', {
1833
+ allSidesAligned: true,
1834
+ hasScreenshotTaken: this.hasScreenshotTaken,
1835
+ captureDelay: this.captureDelay,
1836
+ alignmentStartTime: this.alignmentStartTime
1837
+ });
1109
1838
  if (!this.hasScreenshotTaken) {
1110
- this.lastDetectedBox = bestBox;
1111
- this.takeScreenshot().catch(error => {
1112
- this.debugLog('❌ Error taking screenshot:', error);
1839
+ const currentTime = Date.now();
1840
+ // Initialize alignment start time if not set
1841
+ if (!this.alignmentStartTime) {
1842
+ this.alignmentStartTime = currentTime;
1843
+ this.logger.state('ALIGNMENT_TIMER_STARTED', { startTime: currentTime });
1844
+ }
1845
+ // Check if document has been aligned for the configured delay
1846
+ const alignmentDuration = currentTime - this.alignmentStartTime;
1847
+ this.logger.state('ALIGNMENT_DURATION_CHECK', {
1848
+ alignmentDuration,
1849
+ captureDelay: this.captureDelay,
1850
+ readyToCapture: alignmentDuration >= this.captureDelay
1113
1851
  });
1114
- this.hasScreenshotTaken = true;
1115
- // Reset para permitir segunda captura
1116
- setTimeout(() => {
1117
- this.hasScreenshotTaken = false;
1118
- }, 2000);
1852
+ if (alignmentDuration >= this.captureDelay) {
1853
+ this.logger.state('TRIGGERING_CAPTURE', {
1854
+ alignmentDuration,
1855
+ captureDelay: this.captureDelay
1856
+ });
1857
+ this.lastDetectedBox = bestBox;
1858
+ this.takeScreenshot().catch(error => {
1859
+ this.logger.error('Error al tomar captura de pantalla:', error);
1860
+ });
1861
+ this.hasScreenshotTaken = true;
1862
+ this.alignmentStartTime = undefined;
1863
+ setTimeout(() => {
1864
+ this.hasScreenshotTaken = false;
1865
+ }, 2000);
1866
+ }
1119
1867
  }
1120
1868
  }
1121
1869
  else {
1122
1870
  cardOutline?.classList.remove('perfect-match');
1123
1871
  corners?.forEach(corner => corner.classList.remove('perfect-match'));
1124
- }
1125
- }
1126
- updateGuidanceStatus(boxes) {
1127
- if (boxes.length === 0) {
1128
- this.statusMessage = "Posicione la identificación dentro del marco";
1129
- this.statusColor = "#ff6b6b";
1130
- }
1131
- else {
1132
- const bestBox = boxes.reduce((best, current) => current.score > best.score ? current : best);
1133
- const alignment = this.checkSideAlignment(bestBox);
1134
- const alignedSides = [alignment.top, alignment.right, alignment.bottom, alignment.left].filter(Boolean).length;
1135
- const allSidesAligned = this.areAllSidesAligned(alignment);
1136
- if (allSidesAligned) {
1137
- this.statusMessage = "Identificación perfectamente alineada. Mantenga inmóvil";
1138
- this.statusColor = "#00ff00";
1872
+ // Reset alignment timer when document moves out of position
1873
+ if (this.alignmentStartTime) {
1874
+ this.alignmentStartTime = undefined;
1139
1875
  }
1140
- else if (alignedSides > 0) {
1141
- this.statusMessage = `Alinee los lados restantes (${alignedSides}/4 lados correctos)`;
1142
- this.statusColor = "#ffb366";
1876
+ if (this.alignmentTimer) {
1877
+ clearTimeout(this.alignmentTimer);
1878
+ this.alignmentTimer = undefined;
1143
1879
  }
1144
- else if (bestBox.w < 150) {
1145
- this.statusMessage = "Identificación detectada. Acerque al marco";
1146
- this.statusColor = "#ffb366";
1147
- }
1148
- else {
1149
- this.statusMessage = "Identificación detectada. Alinee con el marco";
1150
- this.statusColor = "#ffb366";
1151
- }
1152
- }
1153
- }
1154
- drawDetections(ctx, boxes) {
1155
- if (!this.videoRef)
1156
- return;
1157
- // Get video and container dimensions
1158
- const videoWidth = this.videoRef.videoWidth;
1159
- const videoHeight = this.videoRef.videoHeight;
1160
- const containerWidth = this.canvasRef.width;
1161
- const containerHeight = this.canvasRef.height;
1162
- if (videoWidth === 0 || videoHeight === 0)
1163
- return;
1164
- // Calculate video aspect ratio and container aspect ratio
1165
- const videoAspectRatio = videoWidth / videoHeight;
1166
- const containerAspectRatio = containerWidth / containerHeight;
1167
- // Determine how video fits in container (same logic as updateMaskDimensions)
1168
- let displayedVideoWidth, displayedVideoHeight;
1169
- let videoOffsetX = 0, videoOffsetY = 0;
1170
- if (videoAspectRatio > containerAspectRatio) {
1171
- // Video is wider - letterboxed (black bars top/bottom)
1172
- displayedVideoWidth = containerWidth;
1173
- displayedVideoHeight = containerWidth / videoAspectRatio;
1174
- videoOffsetY = (containerHeight - displayedVideoHeight) / 2;
1175
1880
  }
1176
- else {
1177
- // Video is taller - pillarboxed (black bars left/right)
1178
- displayedVideoHeight = containerHeight;
1179
- displayedVideoWidth = containerHeight * videoAspectRatio;
1180
- videoOffsetX = (containerWidth - displayedVideoWidth) / 2;
1181
- }
1182
- // Scale factor from model coordinates (320x320) to displayed video area
1183
- const scaleX = displayedVideoWidth / this.INPUT_SIZE;
1184
- const scaleY = displayedVideoHeight / this.INPUT_SIZE;
1185
- boxes.forEach(det => {
1186
- // Convert model coordinates to displayed video coordinates
1187
- const x = det.x * scaleX + videoOffsetX;
1188
- const y = det.y * scaleY + videoOffsetY;
1189
- const w = det.w * scaleX;
1190
- const h = det.h * scaleY;
1191
- ctx.strokeStyle = "#32406C";
1192
- ctx.lineWidth = 2;
1193
- ctx.strokeRect(x, y, w, h);
1194
- });
1195
1881
  }
1196
1882
  async takeScreenshot() {
1197
1883
  if (!this.videoRef || !this.lastDetectedBox)
1198
1884
  return;
1199
- // Activar animación
1885
+ this.logger.state('INICIANDO_CAPTURA', {
1886
+ captureStep: this.stateManager.getCaptureState().step,
1887
+ detectedBox: this.lastDetectedBox,
1888
+ videoResolution: {
1889
+ width: this.videoRef.videoWidth,
1890
+ height: this.videoRef.videoHeight
1891
+ }
1892
+ });
1893
+ this.stateManager.updateCaptureState({ isCapturing: true });
1200
1894
  this.triggerCaptureAnimation();
1201
- // OPTIMIZATION: Reuse capture canvas for full frame
1202
- if (!this.captureCanvas || !this.captureCtx) {
1203
- this.initializeCanvasPool();
1204
- }
1205
- // Resize reused canvas for full frame
1206
- this.captureCanvas.width = this.videoRef.videoWidth;
1207
- this.captureCanvas.height = this.videoRef.videoHeight;
1208
- this.captureCtx.drawImage(this.videoRef, 0, 0, this.captureCanvas.width, this.captureCanvas.height);
1209
- // Calcular las coordenadas de recorte basadas en la detección
1210
- const scaleX = this.videoRef.videoWidth / this.INPUT_SIZE;
1211
- const scaleY = this.videoRef.videoHeight / this.INPUT_SIZE;
1895
+ // Create capture canvas
1896
+ const captureCanvas = document.createElement('canvas');
1897
+ captureCanvas.width = this.videoRef.videoWidth;
1898
+ captureCanvas.height = this.videoRef.videoHeight;
1899
+ const captureCtx = captureCanvas.getContext('2d', { alpha: false });
1900
+ captureCtx.drawImage(this.videoRef, 0, 0, captureCanvas.width, captureCanvas.height);
1901
+ // Calculate crop coordinates
1902
+ const INPUT_SIZE = 320;
1903
+ const scaleX = this.videoRef.videoWidth / INPUT_SIZE;
1904
+ const scaleY = this.videoRef.videoHeight / INPUT_SIZE;
1212
1905
  const cropX = Math.max(0, (this.lastDetectedBox.x * scaleX) - this.cropMargin);
1213
1906
  const cropY = Math.max(0, (this.lastDetectedBox.y * scaleY) - this.cropMargin);
1214
1907
  const cropWidth = Math.min((this.lastDetectedBox.w * scaleX) + (2 * this.cropMargin), this.videoRef.videoWidth - cropX);
1215
1908
  const cropHeight = Math.min((this.lastDetectedBox.h * scaleY) + (2 * this.cropMargin), this.videoRef.videoHeight - cropY);
1216
- // OPTIMIZATION: Create temporary canvas only for cropped version
1217
- // (We reuse main capture canvas for full frame)
1909
+ // Create cropped version
1218
1910
  const croppedCanvas = document.createElement('canvas');
1219
1911
  croppedCanvas.width = cropWidth;
1220
1912
  croppedCanvas.height = cropHeight;
1221
1913
  const croppedCtx = croppedCanvas.getContext('2d', { alpha: false });
1222
- // Recortar la identificación del frame completo
1223
- croppedCtx.drawImage(this.videoRef, cropX, cropY, cropWidth, cropHeight, // Área de origen
1224
- 0, 0, cropWidth, cropHeight // Área de destino
1225
- );
1226
- if (this.captureStep === 'front') {
1227
- // Captura del frente usando canvas reutilizado
1228
- this.capturedFullFrame = this.captureCanvas.toDataURL('image/png');
1229
- this.capturedCroppedId = croppedCanvas.toDataURL('image/png');
1914
+ croppedCtx.drawImage(this.videoRef, cropX, cropY, cropWidth, cropHeight, 0, 0, cropWidth, cropHeight);
1915
+ const captureState = this.stateManager.getCaptureState();
1916
+ if (captureState.step === 'front') {
1917
+ this.stateManager.setCapturedImages({
1918
+ front: {
1919
+ fullFrame: captureCanvas.toDataURL('image/png'),
1920
+ cropped: croppedCanvas.toDataURL('image/png')
1921
+ }
1922
+ });
1230
1923
  // Check if document classification is enabled
1231
1924
  if (this.useDocumentClassification) {
1232
- // Load MobileNet model if not loaded yet (lazy loading)
1233
- if (!this.mobileNetSession) {
1234
- try {
1235
- await this.loadMobileNetModel();
1236
- }
1237
- catch (error) {
1238
- this.debugLog('⚠️ Failed to load classification model, continuing without classification:', error);
1239
- }
1240
- }
1241
- // Classify the cropped document if model is available
1242
- if (this.mobileNetSession) {
1243
- const classification = await this.classifyDocument(croppedCanvas);
1244
- if (classification && classification.class === 'passport') {
1245
- // If it's a passport, skip back capture since passports don't have a back side
1246
- this.debugLog('📄 Passport detected - skipping back capture');
1247
- this.completeProcess(true);
1248
- return;
1249
- }
1925
+ const classification = await this.detectionService.classifyDocument(croppedCanvas);
1926
+ if (classification && classification.class === 'passport') {
1927
+ this.logger.state('PASAPORTE_DETECTADO_SALTANDO_REVERSO', { classification: classification?.class });
1928
+ this.completeProcess(true);
1929
+ return;
1250
1930
  }
1251
1931
  }
1252
- // For other IDs, continue with normal flow (back capture)
1253
- this.captureStep = 'back';
1254
- this.statusMessage = "Voltee la identificación y muestre la parte trasera";
1255
- this.statusColor = "#007bff";
1256
- // Pausar detección durante la animación de giro
1257
- this.isDetectionPaused = true;
1258
- // Mostrar animación de giro después de la captura
1932
+ this.stateManager.updateCaptureState({
1933
+ step: 'back',
1934
+ isDetectionPaused: true,
1935
+ showFlipAnimation: true
1936
+ });
1259
1937
  setTimeout(() => {
1260
- this.showFlipAnimation = true;
1261
- setTimeout(() => {
1262
- this.showFlipAnimation = false;
1263
- // Reanudar detección después de que termine la animación
1264
- this.isDetectionPaused = false;
1265
- }, 3000);
1266
- }, 800);
1267
- this.debugLog('📸 FRENTE capturado. Esperando trasera...');
1268
- }
1269
- else if (this.captureStep === 'back') {
1270
- // Captura de la trasera usando canvas reutilizado
1271
- this.capturedBackFullFrame = this.captureCanvas.toDataURL('image/png');
1272
- this.capturedBackCroppedId = croppedCanvas.toDataURL('image/png');
1938
+ this.stateManager.updateCaptureState({
1939
+ showFlipAnimation: false,
1940
+ isDetectionPaused: false
1941
+ });
1942
+ }, 3000);
1943
+ }
1944
+ else if (captureState.step === 'back') {
1945
+ this.stateManager.setCapturedImages({
1946
+ back: {
1947
+ fullFrame: captureCanvas.toDataURL('image/png'),
1948
+ cropped: croppedCanvas.toDataURL('image/png')
1949
+ }
1950
+ });
1273
1951
  this.completeProcess(false);
1274
- this.debugLog('📸 TRASERA capturada. Proceso completado. Detector detenido. Imágenes emitidas.');
1275
1952
  }
1276
1953
  }
1277
1954
  triggerCaptureAnimation() {
1278
- this.isCapturing = true;
1279
- // Agregar clase de animación al marco
1280
1955
  const cardOutline = this.el.shadowRoot?.querySelector('.card-outline');
1281
1956
  cardOutline?.classList.add('capturing');
1282
- // Limpiar animación después de que termine
1283
1957
  setTimeout(() => {
1284
- this.isCapturing = false;
1958
+ this.stateManager.updateCaptureState({ isCapturing: false });
1285
1959
  cardOutline?.classList.remove('capturing');
1286
1960
  }, 600);
1287
1961
  }
1962
+ completeProcess(skippedBack = false) {
1963
+ this.stateManager.updateCaptureState({
1964
+ step: 'completed',
1965
+ showSuccessAnimation: true
1966
+ });
1967
+ const capturedImages = this.stateManager.getCapturedImages();
1968
+ capturedImages.metadata.processCompleted = true;
1969
+ capturedImages.metadata.backCaptureSkipped = skippedBack;
1970
+ this.stateManager.setCapturedImages(capturedImages);
1971
+ this.stopDetection();
1972
+ this.updateStatus('Proceso completado', `${capturedImages.metadata.totalImages} imágenes capturadas exitosamente`, 'ready');
1973
+ const finalImages = {
1974
+ ...capturedImages,
1975
+ timestamp: new Date().toISOString()
1976
+ };
1977
+ this.captureCompleted.emit(finalImages);
1978
+ setTimeout(() => {
1979
+ this.stateManager.updateCaptureState({ showSuccessAnimation: false });
1980
+ }, 3000);
1981
+ this.logger.state('PROCESO_COMPLETADO', {
1982
+ skippedBack,
1983
+ totalImages: capturedImages.metadata.totalImages,
1984
+ timestamp: new Date().toISOString()
1985
+ });
1986
+ }
1288
1987
  stopDetection() {
1289
1988
  if (this.animationId) {
1290
1989
  cancelAnimationFrame(this.animationId);
1291
1990
  this.animationId = undefined;
1292
1991
  }
1293
- // Limpiar canvas para eliminar cualquier detección visual residual
1294
- if (this.canvasRef) {
1295
- const ctx = this.canvasRef.getContext("2d");
1296
- ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
1992
+ this.detectionBoxes = [];
1993
+ this.logger.state('DETECTOR_DETENIDO', { timestamp: Date.now() });
1994
+ }
1995
+ toggleCameraSelector() {
1996
+ if (this.isSwitchingCamera)
1997
+ return; // Don't toggle if switching camera
1998
+ this.showCameraSelector = !this.showCameraSelector;
1999
+ }
2000
+ async handleCameraSwitch(cameraId) {
2001
+ if (this.isSwitchingCamera)
2002
+ return; // Prevent multiple simultaneous switches
2003
+ try {
2004
+ // Close the selector immediately when user selects a camera
2005
+ this.showCameraSelector = false;
2006
+ this.isSwitchingCamera = true;
2007
+ this.logger.state('INICIANDO_CAMBIO_CAMARA', {
2008
+ from: this.cameraService.getSelectedCameraId(),
2009
+ to: cameraId
2010
+ });
2011
+ // Stop current video stream
2012
+ if (this.videoStream) {
2013
+ this.videoStream.getTracks().forEach(track => track.stop());
2014
+ }
2015
+ // Switch camera in service
2016
+ await this.cameraService.switchCamera(cameraId);
2017
+ // Setup new camera stream
2018
+ const newStream = await this.cameraService.setupCamera();
2019
+ // Update video element
2020
+ await this.initializeVideoStream(newStream);
2021
+ this.logger.state('CAMBIO_CAMARA_EXITOSO', {
2022
+ newCameraId: cameraId,
2023
+ isRearCamera: this.cameraService.isRearCamera(newStream)
2024
+ });
2025
+ }
2026
+ catch (error) {
2027
+ this.logger.error('Error al cambiar cámara:', error);
2028
+ // Try to restore previous camera if switch failed
2029
+ try {
2030
+ const fallbackStream = await this.cameraService.setupCamera();
2031
+ await this.initializeVideoStream(fallbackStream);
2032
+ }
2033
+ catch (fallbackError) {
2034
+ this.logger.error('Error al restaurar cámara anterior:', fallbackError);
2035
+ this.updateStatus('Error al cambiar cámara', 'No se pudo completar el cambio de dispositivo', 'error');
2036
+ }
2037
+ }
2038
+ finally {
2039
+ this.isSwitchingCamera = false;
1297
2040
  }
1298
- this.debugLog('🛑 Detector de identificación detenido');
1299
2041
  }
1300
2042
  resetDetection() {
1301
- this.bestScore = 0;
1302
- this.startTime = Date.now();
1303
- this.statusMessage = "Sistema reiniciado. Posicione la identificación";
1304
- this.statusColor = "#aaa";
2043
+ const currentCaptureState = this.stateManager.getCaptureState();
2044
+ const wasVideoActive = currentCaptureState.isVideoActive;
2045
+ this.stateManager.reset();
2046
+ if (wasVideoActive) {
2047
+ this.stateManager.updateCaptureState({ isVideoActive: true });
2048
+ }
1305
2049
  this.hasScreenshotTaken = false;
1306
- this.capturedFullFrame = null;
1307
- this.capturedCroppedId = null;
1308
- this.capturedBackFullFrame = null;
1309
- this.capturedBackCroppedId = null;
1310
- this.captureStep = 'front';
1311
- this.isCapturing = false;
1312
- this.showFlipAnimation = false;
1313
- this.showSuccessAnimation = false;
1314
- this.isDetectionPaused = false;
1315
- this.isLoading = false;
1316
- this.lastDetectedBox = undefined;
1317
- this.isModelPreloaded = false;
1318
- // Reset performance counters
2050
+ this.startTime = Date.now();
1319
2051
  this.frameSkipCounter = 0;
1320
2052
  this.consecutiveFailures = 0;
1321
2053
  this.lastInferenceTime = 0;
1322
- if (this.canvasRef) {
1323
- const ctx = this.canvasRef.getContext("2d");
1324
- ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
1325
- }
1326
- // Reiniciar el detector si estaba funcionando
1327
- if (this.isVideoActive && this.session) {
2054
+ this.detectionBoxes = [];
2055
+ this.alignmentStartTime = undefined;
2056
+ this.hasDocumentDetected = false;
2057
+ if (this.alignmentTimer) {
2058
+ clearTimeout(this.alignmentTimer);
2059
+ this.alignmentTimer = undefined;
2060
+ }
2061
+ if (wasVideoActive && this.detectionService.isModelLoaded()) {
2062
+ this.updateStatus('Captura reiniciada', 'Buscando documento en el marco de captura', 'active');
1328
2063
  this.detectFrame();
1329
2064
  }
1330
- }
1331
- completeProcess(skippedBack = false) {
1332
- this.captureStep = 'completed';
1333
- this.statusMessage = skippedBack ?
1334
- "Proceso completado (solo frente capturado)" :
1335
- "Proceso de captura completado exitosamente";
1336
- this.statusColor = "#28a745";
1337
- // Detener el detector
1338
- this.stopDetection();
1339
- // Emitir evento con las imágenes capturadas
1340
- const capturedImages = {
1341
- front: {
1342
- fullFrame: this.capturedFullFrame,
1343
- cropped: this.capturedCroppedId
1344
- },
1345
- back: {
1346
- fullFrame: this.capturedBackFullFrame,
1347
- cropped: this.capturedBackCroppedId
1348
- },
1349
- timestamp: new Date().toISOString(),
1350
- metadata: {
1351
- totalImages: skippedBack ? 2 : 4,
1352
- processCompleted: true,
1353
- backCaptureSkipped: skippedBack
1354
- }
1355
- };
1356
- this.captureCompleted.emit(capturedImages);
1357
- // Mostrar animación de éxito después de la captura
1358
- setTimeout(() => {
1359
- this.showSuccessAnimation = true;
1360
- setTimeout(() => {
1361
- this.showSuccessAnimation = false;
1362
- }, 3000);
1363
- }, 800);
2065
+ else {
2066
+ this.updateStatus('Listo para capturar', '', 'ready');
2067
+ }
1364
2068
  }
1365
2069
  exitSession() {
1366
2070
  if (this.videoStream) {
1367
2071
  this.videoStream.getTracks().forEach(track => track.stop());
1368
2072
  this.videoStream = undefined;
1369
- this.isVideoActive = false;
1370
- this.statusMessage = "Sesión finalizada.";
1371
- this.statusColor = "#aaa";
1372
- }
1373
- this.isLoading = false;
1374
- // Limpiar canvas al finalizar sesión
1375
- if (this.canvasRef) {
1376
- const ctx = this.canvasRef.getContext("2d");
1377
- ctx.clearRect(0, 0, this.canvasRef.width, this.canvasRef.height);
2073
+ this.stateManager.updateCaptureState({ isVideoActive: false, isLoading: false });
1378
2074
  }
2075
+ this.isMaskReady = false;
2076
+ this.updateStatus('Sesión finalizada', '', 'ready');
2077
+ this.detectionBoxes = [];
1379
2078
  this.cleanup();
1380
2079
  }
1381
- render() {
1382
- return (index.h("div", { key: 'b90673f523dbf112786eb7184f56415055765c0c', class: "detector-container" }, index.h("div", { key: '925c5c886e9af53b460281244958e722de670a70', class: "video-container" }, index.h("video", { key: '4a0074e33a81b4694c6c99e3ece256c1ac8fe1d5', ref: el => this.videoRef = el, autoplay: true, muted: true, playsinline: true, class: this.shouldMirrorVideo ? 'mirror' : '', style: { display: this.isVideoActive ? 'block' : 'none' } }), index.h("canvas", { key: 'a7b7f3b35c0535c11f6a4a155502dbe016f590b7', ref: el => this.canvasRef = el, class: this.shouldMirrorVideo ? 'mirror' : '' }), this.isMaskReady && (index.h("div", { key: '695b6a2f97e29b0b9c5b9d43682a951caff376a1', class: "overlay-mask" }, index.h("div", { key: '768875c39d5917c6a04306037d03d9e1aed114bd', class: "card-outline" }, index.h("div", { key: 'a56536deb7b8c99145d1bef6fee84e5801798644', class: "side side-top" }), index.h("div", { key: 'df413058c7e787f9c8a95a429a4f7186de07f5f6', class: "side side-right" }), index.h("div", { key: '37e074e3d4c914457f97720f9ab1f1ac2c70c4f1', class: "side side-bottom" }), index.h("div", { key: '772d3d40925c75ba5d39e2e7dd6405f7cc88d292', class: "side side-left" }), index.h("div", { key: 'd4e624782b3f4b4b8dbb8286b3acf003e433928c', class: "corner corner-tl" }), index.h("div", { key: '63f0ccfbbe3c1d413ca6912f36cab4afa6334bb2', class: "corner corner-tr" }), index.h("div", { key: '20012a50fe3d98ddfa669f5283a871c757522797', class: "corner corner-bl" }), index.h("div", { key: '9d82646bd08a6ca2b8c5782629fc68fd93cf1287', class: "corner corner-br" }), !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("div", { key: '79fcbdb52e434a45aa6f2748d6d84500beb2e844', class: "guide-text" }, this.statusMessage))), this.captureStep === 'back' && !this.showFlipAnimation && !this.showSuccessAnimation && (index.h("button", { key: '16e587d645e2489a3410fe80bfc014738f08f02f', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")), this.isVideoActive && (index.h("div", { key: 'd46d6881a9e1b63bdd849f5a8c6e96a2caefdefb', class: "camera-controls" }, this.isMultipleCamerasAvailable && (index.h("button", { key: 'afb4b44d691471f8af6e894e061aecb6c82259da', class: "flip-camera-button", onClick: () => this.flipCamera(), type: "button", title: "Cambiar c\u00E1mara" }, "Girar c\u00E1mara")), index.h("button", { key: '4e0680c2da9e6cc70b5880e8f5db9830c080acf9', class: "camera-selector-button", onClick: () => this.toggleCameraSelector(), type: "button", title: "Seleccionar c\u00E1mara" }, "C\u00E1maras"), this.debug && (index.h("div", { key: 'fc59922452a216273f742d3158559f6b2a1da43e', style: {
1383
- position: 'absolute',
1384
- top: '50px',
1385
- right: '0',
1386
- background: 'rgba(0,0,0,0.8)',
1387
- color: 'white',
1388
- padding: '8px',
1389
- fontSize: '10px',
1390
- borderRadius: '4px',
1391
- whiteSpace: 'nowrap'
1392
- } }, "C\u00E1maras: ", this.availableCameras.length, index.h("br", { key: '8f112283d1e0518a395dc6d94e1caa46fee0a86b' }), "M\u00FAltiples: ", this.isMultipleCamerasAvailable ? 'Sí' : 'No', index.h("br", { key: 'aacfd3ee868ee5d0819ce5ef693e3ef384867332' }), "Selector: ", this.showCameraSelector ? 'Visible' : 'Oculto', index.h("br", { key: '9927df7f56583c7388cee25e13526efc7e032eb1' }), "Video: ", this.isVideoActive ? 'Activo' : 'Inactivo')))), this.showCameraSelector && this.availableCameras.length > 0 && (index.h("div", { key: 'c2914bf7f3175b8f0ddab977abbdefe3022d7d29', class: "camera-selector-dropdown" }, index.h("div", { key: '0b5397e77ff33944f3620d78b1ab41275dffd7ac', class: "camera-selector-header" }, index.h("span", { key: '78f0fb8e34a0cf2d16138522a98cbdb9eefd671f' }, "Seleccionar C\u00E1mara"), index.h("button", { key: '0d4ea7b191d61d1d9b9c35462ce336148be73fcb', class: "close-selector", onClick: () => this.toggleCameraSelector(), type: "button" }, "\u00D7")), index.h("div", { key: 'c16c7a106493ef7633a4cd35b06a4f45327a2e23', class: "camera-list" }, this.availableCameras.map((camera) => (index.h("button", { key: camera.deviceId, class: `camera-option ${this.selectedCameraId === camera.deviceId ? 'selected' : ''}`, onClick: () => {
1393
- this.switchCamera(camera.deviceId);
1394
- this.toggleCameraSelector();
1395
- }, type: "button" }, index.h("span", { class: "camera-label" }, camera.label || `Cámara ${this.availableCameras.indexOf(camera) + 1}`), this.selectedCameraId === camera.deviceId && (index.h("span", { class: "selected-indicator" }, "\u2713")))))), index.h("div", { key: '11d6f980c3995a8414da5f7e6921f963ca72aed4', class: "device-info" }, index.h("small", { key: '78f5ff030f9e6e5021234a246599eb459b05d9f7' }, "Dispositivo: ", this.deviceType)))))), this.isCapturing && (index.h("div", { key: 'ef7d32491d8bdb94b2d6456420c2ddbc80f03d81', class: "capture-animation" })), this.showFlipAnimation && (index.h("div", { key: 'cfb5868ee75a9d1d1604c52f6fce1241090e4ac2', class: "flip-animation" }, index.h("div", { key: '1b41035e63f88434aba6699d4e68e06bea2c1529', class: "id-card-icon" }), index.h("div", { key: '4e83af9d0d39ce37b7448c4a0783b60b42b858e2', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), this.showSuccessAnimation && (index.h("div", { key: 'c7911e8be74b0fc7d7d18d7dcb52374645ca5f12', class: "success-animation" }, index.h("div", { key: '18e5ea5cfa3eb35fe3b99c12e6fab8e27e09e85e', class: "check-icon" }), index.h("div", { key: '490d8fcd6540c3b4fdc95f7fb5e6f6697722c9ac', class: "success-text" }, "\u00A1Proceso completado!"))), this.isLoading && (index.h("div", { key: 'f7fbfec6be2d8e0dc4e522b85b7d67897575cf0e', class: "loading-overlay" }, index.h("div", { key: '8282b92f19da6a9c7d22a64a0929b2b4d67c46be', class: "loading-spinner" }), index.h("div", { key: '7880b689297eb9d80a9b0023ba7933148fd8710a', class: "loading-text" }, this.statusMessage))), index.h("div", { key: '887c951fb03097171d9bd466fe24e36d11a49954', class: "watermark" }, index.h("img", { key: '314c9c172a4c6795c825741ea6f02b0e1186e93d', src: "https://storage.googleapis.com/jaak-static/commons/powered-by-jaak.png", alt: "Powered by Jaak" })))));
2080
+ // PERFORMANCE MONITORING METHODS
2081
+ initializePerformanceMonitor() {
2082
+ this.performanceMetrics.lastUpdateTime = performance.now();
2083
+ // Update performance metrics every 500ms
2084
+ this.performanceUpdateInterval = window.setInterval(() => {
2085
+ this.updatePerformanceMetrics();
2086
+ }, 500);
2087
+ this.logger.debug('Monitor de performance inicializado');
2088
+ }
2089
+ updatePerformanceMetrics() {
2090
+ const currentTime = performance.now();
2091
+ const deltaTime = currentTime - this.performanceMetrics.lastUpdateTime;
2092
+ // Calculate FPS
2093
+ if (deltaTime > 0) {
2094
+ this.performanceMetrics.fps = Math.round(1000 / (deltaTime / this.frameSkipCounter || 1));
2095
+ }
2096
+ // Get memory usage if available
2097
+ if ('memory' in performance) {
2098
+ const memInfo = performance.memory;
2099
+ this.performanceMetrics.memoryUsage = Math.round(memInfo.usedJSHeapSize / 1048576); // MB
2100
+ }
2101
+ // Calculate detection success rate
2102
+ if (this.performanceMetrics.totalDetections > 0) {
2103
+ this.performanceMetrics.successfulDetections = this.performanceMetrics.successfulDetections;
2104
+ const detectionRate = (this.performanceMetrics.successfulDetections / this.performanceMetrics.totalDetections) * 100;
2105
+ this.performanceMetrics.detectionRate = Math.round(detectionRate);
2106
+ }
2107
+ // Update state for rendering
2108
+ this.performanceData = {
2109
+ fps: this.performanceMetrics.fps,
2110
+ inferenceTime: this.performanceMetrics.inferenceTime,
2111
+ memoryUsage: this.performanceMetrics.memoryUsage,
2112
+ onnxLoadTime: this.performanceMetrics.onnxLoadTime,
2113
+ frameProcessingTime: this.performanceMetrics.frameProcessingTime,
2114
+ totalDetections: this.performanceMetrics.totalDetections,
2115
+ successfulDetections: this.performanceMetrics.successfulDetections,
2116
+ detectionRate: this.performanceMetrics.detectionRate
2117
+ };
2118
+ this.performanceMetrics.lastUpdateTime = currentTime;
2119
+ }
2120
+ recordOnnxPerformance(loadTime, inferenceTime) {
2121
+ this.performanceMetrics.onnxLoadTime = Math.round(loadTime);
2122
+ this.performanceMetrics.inferenceTime = Math.round(inferenceTime);
2123
+ }
2124
+ recordFrameProcessing(processingTime, detectionsFound) {
2125
+ this.performanceMetrics.frameProcessingTime = Math.round(processingTime);
2126
+ this.performanceMetrics.totalDetections++;
2127
+ if (detectionsFound > 0) {
2128
+ this.performanceMetrics.successfulDetections++;
2129
+ }
1396
2130
  }
1397
2131
  };
1398
2132
  JaakStamps.style = myComponentCss;