@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.
- package/README.md +216 -215
- package/dist/cjs/jaak-stamps-webcomponent.cjs.js +1 -1
- package/dist/cjs/jaak-stamps.cjs.entry.js +1786 -1052
- package/dist/cjs/jaak-stamps.cjs.entry.js.map +1 -1
- package/dist/cjs/jaak-stamps.entry.cjs.js.map +1 -1
- package/dist/cjs/loader.cjs.js +1 -1
- package/dist/collection/components/my-component/my-component.css +440 -110
- package/dist/collection/components/my-component/my-component.js +829 -1120
- package/dist/collection/components/my-component/my-component.js.map +1 -1
- package/dist/collection/services/CameraService.js +453 -0
- package/dist/collection/services/CameraService.js.map +1 -0
- package/dist/collection/services/DetectionService.js +369 -0
- package/dist/collection/services/DetectionService.js.map +1 -0
- package/dist/collection/services/EventBusService.js +42 -0
- package/dist/collection/services/EventBusService.js.map +1 -0
- package/dist/collection/services/LoggerService.js +40 -0
- package/dist/collection/services/LoggerService.js.map +1 -0
- package/dist/collection/services/ServiceContainer.js +66 -0
- package/dist/collection/services/ServiceContainer.js.map +1 -0
- package/dist/collection/services/StateManagerService.js +109 -0
- package/dist/collection/services/StateManagerService.js.map +1 -0
- package/dist/collection/services/factories/DeviceStrategyFactory.js +16 -0
- package/dist/collection/services/factories/DeviceStrategyFactory.js.map +1 -0
- package/dist/collection/services/interfaces/ICameraService.js +2 -0
- package/dist/collection/services/interfaces/ICameraService.js.map +1 -0
- package/dist/collection/services/interfaces/IDetectionService.js +2 -0
- package/dist/collection/services/interfaces/IDetectionService.js.map +1 -0
- package/dist/collection/services/interfaces/IEventBus.js +2 -0
- package/dist/collection/services/interfaces/IEventBus.js.map +1 -0
- package/dist/collection/services/interfaces/ILogger.js +2 -0
- package/dist/collection/services/interfaces/ILogger.js.map +1 -0
- package/dist/collection/services/interfaces/IStateManager.js +2 -0
- package/dist/collection/services/interfaces/IStateManager.js.map +1 -0
- package/dist/collection/services/strategies/HighPerformanceDeviceStrategy.js +30 -0
- package/dist/collection/services/strategies/HighPerformanceDeviceStrategy.js.map +1 -0
- package/dist/collection/services/strategies/IDeviceStrategy.js +2 -0
- package/dist/collection/services/strategies/IDeviceStrategy.js.map +1 -0
- package/dist/collection/services/strategies/LowMemoryDeviceStrategy.js +30 -0
- package/dist/collection/services/strategies/LowMemoryDeviceStrategy.js.map +1 -0
- package/dist/collection/types/component-types.js +2 -0
- package/dist/collection/types/component-types.js.map +1 -0
- package/dist/components/jaak-stamps.js +1802 -1076
- package/dist/components/jaak-stamps.js.map +1 -1
- package/dist/esm/jaak-stamps-webcomponent.js +1 -1
- package/dist/esm/jaak-stamps.entry.js +1786 -1052
- package/dist/esm/jaak-stamps.entry.js.map +1 -1
- package/dist/esm/loader.js +1 -1
- package/dist/jaak-stamps-webcomponent/jaak-stamps-webcomponent.esm.js +1 -1
- package/dist/jaak-stamps-webcomponent/jaak-stamps.entry.esm.js.map +1 -1
- package/dist/jaak-stamps-webcomponent/p-10ee2dab.entry.js +2 -0
- package/dist/jaak-stamps-webcomponent/p-10ee2dab.entry.js.map +1 -0
- package/dist/types/components/my-component/my-component.d.ts +83 -108
- package/dist/types/components.d.ts +23 -9
- package/dist/types/services/CameraService.d.ts +46 -0
- package/dist/types/services/DetectionService.d.ts +35 -0
- package/dist/types/services/EventBusService.d.ts +9 -0
- package/dist/types/services/LoggerService.d.ts +12 -0
- package/dist/types/services/ServiceContainer.d.ts +27 -0
- package/dist/types/services/StateManagerService.d.ts +15 -0
- package/dist/types/services/factories/DeviceStrategyFactory.d.ts +4 -0
- package/dist/types/services/interfaces/ICameraService.d.ts +34 -0
- package/dist/types/services/interfaces/IDetectionService.d.ts +31 -0
- package/dist/types/services/interfaces/IEventBus.d.ts +16 -0
- package/dist/types/services/interfaces/ILogger.d.ts +8 -0
- package/dist/types/services/interfaces/IStateManager.d.ts +35 -0
- package/dist/types/services/strategies/HighPerformanceDeviceStrategy.d.ts +6 -0
- package/dist/types/services/strategies/IDeviceStrategy.d.ts +21 -0
- package/dist/types/services/strategies/LowMemoryDeviceStrategy.d.ts +6 -0
- package/dist/types/types/component-types.d.ts +36 -0
- package/package.json +3 -3
- package/dist/jaak-stamps-webcomponent/p-14eb13d8.entry.js +0 -2
- package/dist/jaak-stamps-webcomponent/p-14eb13d8.entry.js.map +0 -1
|
@@ -1,121 +1,210 @@
|
|
|
1
1
|
import { p as proxyCustomElement, H, c as createEvent, h } from './index.js';
|
|
2
2
|
|
|
3
|
-
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)}}";
|
|
3
|
+
class LoggerService {
|
|
4
|
+
debugMode;
|
|
5
|
+
constructor(debug = false) {
|
|
6
|
+
this.debugMode = debug;
|
|
7
|
+
}
|
|
8
|
+
setDebugMode(debug) {
|
|
9
|
+
this.debugMode = debug;
|
|
10
|
+
}
|
|
11
|
+
info(...args) {
|
|
12
|
+
if (this.debugMode) {
|
|
13
|
+
console.log(`[JAAK-STAMPS] [INFO] [${new Date().toLocaleTimeString()}]`, ...args);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
warn(...args) {
|
|
17
|
+
if (this.debugMode) {
|
|
18
|
+
console.warn(`[JAAK-STAMPS] [WARN] [${new Date().toLocaleTimeString()}]`, ...args);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
error(...args) {
|
|
22
|
+
if (this.debugMode) {
|
|
23
|
+
console.error(`[JAAK-STAMPS] [ERROR] [${new Date().toLocaleTimeString()}]`, ...args);
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
debug(...args) {
|
|
27
|
+
if (this.debugMode) {
|
|
28
|
+
console.debug(`[JAAK-STAMPS] [DEBUG] [${new Date().toLocaleTimeString()}]`, ...args);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
state(state, data) {
|
|
32
|
+
if (this.debugMode) {
|
|
33
|
+
console.log(`[JAAK-STAMPS] [STATE] [${new Date().toLocaleTimeString()}] ${state}`, data || '');
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
performance(operation, duration) {
|
|
37
|
+
if (this.debugMode) {
|
|
38
|
+
console.log(`[JAAK-STAMPS] [PERF] [${new Date().toLocaleTimeString()}] ${operation}: ${duration}ms`);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
4
42
|
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
this.
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
this.
|
|
43
|
+
class EventBusService {
|
|
44
|
+
events = new Map();
|
|
45
|
+
on(event, callback) {
|
|
46
|
+
if (!this.events.has(event)) {
|
|
47
|
+
this.events.set(event, []);
|
|
48
|
+
}
|
|
49
|
+
this.events.get(event).push(callback);
|
|
12
50
|
}
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
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);
|
|
51
|
+
off(event, callback) {
|
|
52
|
+
const callbacks = this.events.get(event);
|
|
53
|
+
if (callbacks) {
|
|
54
|
+
const index = callbacks.indexOf(callback);
|
|
55
|
+
if (index > -1) {
|
|
56
|
+
callbacks.splice(index, 1);
|
|
57
|
+
}
|
|
84
58
|
}
|
|
85
59
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
60
|
+
emit(event, data) {
|
|
61
|
+
const callbacks = this.events.get(event);
|
|
62
|
+
if (callbacks) {
|
|
63
|
+
callbacks.forEach(callback => {
|
|
64
|
+
try {
|
|
65
|
+
callback(data);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
console.error(`Error in event callback for ${event}:`, error);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
90
71
|
}
|
|
91
72
|
}
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
this.
|
|
73
|
+
once(event, callback) {
|
|
74
|
+
const onceCallback = (data) => {
|
|
75
|
+
callback(data);
|
|
76
|
+
this.off(event, onceCallback);
|
|
77
|
+
};
|
|
78
|
+
this.on(event, onceCallback);
|
|
79
|
+
}
|
|
80
|
+
clear() {
|
|
81
|
+
this.events.clear();
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
class StateManagerService {
|
|
86
|
+
eventBus;
|
|
87
|
+
captureState = {
|
|
88
|
+
step: 'front',
|
|
89
|
+
isCapturing: false,
|
|
90
|
+
isDetectionPaused: false,
|
|
91
|
+
isVideoActive: false,
|
|
92
|
+
isLoading: false,
|
|
93
|
+
showFlipAnimation: false,
|
|
94
|
+
showSuccessAnimation: false,
|
|
95
|
+
bestScore: 0,
|
|
96
|
+
hasScreenshotTaken: false
|
|
97
|
+
};
|
|
98
|
+
capturedImages = {
|
|
99
|
+
front: {
|
|
100
|
+
fullFrame: null,
|
|
101
|
+
cropped: null
|
|
102
|
+
},
|
|
103
|
+
back: {
|
|
104
|
+
fullFrame: null,
|
|
105
|
+
cropped: null
|
|
106
|
+
},
|
|
107
|
+
metadata: {
|
|
108
|
+
totalImages: 0,
|
|
109
|
+
processCompleted: false,
|
|
110
|
+
backCaptureSkipped: false
|
|
96
111
|
}
|
|
112
|
+
};
|
|
113
|
+
constructor(eventBus) {
|
|
114
|
+
this.eventBus = eventBus;
|
|
97
115
|
}
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
116
|
+
getCaptureState() {
|
|
117
|
+
return { ...this.captureState };
|
|
118
|
+
}
|
|
119
|
+
updateCaptureState(updates) {
|
|
120
|
+
const previousState = { ...this.captureState };
|
|
121
|
+
this.captureState = { ...this.captureState, ...updates };
|
|
122
|
+
// Emit state change event
|
|
123
|
+
this.eventBus.emit('state-changed', {
|
|
124
|
+
previous: previousState,
|
|
125
|
+
current: this.captureState,
|
|
126
|
+
changes: updates
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
getCapturedImages() {
|
|
130
|
+
return JSON.parse(JSON.stringify(this.capturedImages));
|
|
131
|
+
}
|
|
132
|
+
setCapturedImages(images) {
|
|
133
|
+
this.capturedImages = {
|
|
134
|
+
...this.capturedImages,
|
|
135
|
+
...images,
|
|
136
|
+
metadata: {
|
|
137
|
+
...this.capturedImages.metadata,
|
|
138
|
+
...images.metadata
|
|
139
|
+
}
|
|
140
|
+
};
|
|
141
|
+
// Update total images count
|
|
142
|
+
let totalImages = 0;
|
|
143
|
+
if (this.capturedImages.front.fullFrame && this.capturedImages.front.cropped) {
|
|
144
|
+
totalImages += 2;
|
|
145
|
+
}
|
|
146
|
+
if (this.capturedImages.back.fullFrame && this.capturedImages.back.cropped) {
|
|
147
|
+
totalImages += 2;
|
|
103
148
|
}
|
|
149
|
+
this.capturedImages.metadata.totalImages = totalImages;
|
|
104
150
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
151
|
+
reset() {
|
|
152
|
+
this.captureState = {
|
|
153
|
+
step: 'front',
|
|
154
|
+
isCapturing: false,
|
|
155
|
+
isDetectionPaused: false,
|
|
156
|
+
isVideoActive: false,
|
|
157
|
+
isLoading: false,
|
|
158
|
+
showFlipAnimation: false,
|
|
159
|
+
showSuccessAnimation: false,
|
|
160
|
+
bestScore: 0,
|
|
161
|
+
hasScreenshotTaken: false
|
|
162
|
+
};
|
|
163
|
+
this.capturedImages = {
|
|
164
|
+
front: {
|
|
165
|
+
fullFrame: null,
|
|
166
|
+
cropped: null
|
|
167
|
+
},
|
|
168
|
+
back: {
|
|
169
|
+
fullFrame: null,
|
|
170
|
+
cropped: null
|
|
171
|
+
},
|
|
172
|
+
metadata: {
|
|
173
|
+
totalImages: 0,
|
|
174
|
+
processCompleted: false,
|
|
175
|
+
backCaptureSkipped: false
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
this.eventBus.emit('state-changed', {
|
|
179
|
+
previous: null,
|
|
180
|
+
current: this.captureState,
|
|
181
|
+
changes: { reset: true }
|
|
182
|
+
});
|
|
109
183
|
}
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
184
|
+
isProcessCompleted() {
|
|
185
|
+
return this.captureState.step === 'completed';
|
|
186
|
+
}
|
|
187
|
+
canProceedToBack() {
|
|
188
|
+
return this.captureState.step === 'front' &&
|
|
189
|
+
this.capturedImages.front.fullFrame !== null &&
|
|
190
|
+
this.capturedImages.front.cropped !== null;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
class CameraService {
|
|
195
|
+
logger;
|
|
196
|
+
eventBus;
|
|
197
|
+
availableCameras = [];
|
|
198
|
+
selectedCameraId = null;
|
|
199
|
+
deviceType = 'desktop';
|
|
200
|
+
preferredCameraFacing = null;
|
|
201
|
+
preferredCamera = 'auto';
|
|
202
|
+
constructor(logger, eventBus, preferredCamera = 'auto') {
|
|
203
|
+
this.logger = logger;
|
|
204
|
+
this.eventBus = eventBus;
|
|
205
|
+
this.preferredCamera = preferredCamera;
|
|
116
206
|
}
|
|
117
|
-
async
|
|
118
|
-
// Detect device type
|
|
207
|
+
async detectDeviceType() {
|
|
119
208
|
const userAgent = navigator.userAgent;
|
|
120
209
|
const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(userAgent);
|
|
121
210
|
const isTablet = /iPad|Android/i.test(userAgent) && window.innerWidth >= 768;
|
|
@@ -128,288 +217,1159 @@ const JaakStamps$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H
|
|
|
128
217
|
else {
|
|
129
218
|
this.deviceType = 'desktop';
|
|
130
219
|
}
|
|
131
|
-
this.
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
220
|
+
this.logger.state('DISPOSITIVO_DETECTADO', {
|
|
221
|
+
deviceType: this.deviceType,
|
|
222
|
+
userAgent: navigator.userAgent,
|
|
223
|
+
screenDimensions: { width: window.innerWidth, height: window.innerHeight }
|
|
224
|
+
});
|
|
225
|
+
return this.deviceType;
|
|
136
226
|
}
|
|
137
|
-
async
|
|
227
|
+
async enumerateDevices() {
|
|
138
228
|
try {
|
|
139
|
-
// First, check if we have permission to enumerate devices
|
|
140
229
|
const permissionStatus = await this.checkCameraPermission();
|
|
141
230
|
if (permissionStatus === 'denied') {
|
|
142
|
-
this.
|
|
143
|
-
|
|
144
|
-
this.statusColor = "#ff6b6b";
|
|
145
|
-
return;
|
|
231
|
+
this.logger.error('Permiso de cámara denegado por el usuario');
|
|
232
|
+
return [];
|
|
146
233
|
}
|
|
147
|
-
// Request minimal permission to get device labels
|
|
148
234
|
if (permissionStatus === 'prompt') {
|
|
149
235
|
const tempStream = await navigator.mediaDevices.getUserMedia({ video: true });
|
|
150
236
|
tempStream.getTracks().forEach(track => track.stop());
|
|
151
237
|
}
|
|
152
|
-
// Now enumerate devices with labels
|
|
153
238
|
const devices = await navigator.mediaDevices.enumerateDevices();
|
|
154
239
|
this.availableCameras = devices.filter(device => device.kind === 'videoinput');
|
|
155
|
-
this.
|
|
156
|
-
this.debugLog('📹 Available cameras:', {
|
|
240
|
+
this.logger.state('CAMARAS_DETECTADAS', {
|
|
157
241
|
count: this.availableCameras.length,
|
|
158
|
-
isMultipleCamerasAvailable: this.isMultipleCamerasAvailable,
|
|
159
242
|
cameras: this.availableCameras.map(cam => ({
|
|
160
243
|
id: cam.deviceId,
|
|
161
244
|
label: cam.label || 'Unknown Camera'
|
|
162
245
|
}))
|
|
163
246
|
});
|
|
164
|
-
// Set initial camera preference based on device type
|
|
165
247
|
this.setInitialCameraPreference();
|
|
248
|
+
this.eventBus.emit('camera-changed', this.selectedCameraId);
|
|
249
|
+
return this.availableCameras;
|
|
166
250
|
}
|
|
167
251
|
catch (error) {
|
|
168
|
-
this.
|
|
252
|
+
this.logger.error('Error al enumerar cámaras disponibles:', error);
|
|
169
253
|
this.handleCameraPermissionError(error);
|
|
254
|
+
return [];
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
getAvailableCameras() {
|
|
258
|
+
return [...this.availableCameras];
|
|
259
|
+
}
|
|
260
|
+
isMultipleCamerasAvailable() {
|
|
261
|
+
return this.availableCameras.length > 1;
|
|
262
|
+
}
|
|
263
|
+
getSelectedCameraId() {
|
|
264
|
+
return this.selectedCameraId;
|
|
265
|
+
}
|
|
266
|
+
async setSelectedCamera(cameraId) {
|
|
267
|
+
const camera = this.availableCameras.find(cam => cam.deviceId === cameraId);
|
|
268
|
+
if (!camera) {
|
|
269
|
+
throw new Error(`Camera with ID ${cameraId} not found`);
|
|
270
|
+
}
|
|
271
|
+
this.selectedCameraId = cameraId;
|
|
272
|
+
this.updatePreferredFacing(camera);
|
|
273
|
+
this.savePreference();
|
|
274
|
+
this.eventBus.emit('camera-changed', cameraId);
|
|
275
|
+
}
|
|
276
|
+
getPreferredFacing() {
|
|
277
|
+
return this.preferredCameraFacing;
|
|
278
|
+
}
|
|
279
|
+
async setupCamera(constraints) {
|
|
280
|
+
const finalConstraints = constraints || await this.getMaxResolution();
|
|
281
|
+
const stream = await navigator.mediaDevices.getUserMedia({
|
|
282
|
+
video: finalConstraints,
|
|
283
|
+
audio: false
|
|
284
|
+
});
|
|
285
|
+
return stream;
|
|
286
|
+
}
|
|
287
|
+
async switchCamera(cameraId) {
|
|
288
|
+
const selectedCamera = this.availableCameras.find(cam => cam.deviceId === cameraId);
|
|
289
|
+
if (!selectedCamera) {
|
|
290
|
+
this.logger.warn('Cámara seleccionada no encontrada, re-enumerando dispositivos...');
|
|
291
|
+
await this.enumerateDevices();
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
await this.setSelectedCamera(cameraId);
|
|
295
|
+
this.logger.state('CAMARA_CAMBIADA', {
|
|
296
|
+
label: selectedCamera.label,
|
|
297
|
+
deviceId: selectedCamera.deviceId
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
async flipToNextCamera() {
|
|
301
|
+
if (!this.isMultipleCamerasAvailable())
|
|
302
|
+
return;
|
|
303
|
+
const currentIndex = this.availableCameras.findIndex(camera => camera.deviceId === this.selectedCameraId);
|
|
304
|
+
const nextIndex = (currentIndex + 1) % this.availableCameras.length;
|
|
305
|
+
const nextCamera = this.availableCameras[nextIndex];
|
|
306
|
+
await this.switchCamera(nextCamera.deviceId);
|
|
307
|
+
}
|
|
308
|
+
savePreference() {
|
|
309
|
+
try {
|
|
310
|
+
const preference = {
|
|
311
|
+
cameraId: this.selectedCameraId,
|
|
312
|
+
facing: this.preferredCameraFacing,
|
|
313
|
+
timestamp: Date.now()
|
|
314
|
+
};
|
|
315
|
+
localStorage.setItem('jaak-stamps-camera-preference', JSON.stringify(preference));
|
|
316
|
+
this.logger.state('PREFERENCIA_CAMARA_GUARDADA', preference);
|
|
317
|
+
}
|
|
318
|
+
catch (error) {
|
|
319
|
+
this.logger.warn('Error al guardar preferencia de cámara:', error);
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
loadPreference() {
|
|
323
|
+
try {
|
|
324
|
+
const saved = localStorage.getItem('jaak-stamps-camera-preference');
|
|
325
|
+
if (saved) {
|
|
326
|
+
const preference = JSON.parse(saved);
|
|
327
|
+
const isStillAvailable = this.availableCameras.some(camera => camera.deviceId === preference.cameraId);
|
|
328
|
+
if (isStillAvailable) {
|
|
329
|
+
this.selectedCameraId = preference.cameraId;
|
|
330
|
+
this.preferredCameraFacing = preference.facing;
|
|
331
|
+
this.logger.state('PREFERENCIA_CAMARA_CARGADA', preference);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
this.logger.warn('Error al cargar preferencia de cámara:', error);
|
|
170
337
|
}
|
|
171
338
|
}
|
|
339
|
+
isRearCamera(stream) {
|
|
340
|
+
const videoTrack = stream.getVideoTracks()[0];
|
|
341
|
+
if (!videoTrack)
|
|
342
|
+
return false;
|
|
343
|
+
const settings = videoTrack.getSettings();
|
|
344
|
+
return settings.facingMode === 'environment';
|
|
345
|
+
}
|
|
346
|
+
getCameraInfo() {
|
|
347
|
+
return {
|
|
348
|
+
availableCameras: this.availableCameras.map(camera => ({
|
|
349
|
+
id: camera.deviceId,
|
|
350
|
+
label: camera.label || 'Unknown Camera',
|
|
351
|
+
selected: camera.deviceId === this.selectedCameraId
|
|
352
|
+
})),
|
|
353
|
+
selectedCameraId: this.selectedCameraId,
|
|
354
|
+
deviceType: this.deviceType,
|
|
355
|
+
isMultipleCamerasAvailable: this.isMultipleCamerasAvailable(),
|
|
356
|
+
preferredFacing: this.preferredCameraFacing
|
|
357
|
+
};
|
|
358
|
+
}
|
|
172
359
|
async checkCameraPermission() {
|
|
173
360
|
try {
|
|
174
361
|
if (!navigator.permissions) {
|
|
175
|
-
return 'prompt';
|
|
362
|
+
return 'prompt';
|
|
176
363
|
}
|
|
177
364
|
const permission = await navigator.permissions.query({ name: 'camera' });
|
|
178
365
|
return permission.state;
|
|
179
366
|
}
|
|
180
367
|
catch (error) {
|
|
181
|
-
this.
|
|
368
|
+
this.logger.warn('No se pudo verificar permisos de cámara:', error);
|
|
182
369
|
return 'prompt';
|
|
183
370
|
}
|
|
184
371
|
}
|
|
185
372
|
handleCameraPermissionError(error) {
|
|
186
|
-
|
|
187
|
-
|
|
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
|
-
}
|
|
373
|
+
this.availableCameras = [];
|
|
374
|
+
this.eventBus.emit('error', new Error(`Camera permission error: ${error.message}`));
|
|
210
375
|
}
|
|
211
376
|
setInitialCameraPreference() {
|
|
212
377
|
if (this.availableCameras.length === 0)
|
|
213
378
|
return;
|
|
214
|
-
// Apply user preference for camera selection
|
|
215
379
|
if (this.preferredCamera === 'front') {
|
|
216
|
-
|
|
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
|
-
}
|
|
380
|
+
this.selectFrontCamera();
|
|
230
381
|
}
|
|
231
382
|
else if (this.preferredCamera === 'back') {
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
383
|
+
this.selectBackCamera();
|
|
384
|
+
}
|
|
385
|
+
else {
|
|
386
|
+
this.selectAutoCamera();
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
selectFrontCamera() {
|
|
390
|
+
this.preferredCameraFacing = 'user';
|
|
391
|
+
const frontCamera = this.availableCameras.find(camera => camera.label.toLowerCase().includes('front') ||
|
|
392
|
+
camera.label.toLowerCase().includes('user') ||
|
|
393
|
+
camera.label.toLowerCase().includes('selfie') ||
|
|
394
|
+
!camera.label.toLowerCase().includes('back') && !camera.label.toLowerCase().includes('rear'));
|
|
395
|
+
this.selectedCameraId = frontCamera ? frontCamera.deviceId : this.availableCameras[0].deviceId;
|
|
396
|
+
this.logger.state('CAMARA_FRONTAL_SELECCIONADA', {
|
|
397
|
+
label: frontCamera?.label || this.availableCameras[0].label,
|
|
398
|
+
deviceId: this.selectedCameraId
|
|
399
|
+
});
|
|
400
|
+
}
|
|
401
|
+
selectBackCamera() {
|
|
402
|
+
this.preferredCameraFacing = 'environment';
|
|
403
|
+
const backCamera = this.availableCameras.find(camera => camera.label.toLowerCase().includes('back') ||
|
|
404
|
+
camera.label.toLowerCase().includes('rear') ||
|
|
405
|
+
camera.label.toLowerCase().includes('environment'));
|
|
406
|
+
this.selectedCameraId = backCamera ? backCamera.deviceId : this.availableCameras[0].deviceId;
|
|
407
|
+
this.logger.state('CAMARA_TRASERA_SELECCIONADA', {
|
|
408
|
+
label: backCamera?.label || this.availableCameras[0].label,
|
|
409
|
+
deviceId: this.selectedCameraId
|
|
410
|
+
});
|
|
411
|
+
}
|
|
412
|
+
selectAutoCamera() {
|
|
413
|
+
if (this.deviceType === 'mobile' || this.deviceType === 'tablet') {
|
|
414
|
+
this.selectBackCamera();
|
|
415
|
+
this.logger.state('CAMARA_AUTO_SELECCIONADA_MOBILE', { type: 'rear' });
|
|
416
|
+
}
|
|
417
|
+
else {
|
|
418
|
+
this.selectedCameraId = this.availableCameras[0].deviceId;
|
|
419
|
+
this.logger.state('CAMARA_AUTO_SELECCIONADA_DESKTOP', {
|
|
420
|
+
label: this.availableCameras[0].label,
|
|
421
|
+
deviceId: this.selectedCameraId
|
|
422
|
+
});
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
updatePreferredFacing(camera) {
|
|
426
|
+
const isRearCamera = camera.label.toLowerCase().includes('back') ||
|
|
427
|
+
camera.label.toLowerCase().includes('rear') ||
|
|
428
|
+
camera.label.toLowerCase().includes('environment');
|
|
429
|
+
this.preferredCameraFacing = isRearCamera ? 'environment' : 'user';
|
|
430
|
+
}
|
|
431
|
+
async getMaxResolution() {
|
|
432
|
+
try {
|
|
433
|
+
const videoConstraints = {};
|
|
434
|
+
if (this.selectedCameraId) {
|
|
435
|
+
videoConstraints.deviceId = { exact: this.selectedCameraId };
|
|
436
|
+
}
|
|
437
|
+
else if (this.preferredCameraFacing) {
|
|
438
|
+
videoConstraints.facingMode = this.preferredCameraFacing;
|
|
240
439
|
}
|
|
241
440
|
else {
|
|
242
|
-
|
|
243
|
-
this.debugLog('⚠️ Back camera not found, using first available:', this.availableCameras[0].label);
|
|
441
|
+
videoConstraints.facingMode = "environment";
|
|
244
442
|
}
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
443
|
+
const tempStream = await navigator.mediaDevices.getUserMedia({
|
|
444
|
+
video: videoConstraints
|
|
445
|
+
});
|
|
446
|
+
const videoTrack = tempStream.getVideoTracks()[0];
|
|
447
|
+
const capabilities = videoTrack.getCapabilities();
|
|
448
|
+
tempStream.getTracks().forEach(track => track.stop());
|
|
449
|
+
const constraints = { ...videoConstraints };
|
|
450
|
+
// Enhanced focus and image quality settings
|
|
451
|
+
this.applyAdvancedCameraSettings(constraints, capabilities);
|
|
452
|
+
if (capabilities.width && capabilities.height) {
|
|
453
|
+
const maxWidth = Math.min(capabilities.width.max, 1920);
|
|
454
|
+
const maxHeight = Math.min(capabilities.height.max, 1080);
|
|
455
|
+
const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
|
|
456
|
+
if (isTablet) {
|
|
457
|
+
constraints.width = { ideal: Math.min(maxWidth, 1280) };
|
|
458
|
+
constraints.height = { ideal: Math.min(maxHeight, 720) };
|
|
257
459
|
}
|
|
258
460
|
else {
|
|
259
|
-
|
|
260
|
-
|
|
461
|
+
constraints.width = { ideal: maxWidth };
|
|
462
|
+
constraints.height = { ideal: maxHeight };
|
|
261
463
|
}
|
|
262
464
|
}
|
|
465
|
+
this.logger.state('CONFIGURACION_CAMARA_OPTIMIZADA', {
|
|
466
|
+
constraints,
|
|
467
|
+
capabilities: this.getCapabilitiesSummary(capabilities)
|
|
468
|
+
});
|
|
469
|
+
return constraints;
|
|
470
|
+
}
|
|
471
|
+
catch (err) {
|
|
472
|
+
this.logger.warn('No se pudieron obtener capacidades de cámara, usando configuración de respaldo');
|
|
473
|
+
const isTablet = /iPad|Android/i.test(navigator.userAgent) && window.innerWidth >= 768;
|
|
474
|
+
const fallbackConstraints = {
|
|
475
|
+
width: { ideal: isTablet ? 1280 : 1920 },
|
|
476
|
+
height: { ideal: isTablet ? 720 : 1080 }
|
|
477
|
+
};
|
|
478
|
+
// Apply basic focus settings even for fallback
|
|
479
|
+
this.applyBasicFocusSettings(fallbackConstraints);
|
|
480
|
+
if (this.selectedCameraId) {
|
|
481
|
+
fallbackConstraints.deviceId = { exact: this.selectedCameraId };
|
|
482
|
+
}
|
|
483
|
+
else if (this.preferredCameraFacing) {
|
|
484
|
+
fallbackConstraints.facingMode = this.preferredCameraFacing;
|
|
485
|
+
}
|
|
263
486
|
else {
|
|
264
|
-
|
|
265
|
-
this.selectedCameraId = this.availableCameras[0].deviceId;
|
|
266
|
-
this.debugLog('💻 Auto-selected desktop camera:', this.availableCameras[0].label);
|
|
487
|
+
fallbackConstraints.facingMode = "environment";
|
|
267
488
|
}
|
|
489
|
+
return fallbackConstraints;
|
|
268
490
|
}
|
|
269
491
|
}
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
492
|
+
applyAdvancedCameraSettings(constraints, capabilities) {
|
|
493
|
+
// Apply standard camera settings that are widely supported
|
|
494
|
+
// Frame rate optimization
|
|
495
|
+
if (capabilities.frameRate) {
|
|
496
|
+
constraints.frameRate = {
|
|
497
|
+
ideal: 30,
|
|
498
|
+
min: 15,
|
|
499
|
+
max: 60
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
// Width and height constraints for optimal resolution
|
|
503
|
+
if (capabilities.width && capabilities.height) {
|
|
504
|
+
constraints.width = {
|
|
505
|
+
ideal: Math.min(1920, capabilities.width.max || 1920),
|
|
506
|
+
min: 640
|
|
507
|
+
};
|
|
508
|
+
constraints.height = {
|
|
509
|
+
ideal: Math.min(1080, capabilities.height.max || 1080),
|
|
510
|
+
min: 480
|
|
511
|
+
};
|
|
512
|
+
}
|
|
513
|
+
// Apply enhanced constraints through advanced array for better browser compatibility
|
|
514
|
+
const advancedConstraints = [];
|
|
515
|
+
// Try to set optimal settings through advanced constraints
|
|
516
|
+
const advanced = {};
|
|
517
|
+
// Focus mode - use 'any' type to bypass TypeScript limitations
|
|
518
|
+
if (capabilities.focusMode) {
|
|
519
|
+
if (capabilities.focusMode.includes('continuous')) {
|
|
520
|
+
advanced.focusMode = 'continuous';
|
|
521
|
+
}
|
|
522
|
+
else if (capabilities.focusMode.includes('single-shot')) {
|
|
523
|
+
advanced.focusMode = 'single-shot';
|
|
282
524
|
}
|
|
283
525
|
}
|
|
284
|
-
|
|
285
|
-
|
|
526
|
+
// Focus distance for close objects
|
|
527
|
+
if (capabilities.focusDistance) {
|
|
528
|
+
advanced.focusDistance = {
|
|
529
|
+
ideal: 0.4, // 40cm - optimal for document capture
|
|
530
|
+
min: 0.2,
|
|
531
|
+
max: 1.0
|
|
532
|
+
};
|
|
286
533
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
534
|
+
// Zoom control
|
|
535
|
+
if (capabilities.zoom) {
|
|
536
|
+
advanced.zoom = {
|
|
537
|
+
ideal: 1.0,
|
|
538
|
+
min: capabilities.zoom.min,
|
|
539
|
+
max: Math.min(capabilities.zoom.max, 3.0)
|
|
540
|
+
};
|
|
541
|
+
}
|
|
542
|
+
// Add advanced constraints if any were set
|
|
543
|
+
if (Object.keys(advanced).length > 0) {
|
|
544
|
+
advancedConstraints.push(advanced);
|
|
545
|
+
}
|
|
546
|
+
if (advancedConstraints.length > 0) {
|
|
547
|
+
constraints.advanced = advancedConstraints;
|
|
548
|
+
}
|
|
549
|
+
}
|
|
550
|
+
applyBasicFocusSettings(constraints) {
|
|
551
|
+
// Apply basic focus settings when capabilities are not available
|
|
552
|
+
// Use advanced constraints for non-standard properties
|
|
553
|
+
const advanced = {
|
|
554
|
+
focusMode: 'continuous',
|
|
555
|
+
exposureMode: 'continuous',
|
|
556
|
+
whiteBalanceMode: 'continuous'
|
|
557
|
+
};
|
|
558
|
+
if (!constraints.advanced) {
|
|
559
|
+
constraints.advanced = [];
|
|
560
|
+
}
|
|
561
|
+
constraints.advanced.push(advanced);
|
|
562
|
+
constraints.frameRate = { ideal: 30 };
|
|
563
|
+
}
|
|
564
|
+
getCapabilitiesSummary(capabilities) {
|
|
565
|
+
return {
|
|
566
|
+
hasAutoFocus: !!capabilities.focusMode,
|
|
567
|
+
hasFocusDistance: !!capabilities.focusDistance,
|
|
568
|
+
hasExposureControl: !!capabilities.exposureMode,
|
|
569
|
+
hasWhiteBalance: !!capabilities.whiteBalanceMode,
|
|
570
|
+
hasZoom: !!capabilities.zoom,
|
|
571
|
+
hasTorch: capabilities.torch !== undefined,
|
|
572
|
+
hasImageControls: !!(capabilities.brightness || capabilities.contrast || capabilities.saturation || capabilities.sharpness),
|
|
573
|
+
resolutionRange: capabilities.width && capabilities.height ?
|
|
574
|
+
`${capabilities.width.min}x${capabilities.height.min} - ${capabilities.width.max}x${capabilities.height.max}` : 'unknown'
|
|
575
|
+
};
|
|
576
|
+
}
|
|
577
|
+
// New method to enable torch/flash for better illumination
|
|
578
|
+
async setTorchEnabled(enabled, stream) {
|
|
579
|
+
try {
|
|
580
|
+
if (!stream) {
|
|
581
|
+
this.logger.warn('No hay stream disponible para controlar el flash');
|
|
582
|
+
return false;
|
|
583
|
+
}
|
|
584
|
+
const videoTrack = stream.getVideoTracks()[0];
|
|
585
|
+
if (!videoTrack) {
|
|
586
|
+
this.logger.warn('No hay track de video disponible');
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
const capabilities = videoTrack.getCapabilities();
|
|
590
|
+
if (capabilities.torch === undefined) {
|
|
591
|
+
this.logger.warn('El dispositivo no soporta control de flash');
|
|
592
|
+
return false;
|
|
593
|
+
}
|
|
594
|
+
await videoTrack.applyConstraints({
|
|
595
|
+
advanced: [{ torch: enabled }]
|
|
596
|
+
});
|
|
597
|
+
this.logger.state('FLASH_CONTROLADO', { enabled });
|
|
598
|
+
return true;
|
|
599
|
+
}
|
|
600
|
+
catch (error) {
|
|
601
|
+
this.logger.error('Error al controlar el flash:', error);
|
|
602
|
+
return false;
|
|
603
|
+
}
|
|
604
|
+
}
|
|
605
|
+
// Method to manually trigger focus on a specific point
|
|
606
|
+
async focusAtPoint(x, y, stream) {
|
|
607
|
+
try {
|
|
608
|
+
if (!stream) {
|
|
609
|
+
this.logger.warn('No hay stream disponible para enfocar');
|
|
610
|
+
return false;
|
|
611
|
+
}
|
|
612
|
+
const videoTrack = stream.getVideoTracks()[0];
|
|
613
|
+
if (!videoTrack) {
|
|
614
|
+
this.logger.warn('No hay track de video disponible');
|
|
615
|
+
return false;
|
|
616
|
+
}
|
|
617
|
+
const capabilities = videoTrack.getCapabilities();
|
|
618
|
+
if (!capabilities.focusMode || !capabilities.focusMode.includes('single-shot')) {
|
|
619
|
+
this.logger.warn('El dispositivo no soporta enfoque manual');
|
|
620
|
+
return false;
|
|
621
|
+
}
|
|
622
|
+
// Trigger single-shot focus
|
|
623
|
+
await videoTrack.applyConstraints({
|
|
624
|
+
advanced: [{ focusMode: 'single-shot' }]
|
|
625
|
+
});
|
|
626
|
+
// Return to continuous focus after a short delay
|
|
627
|
+
setTimeout(async () => {
|
|
628
|
+
try {
|
|
629
|
+
await videoTrack.applyConstraints({
|
|
630
|
+
advanced: [{ focusMode: 'continuous' }]
|
|
631
|
+
});
|
|
632
|
+
}
|
|
633
|
+
catch (error) {
|
|
634
|
+
this.logger.warn('Error al volver a enfoque continuo:', error);
|
|
635
|
+
}
|
|
636
|
+
}, 1000);
|
|
637
|
+
this.logger.state('ENFOQUE_MANUAL_ACTIVADO', { x, y });
|
|
638
|
+
return true;
|
|
639
|
+
}
|
|
640
|
+
catch (error) {
|
|
641
|
+
this.logger.error('Error al enfocar manualmente:', error);
|
|
642
|
+
return false;
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
class LowMemoryDeviceStrategy {
|
|
648
|
+
getDeviceInfo() {
|
|
649
|
+
const nav = navigator;
|
|
650
|
+
const memory = nav.deviceMemory || nav.hardwareConcurrency || 4;
|
|
651
|
+
const connection = nav.connection || nav.mozConnection || nav.webkitConnection;
|
|
652
|
+
const isSlowConnection = connection && (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g');
|
|
653
|
+
return {
|
|
654
|
+
estimatedRAM: memory,
|
|
655
|
+
isLowMemory: true,
|
|
656
|
+
isSlowConnection: isSlowConnection
|
|
657
|
+
};
|
|
658
|
+
}
|
|
659
|
+
getSessionOptions(_debug) {
|
|
660
|
+
return {
|
|
661
|
+
executionProviders: ['wasm'],
|
|
662
|
+
graphOptimizationLevel: 'basic',
|
|
663
|
+
logSeverityLevel: 4,
|
|
664
|
+
logVerbosityLevel: 0,
|
|
665
|
+
enableCpuMemArena: false,
|
|
666
|
+
enableMemPattern: false,
|
|
667
|
+
executionMode: 'sequential',
|
|
668
|
+
interOpNumThreads: 1,
|
|
669
|
+
intraOpNumThreads: 1,
|
|
670
|
+
};
|
|
671
|
+
}
|
|
672
|
+
shouldUseSequentialLoading() {
|
|
673
|
+
return true;
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
|
|
677
|
+
class HighPerformanceDeviceStrategy {
|
|
678
|
+
getDeviceInfo() {
|
|
679
|
+
const nav = navigator;
|
|
680
|
+
const memory = nav.deviceMemory || nav.hardwareConcurrency || 4;
|
|
681
|
+
const connection = nav.connection || nav.mozConnection || nav.webkitConnection;
|
|
682
|
+
const isSlowConnection = connection && (connection.effectiveType === 'slow-2g' || connection.effectiveType === '2g');
|
|
683
|
+
return {
|
|
684
|
+
estimatedRAM: memory,
|
|
685
|
+
isLowMemory: false,
|
|
686
|
+
isSlowConnection: isSlowConnection
|
|
687
|
+
};
|
|
688
|
+
}
|
|
689
|
+
getSessionOptions(debug) {
|
|
690
|
+
return {
|
|
691
|
+
executionProviders: ['webgl', 'wasm'],
|
|
692
|
+
graphOptimizationLevel: 'all',
|
|
693
|
+
logSeverityLevel: debug ? 2 : 4,
|
|
694
|
+
logVerbosityLevel: 0,
|
|
695
|
+
enableCpuMemArena: true,
|
|
696
|
+
enableMemPattern: true,
|
|
697
|
+
executionMode: 'parallel',
|
|
698
|
+
interOpNumThreads: 2,
|
|
699
|
+
intraOpNumThreads: 2,
|
|
700
|
+
};
|
|
701
|
+
}
|
|
702
|
+
shouldUseSequentialLoading() {
|
|
703
|
+
return false;
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
|
|
707
|
+
class DeviceStrategyFactory {
|
|
708
|
+
static createStrategy() {
|
|
709
|
+
const nav = navigator;
|
|
710
|
+
const memory = nav.deviceMemory || nav.hardwareConcurrency || 4;
|
|
711
|
+
const isLowMemory = memory <= 4;
|
|
712
|
+
if (isLowMemory) {
|
|
713
|
+
return new LowMemoryDeviceStrategy();
|
|
714
|
+
}
|
|
715
|
+
else {
|
|
716
|
+
return new HighPerformanceDeviceStrategy();
|
|
717
|
+
}
|
|
718
|
+
}
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
class DetectionService {
|
|
722
|
+
logger;
|
|
723
|
+
debug;
|
|
724
|
+
useDocumentClassification;
|
|
725
|
+
session;
|
|
726
|
+
mobileNetSession;
|
|
727
|
+
mobileNetClassMap;
|
|
728
|
+
modelLoaded = false;
|
|
729
|
+
deviceStrategy;
|
|
730
|
+
MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/ddmyp-v2.onnx";
|
|
731
|
+
MOBILENET_MODEL_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.onnx";
|
|
732
|
+
MOBILENET_CLASSES_PATH = "https://storage.googleapis.com/jaak-static/web/component/stamps/cdmmp-v1.json";
|
|
733
|
+
INPUT_SIZE = 320;
|
|
734
|
+
CONFIDENCE_THRESHOLD = 0.6;
|
|
735
|
+
// Canvas pool for optimization
|
|
736
|
+
preprocessCanvas;
|
|
737
|
+
preprocessCtx;
|
|
738
|
+
captureCanvas;
|
|
739
|
+
constructor(logger, debug = false, useDocumentClassification = false) {
|
|
740
|
+
this.logger = logger;
|
|
741
|
+
this.debug = debug;
|
|
742
|
+
this.useDocumentClassification = useDocumentClassification;
|
|
743
|
+
this.deviceStrategy = DeviceStrategyFactory.createStrategy();
|
|
744
|
+
this.initializeCanvasPool();
|
|
745
|
+
}
|
|
746
|
+
async loadModel() {
|
|
747
|
+
if (this.modelLoaded || this.session) {
|
|
748
|
+
this.logger.state('MODELO_YA_PRECARGADO', {
|
|
749
|
+
sessionExists: !!this.session,
|
|
750
|
+
modelPreloaded: this.modelLoaded
|
|
751
|
+
});
|
|
752
|
+
return;
|
|
753
|
+
}
|
|
754
|
+
try {
|
|
755
|
+
this.logger.state('PRECARGANDO_MODELO_DETECCION', { modelPath: this.MODEL_PATH });
|
|
756
|
+
const sessionOptions = this.deviceStrategy.getSessionOptions(this.debug);
|
|
757
|
+
try {
|
|
758
|
+
this.session = await window.ort.InferenceSession.create(this.MODEL_PATH, sessionOptions);
|
|
759
|
+
}
|
|
760
|
+
catch (error) {
|
|
761
|
+
if (error.message.includes('failed to allocate a buffer')) {
|
|
762
|
+
this.logger.warn('Fallo en asignación de buffer durante precarga, intentando con configuración mínima');
|
|
763
|
+
const fallbackOptions = {
|
|
764
|
+
executionProviders: ['wasm'],
|
|
765
|
+
graphOptimizationLevel: 'disabled',
|
|
766
|
+
logSeverityLevel: 4,
|
|
767
|
+
enableCpuMemArena: false,
|
|
768
|
+
enableMemPattern: false,
|
|
769
|
+
executionMode: 'sequential',
|
|
770
|
+
interOpNumThreads: 1,
|
|
771
|
+
intraOpNumThreads: 1,
|
|
772
|
+
};
|
|
773
|
+
this.session = await window.ort.InferenceSession.create(this.MODEL_PATH, fallbackOptions);
|
|
774
|
+
}
|
|
775
|
+
else {
|
|
776
|
+
throw error;
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
this.modelLoaded = true;
|
|
780
|
+
this.logger.state('MODELO_DETECCION_CARGADO_EXITOSAMENTE', { sessionCreated: !!this.session });
|
|
781
|
+
}
|
|
782
|
+
catch (error) {
|
|
783
|
+
this.logger.error('Error al precargar modelo de detección:', error);
|
|
784
|
+
throw error;
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
async loadClassificationModel() {
|
|
788
|
+
if (!this.useDocumentClassification) {
|
|
789
|
+
return;
|
|
790
|
+
}
|
|
791
|
+
try {
|
|
792
|
+
this.logger.state('CARGANDO_MODELO_MOBILENET', { path: this.MOBILENET_MODEL_PATH });
|
|
793
|
+
// Load class map
|
|
794
|
+
const classResponse = await fetch(this.MOBILENET_CLASSES_PATH);
|
|
795
|
+
if (!classResponse.ok) {
|
|
796
|
+
throw new Error(`Failed to load class map: ${this.MOBILENET_CLASSES_PATH}`);
|
|
797
|
+
}
|
|
798
|
+
this.mobileNetClassMap = await classResponse.json();
|
|
799
|
+
this.logger.state('CLASES_MOBILENET_CARGADAS', {
|
|
800
|
+
classCount: Object.keys(this.mobileNetClassMap).length
|
|
801
|
+
});
|
|
802
|
+
// Load model
|
|
803
|
+
const sessionOptions = this.deviceStrategy.getSessionOptions(this.debug);
|
|
804
|
+
try {
|
|
805
|
+
this.mobileNetSession = await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, sessionOptions);
|
|
806
|
+
}
|
|
807
|
+
catch (error) {
|
|
808
|
+
if (error.message.includes('failed to allocate a buffer')) {
|
|
809
|
+
this.logger.warn('Fallo en asignación de buffer de MobileNet, intentando con configuración mínima');
|
|
810
|
+
const fallbackOptions = {
|
|
811
|
+
executionProviders: ['wasm'],
|
|
812
|
+
graphOptimizationLevel: 'disabled',
|
|
813
|
+
logSeverityLevel: 4,
|
|
814
|
+
enableCpuMemArena: false,
|
|
815
|
+
enableMemPattern: false,
|
|
816
|
+
executionMode: 'sequential',
|
|
817
|
+
interOpNumThreads: 1,
|
|
818
|
+
intraOpNumThreads: 1,
|
|
819
|
+
};
|
|
820
|
+
this.mobileNetSession = await window.ort.InferenceSession.create(this.MOBILENET_MODEL_PATH, fallbackOptions);
|
|
821
|
+
}
|
|
822
|
+
else {
|
|
823
|
+
throw error;
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
this.logger.state('MODELO_MOBILENET_CARGADO_EXITOSAMENTE', {
|
|
827
|
+
sessionCreated: !!this.mobileNetSession
|
|
828
|
+
});
|
|
829
|
+
}
|
|
830
|
+
catch (error) {
|
|
831
|
+
this.logger.error('Error al cargar modelo MobileNet:', error);
|
|
832
|
+
throw error;
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
isModelLoaded() {
|
|
836
|
+
return this.modelLoaded && !!this.session;
|
|
837
|
+
}
|
|
838
|
+
preprocess(video) {
|
|
839
|
+
if (!this.preprocessCanvas || !this.preprocessCtx) {
|
|
840
|
+
this.initializeCanvasPool();
|
|
841
|
+
}
|
|
842
|
+
this.preprocessCtx.clearRect(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
|
|
843
|
+
this.preprocessCtx.drawImage(video, 0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
|
|
844
|
+
const imageData = this.preprocessCtx.getImageData(0, 0, this.INPUT_SIZE, this.INPUT_SIZE);
|
|
845
|
+
const [R, G, B] = [[], [], []];
|
|
846
|
+
const { data } = imageData;
|
|
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);
|
|
851
|
+
}
|
|
852
|
+
const transposedData = new Float32Array(R.concat(G, B));
|
|
853
|
+
const float16Data = new Uint16Array(transposedData.length);
|
|
854
|
+
for (let i = 0; i < transposedData.length; i++) {
|
|
855
|
+
float16Data[i] = this.float32ToFloat16(transposedData[i]);
|
|
856
|
+
}
|
|
857
|
+
return new window.ort.Tensor("float16", float16Data, [1, 3, this.INPUT_SIZE, this.INPUT_SIZE]);
|
|
858
|
+
}
|
|
859
|
+
async runInference(inputTensor) {
|
|
860
|
+
if (!this.session) {
|
|
861
|
+
throw new Error('Detection model not loaded');
|
|
862
|
+
}
|
|
863
|
+
const feeds = { [this.session.inputNames[0]]: inputTensor };
|
|
864
|
+
const results = await this.session.run(feeds);
|
|
865
|
+
const output = results[this.session.outputNames[0]].data;
|
|
866
|
+
const detections = [];
|
|
867
|
+
for (let i = 0; i < output.length; i += 6) {
|
|
868
|
+
const [x1, y1, x2, y2, score, classId] = output.slice(i, i + 6);
|
|
869
|
+
if (score > this.CONFIDENCE_THRESHOLD) {
|
|
870
|
+
detections.push({
|
|
871
|
+
x: x1,
|
|
872
|
+
y: y1,
|
|
873
|
+
w: x2 - x1,
|
|
874
|
+
h: y2 - y1,
|
|
875
|
+
score,
|
|
876
|
+
classId
|
|
877
|
+
});
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
return detections;
|
|
881
|
+
}
|
|
882
|
+
async classifyDocument(canvas) {
|
|
883
|
+
if (!this.mobileNetSession || !this.mobileNetClassMap) {
|
|
884
|
+
this.logger.warn('Modelo MobileNet no está cargado, saltando clasificación');
|
|
885
|
+
return null;
|
|
886
|
+
}
|
|
887
|
+
try {
|
|
888
|
+
this.logger.state('CLASIFICANDO_DOCUMENTO', { timestamp: Date.now() });
|
|
889
|
+
const inputTensor = this.preprocessMobileNet(canvas);
|
|
890
|
+
const feeds = { input: inputTensor };
|
|
891
|
+
const results = await this.mobileNetSession.run(feeds);
|
|
892
|
+
const output = results[Object.keys(results)[0]].data;
|
|
893
|
+
const maxIdx = output.reduce((bestIdx, val, idx, arr) => val > arr[bestIdx] ? idx : bestIdx, 0);
|
|
894
|
+
const confidence = output[maxIdx];
|
|
895
|
+
const className = this.mobileNetClassMap[maxIdx.toString()] || "unknown";
|
|
896
|
+
this.logger.state('DOCUMENTO_CLASIFICADO', {
|
|
897
|
+
class: className,
|
|
898
|
+
confidence: confidence.toFixed(3),
|
|
899
|
+
classIndex: maxIdx,
|
|
900
|
+
timestamp: Date.now()
|
|
901
|
+
});
|
|
902
|
+
return {
|
|
903
|
+
class: className,
|
|
904
|
+
confidence: confidence,
|
|
905
|
+
classIndex: maxIdx
|
|
294
906
|
};
|
|
295
|
-
localStorage.setItem('jaak-stamps-camera-preference', JSON.stringify(preference));
|
|
296
|
-
this.debugLog('💾 Saved camera preference:', preference);
|
|
297
907
|
}
|
|
298
908
|
catch (error) {
|
|
299
|
-
this.
|
|
909
|
+
this.logger.error('Error al clasificar documento:', error);
|
|
910
|
+
return null;
|
|
911
|
+
}
|
|
912
|
+
}
|
|
913
|
+
checkSideAlignment(box, maskConfig) {
|
|
914
|
+
const { INPUT_SIZE, ID1_ASPECT_RATIO, shouldMirrorVideo, alignmentTolerance, maskSize, videoRef } = maskConfig;
|
|
915
|
+
if (!videoRef) {
|
|
916
|
+
return { top: false, right: false, bottom: false, left: false };
|
|
917
|
+
}
|
|
918
|
+
// Get video dimensions to calculate actual mask boundaries in model space
|
|
919
|
+
const videoWidth = videoRef.videoWidth;
|
|
920
|
+
const videoHeight = videoRef.videoHeight;
|
|
921
|
+
if (videoWidth === 0 || videoHeight === 0) {
|
|
922
|
+
return { top: false, right: false, bottom: false, left: false };
|
|
923
|
+
}
|
|
924
|
+
// Calculate video aspect ratio
|
|
925
|
+
const videoAspectRatio = videoWidth / videoHeight;
|
|
926
|
+
// The model sees video stretched to 320x320, but we need to calculate where
|
|
927
|
+
// the mask should be in this distorted space to match the visual mask
|
|
928
|
+
// In the visual display, we calculate mask size based on the limiting dimension
|
|
929
|
+
// We need to replicate this logic but account for the distortion in model space
|
|
930
|
+
// Calculate the "display" dimensions (what the visual mask calculations use)
|
|
931
|
+
const containerAspectRatio = 1; // Assume square container for simplicity
|
|
932
|
+
let displayedVideoWidth, displayedVideoHeight;
|
|
933
|
+
if (videoAspectRatio > containerAspectRatio) {
|
|
934
|
+
// Video is wider - letterboxed in display
|
|
935
|
+
displayedVideoWidth = INPUT_SIZE;
|
|
936
|
+
displayedVideoHeight = INPUT_SIZE / videoAspectRatio;
|
|
937
|
+
}
|
|
938
|
+
else {
|
|
939
|
+
// Video is taller - pillarboxed in display
|
|
940
|
+
displayedVideoHeight = INPUT_SIZE;
|
|
941
|
+
displayedVideoWidth = INPUT_SIZE * videoAspectRatio;
|
|
942
|
+
}
|
|
943
|
+
// Calculate mask dimensions using the same logic as updateMaskDimensions
|
|
944
|
+
const maxWidthByHeight = displayedVideoHeight * ID1_ASPECT_RATIO;
|
|
945
|
+
let visualMaskWidth, visualMaskHeight;
|
|
946
|
+
const sizeRatio = maskSize / 100;
|
|
947
|
+
if (maxWidthByHeight <= displayedVideoWidth) {
|
|
948
|
+
// Video height is the limiting factor
|
|
949
|
+
visualMaskHeight = displayedVideoHeight * sizeRatio;
|
|
950
|
+
visualMaskWidth = visualMaskHeight * ID1_ASPECT_RATIO;
|
|
951
|
+
}
|
|
952
|
+
else {
|
|
953
|
+
// Video width is the limiting factor
|
|
954
|
+
visualMaskWidth = displayedVideoWidth * sizeRatio;
|
|
955
|
+
visualMaskHeight = visualMaskWidth / ID1_ASPECT_RATIO;
|
|
956
|
+
}
|
|
957
|
+
// Now map these visual mask dimensions to the distorted model space
|
|
958
|
+
// The model stretches video to 320x320, so we need to apply the inverse transformation
|
|
959
|
+
const modelMaskWidth = visualMaskWidth * (INPUT_SIZE / displayedVideoWidth);
|
|
960
|
+
const modelMaskHeight = visualMaskHeight * (INPUT_SIZE / displayedVideoHeight);
|
|
961
|
+
// Calculate mask boundaries in model coordinate system (always centered in 320x320)
|
|
962
|
+
const maskCenterX = INPUT_SIZE / 2;
|
|
963
|
+
const maskCenterY = INPUT_SIZE / 2;
|
|
964
|
+
const maskLeft = maskCenterX - (modelMaskWidth / 2);
|
|
965
|
+
const maskRight = maskCenterX + (modelMaskWidth / 2);
|
|
966
|
+
const maskTop = maskCenterY - (modelMaskHeight / 2);
|
|
967
|
+
const maskBottom = maskCenterY + (modelMaskHeight / 2);
|
|
968
|
+
// Obtener las coordenadas del documento detectado
|
|
969
|
+
let docLeft = box.x;
|
|
970
|
+
let docRight = box.x + box.w;
|
|
971
|
+
const docTop = box.y;
|
|
972
|
+
const docBottom = box.y + box.h;
|
|
973
|
+
// Si el video está en modo mirror, invertir las coordenadas horizontales
|
|
974
|
+
if (shouldMirrorVideo) {
|
|
975
|
+
const originalDocLeft = docLeft;
|
|
976
|
+
const originalDocRight = docRight;
|
|
977
|
+
docLeft = INPUT_SIZE - originalDocRight;
|
|
978
|
+
docRight = INPUT_SIZE - originalDocLeft;
|
|
979
|
+
}
|
|
980
|
+
// Tolerancia para considerar que un lado está alineado (en píxeles)
|
|
981
|
+
const tolerance = alignmentTolerance;
|
|
982
|
+
// Verificar alineación de esquinas más estricta
|
|
983
|
+
// Una esquina está alineada solo si AMBOS bordes que la forman están alineados
|
|
984
|
+
const topAligned = Math.abs(docTop - maskTop) <= tolerance;
|
|
985
|
+
const rightAligned = Math.abs(docRight - maskRight) <= tolerance;
|
|
986
|
+
const bottomAligned = Math.abs(docBottom - maskBottom) <= tolerance;
|
|
987
|
+
const leftAligned = Math.abs(docLeft - maskLeft) <= tolerance;
|
|
988
|
+
return {
|
|
989
|
+
top: topAligned && leftAligned, // Esquina superior izquierda: borde top Y left alineados
|
|
990
|
+
right: topAligned && rightAligned, // Esquina superior derecha: borde top Y right alineados
|
|
991
|
+
bottom: bottomAligned && leftAligned, // Esquina inferior izquierda: borde bottom Y left alineados
|
|
992
|
+
left: bottomAligned && rightAligned // Esquina inferior derecha: borde bottom Y right alineados
|
|
993
|
+
};
|
|
994
|
+
}
|
|
995
|
+
isCardInFrame(box) {
|
|
996
|
+
const cardCenterX = box.x + box.w / 2;
|
|
997
|
+
const cardCenterY = box.y + box.h / 2;
|
|
998
|
+
const frameCenterX = this.INPUT_SIZE / 2;
|
|
999
|
+
const frameCenterY = this.INPUT_SIZE / 2;
|
|
1000
|
+
const toleranceX = 40;
|
|
1001
|
+
const toleranceY = 30;
|
|
1002
|
+
const isCentered = Math.abs(cardCenterX - frameCenterX) < toleranceX &&
|
|
1003
|
+
Math.abs(cardCenterY - frameCenterY) < toleranceY;
|
|
1004
|
+
const isGoodSize = box.w > 150 && box.w < 300 && box.h > 90 && box.h < 200;
|
|
1005
|
+
return isCentered && isGoodSize;
|
|
1006
|
+
}
|
|
1007
|
+
areAllSidesAligned(alignment) {
|
|
1008
|
+
return alignment.top && alignment.right && alignment.bottom && alignment.left;
|
|
1009
|
+
}
|
|
1010
|
+
cleanup() {
|
|
1011
|
+
this.cleanupCanvasPool();
|
|
1012
|
+
if (this.session) {
|
|
1013
|
+
this.session.release?.();
|
|
1014
|
+
this.session = undefined;
|
|
1015
|
+
}
|
|
1016
|
+
if (this.mobileNetSession) {
|
|
1017
|
+
this.mobileNetSession.release?.();
|
|
1018
|
+
this.mobileNetSession = undefined;
|
|
1019
|
+
}
|
|
1020
|
+
this.mobileNetClassMap = undefined;
|
|
1021
|
+
this.modelLoaded = false;
|
|
1022
|
+
this.logger.state('DETECCION_SERVICE_LIMPIADO', { timestamp: Date.now() });
|
|
1023
|
+
}
|
|
1024
|
+
initializeCanvasPool() {
|
|
1025
|
+
this.preprocessCanvas = document.createElement('canvas');
|
|
1026
|
+
this.preprocessCanvas.width = this.INPUT_SIZE;
|
|
1027
|
+
this.preprocessCanvas.height = this.INPUT_SIZE;
|
|
1028
|
+
this.preprocessCtx = this.preprocessCanvas.getContext('2d', {
|
|
1029
|
+
alpha: false,
|
|
1030
|
+
willReadFrequently: true
|
|
1031
|
+
});
|
|
1032
|
+
this.captureCanvas = document.createElement('canvas');
|
|
1033
|
+
this.logger.state('CANVAS_POOL_INICIALIZADO', {
|
|
1034
|
+
preprocessCanvasSize: this.INPUT_SIZE
|
|
1035
|
+
});
|
|
1036
|
+
}
|
|
1037
|
+
cleanupCanvasPool() {
|
|
1038
|
+
if (this.preprocessCanvas) {
|
|
1039
|
+
this.preprocessCtx = undefined;
|
|
1040
|
+
this.preprocessCanvas = undefined;
|
|
1041
|
+
}
|
|
1042
|
+
if (this.captureCanvas) {
|
|
1043
|
+
this.captureCanvas = undefined;
|
|
1044
|
+
}
|
|
1045
|
+
}
|
|
1046
|
+
float32ToFloat16(value) {
|
|
1047
|
+
const buffer = new ArrayBuffer(4);
|
|
1048
|
+
const view = new DataView(buffer);
|
|
1049
|
+
view.setFloat32(0, value, true);
|
|
1050
|
+
const f = view.getUint32(0, true);
|
|
1051
|
+
const sign = (f >> 31) & 0x1;
|
|
1052
|
+
const exp = (f >> 23) & 0xFF;
|
|
1053
|
+
const frac = f & 0x7FFFFF;
|
|
1054
|
+
let newExp = exp - 127 + 15;
|
|
1055
|
+
if (exp === 0) {
|
|
1056
|
+
newExp = 0;
|
|
1057
|
+
}
|
|
1058
|
+
else if (exp === 0xFF) {
|
|
1059
|
+
newExp = 0x1F;
|
|
1060
|
+
}
|
|
1061
|
+
else if (newExp >= 0x1F) {
|
|
1062
|
+
newExp = 0x1F;
|
|
1063
|
+
return (sign << 15) | (newExp << 10);
|
|
1064
|
+
}
|
|
1065
|
+
else if (newExp <= 0) {
|
|
1066
|
+
return (sign << 15);
|
|
1067
|
+
}
|
|
1068
|
+
return (sign << 15) | (newExp << 10) | (frac >> 13);
|
|
1069
|
+
}
|
|
1070
|
+
preprocessMobileNet(canvas) {
|
|
1071
|
+
const tempCanvas = document.createElement('canvas');
|
|
1072
|
+
tempCanvas.width = 224;
|
|
1073
|
+
tempCanvas.height = 224;
|
|
1074
|
+
const tempCtx = tempCanvas.getContext('2d');
|
|
1075
|
+
tempCtx.drawImage(canvas, 0, 0, 224, 224);
|
|
1076
|
+
const imageData = tempCtx.getImageData(0, 0, 224, 224);
|
|
1077
|
+
const data = imageData.data;
|
|
1078
|
+
const hw = 224 * 224;
|
|
1079
|
+
const arr = new Float32Array(3 * hw);
|
|
1080
|
+
for (let i = 0; i < hw; i++) {
|
|
1081
|
+
arr[i] = (data[i * 4 + 0] / 255 - 0.5) / 0.5;
|
|
1082
|
+
arr[hw + i] = (data[i * 4 + 1] / 255 - 0.5) / 0.5;
|
|
1083
|
+
arr[2 * hw + i] = (data[i * 4 + 2] / 255 - 0.5) / 0.5;
|
|
1084
|
+
}
|
|
1085
|
+
return new window.ort.Tensor('float32', arr, [1, 3, 224, 224]);
|
|
1086
|
+
}
|
|
1087
|
+
}
|
|
1088
|
+
|
|
1089
|
+
class ServiceContainer {
|
|
1090
|
+
services = new Map();
|
|
1091
|
+
constructor(config) {
|
|
1092
|
+
this.initializeServices(config);
|
|
1093
|
+
}
|
|
1094
|
+
initializeServices(config) {
|
|
1095
|
+
// Initialize services in dependency order
|
|
1096
|
+
const eventBus = new EventBusService();
|
|
1097
|
+
const logger = new LoggerService(config.debug);
|
|
1098
|
+
const stateManager = new StateManagerService(eventBus);
|
|
1099
|
+
const cameraService = new CameraService(logger, eventBus, config.preferredCamera);
|
|
1100
|
+
const detectionService = new DetectionService(logger, config.debug, config.useDocumentClassification);
|
|
1101
|
+
// Register services
|
|
1102
|
+
this.services.set('eventBus', eventBus);
|
|
1103
|
+
this.services.set('logger', logger);
|
|
1104
|
+
this.services.set('stateManager', stateManager);
|
|
1105
|
+
this.services.set('cameraService', cameraService);
|
|
1106
|
+
this.services.set('detectionService', detectionService);
|
|
1107
|
+
}
|
|
1108
|
+
get(serviceName) {
|
|
1109
|
+
const service = this.services.get(serviceName);
|
|
1110
|
+
if (!service) {
|
|
1111
|
+
throw new Error(`Service ${serviceName} not found`);
|
|
1112
|
+
}
|
|
1113
|
+
return service;
|
|
1114
|
+
}
|
|
1115
|
+
getLogger() {
|
|
1116
|
+
return this.get('logger');
|
|
1117
|
+
}
|
|
1118
|
+
getEventBus() {
|
|
1119
|
+
return this.get('eventBus');
|
|
1120
|
+
}
|
|
1121
|
+
getStateManager() {
|
|
1122
|
+
return this.get('stateManager');
|
|
1123
|
+
}
|
|
1124
|
+
getCameraService() {
|
|
1125
|
+
return this.get('cameraService');
|
|
1126
|
+
}
|
|
1127
|
+
getDetectionService() {
|
|
1128
|
+
return this.get('detectionService');
|
|
1129
|
+
}
|
|
1130
|
+
updateConfig(config) {
|
|
1131
|
+
if (config.debug !== undefined) {
|
|
1132
|
+
const logger = this.services.get('logger');
|
|
1133
|
+
logger.setDebugMode(config.debug);
|
|
1134
|
+
}
|
|
1135
|
+
}
|
|
1136
|
+
cleanup() {
|
|
1137
|
+
// Cleanup services in reverse order
|
|
1138
|
+
this.getDetectionService().cleanup();
|
|
1139
|
+
this.getEventBus().clear();
|
|
1140
|
+
this.services.clear();
|
|
1141
|
+
}
|
|
1142
|
+
}
|
|
1143
|
+
|
|
1144
|
+
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}}";
|
|
1145
|
+
|
|
1146
|
+
const JaakStamps$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H {
|
|
1147
|
+
constructor() {
|
|
1148
|
+
super();
|
|
1149
|
+
this.__registerHost();
|
|
1150
|
+
this.__attachShadow();
|
|
1151
|
+
this.captureCompleted = createEvent(this, "captureCompleted");
|
|
1152
|
+
this.isReady = createEvent(this, "isReady");
|
|
1153
|
+
}
|
|
1154
|
+
get el() { return 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();
|
|
300
1238
|
}
|
|
301
1239
|
}
|
|
302
|
-
async
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
}
|
|
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);
|
|
332
|
-
}
|
|
333
|
-
catch (error) {
|
|
334
|
-
this.debugLog('❌ Error switching camera:', error);
|
|
335
|
-
this.handleCameraPermissionError(error);
|
|
336
|
-
}
|
|
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() });
|
|
337
1257
|
}
|
|
338
|
-
async
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
this.handleCameraPermissionError(error);
|
|
349
|
-
throw error;
|
|
350
|
-
}
|
|
351
|
-
// Wait before retrying
|
|
352
|
-
await new Promise(resolve => setTimeout(resolve, 500 * attempt));
|
|
353
|
-
}
|
|
354
|
-
}
|
|
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);
|
|
1267
|
+
});
|
|
355
1268
|
}
|
|
356
|
-
|
|
357
|
-
this.
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
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
|
|
363
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();
|
|
364
1289
|
}
|
|
365
|
-
|
|
366
|
-
if (
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
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
|
+
}
|
|
372
1308
|
}
|
|
373
|
-
async
|
|
374
|
-
this.validateMaskSize();
|
|
375
|
-
this.validateCropMargin();
|
|
376
|
-
this.validatePreferredCamera();
|
|
377
|
-
await this.detectDeviceTypeAndCameras();
|
|
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
|
-
|
|
383
|
-
|
|
384
|
-
|
|
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
|
-
|
|
389
|
-
|
|
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
|
-
|
|
396
|
-
|
|
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.
|
|
1364
|
+
resizeObserver.observe(this.detectionContainer.parentElement);
|
|
401
1365
|
}
|
|
402
1366
|
}
|
|
403
1367
|
handleResize() {
|
|
404
|
-
if (this.
|
|
405
|
-
const container = this.
|
|
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.
|
|
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$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H
|
|
|
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
|
|
441
|
-
|
|
442
|
-
|
|
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 *
|
|
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 /
|
|
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$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H
|
|
|
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.
|
|
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$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H
|
|
|
477
1431
|
offset: { x: videoOffsetX, y: videoOffsetY }
|
|
478
1432
|
});
|
|
479
1433
|
}
|
|
480
|
-
|
|
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
|
-
|
|
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.
|
|
1443
|
+
return this.stateManager.isProcessCompleted();
|
|
520
1444
|
}
|
|
521
1445
|
async startCapture() {
|
|
522
1446
|
await this.startDetection();
|
|
@@ -527,452 +1451,250 @@ const JaakStamps$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H
|
|
|
527
1451
|
async resetCapture() {
|
|
528
1452
|
this.resetDetection();
|
|
529
1453
|
}
|
|
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
1454
|
async skipBackCapture() {
|
|
575
|
-
|
|
1455
|
+
const captureState = this.stateManager.getCaptureState();
|
|
1456
|
+
const capturedImages = this.stateManager.getCapturedImages();
|
|
1457
|
+
if (captureState.step === 'back' && capturedImages.front.fullFrame) {
|
|
576
1458
|
this.completeProcess(true);
|
|
577
1459
|
}
|
|
578
1460
|
}
|
|
579
|
-
async
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
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;
|
|
798
|
-
}
|
|
799
|
-
}
|
|
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
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
this.
|
|
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 (
|
|
831
|
-
this.
|
|
832
|
-
this.
|
|
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
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
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
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
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
|
-
|
|
853
|
-
|
|
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
|
-
|
|
1540
|
+
async setTorchEnabled(enabled) {
|
|
1541
|
+
const torchEnabled = await this.cameraService.setTorchEnabled(enabled, this.videoStream);
|
|
856
1542
|
return {
|
|
857
|
-
|
|
858
|
-
|
|
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
|
-
//
|
|
875
|
-
if (!this.
|
|
876
|
-
|
|
877
|
-
this.
|
|
878
|
-
this.
|
|
879
|
-
|
|
880
|
-
this.
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
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.
|
|
888
|
-
this.emitReadyEvent();
|
|
1572
|
+
this.logger.state('MODELOS_CARGADOS_EN_DETECCION', { loadTime: Math.round(loadTime) });
|
|
889
1573
|
}
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
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
|
-
|
|
896
|
-
await this.setupCamera();
|
|
1589
|
+
// Finalizar e iniciar captura
|
|
897
1590
|
this.startTime = Date.now();
|
|
898
|
-
this.isLoading
|
|
1591
|
+
this.stateManager.updateCaptureState({ isLoading: false });
|
|
899
1592
|
this.detectFrame();
|
|
900
1593
|
}
|
|
901
1594
|
catch (err) {
|
|
902
|
-
this.
|
|
903
|
-
this.
|
|
904
|
-
this.
|
|
905
|
-
|
|
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
|
-
|
|
1624
|
+
const frameStartTime = performance.now();
|
|
1625
|
+
const captureState = this.stateManager.getCaptureState();
|
|
1626
|
+
if (!this.videoRef || !this.detectionContainer || !this.detectionService.isModelLoaded())
|
|
911
1627
|
return;
|
|
912
|
-
|
|
913
|
-
|
|
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
|
-
//
|
|
1634
|
+
// Frame skipping for performance
|
|
921
1635
|
this.frameSkipCounter++;
|
|
922
1636
|
if (this.frameSkipCounter <= this.FRAME_SKIP) {
|
|
923
|
-
if (
|
|
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
|
-
//
|
|
1643
|
+
// Throttle inference
|
|
930
1644
|
const currentTime = Date.now();
|
|
931
1645
|
if (currentTime - this.lastInferenceTime < this.MIN_INFERENCE_INTERVAL) {
|
|
932
|
-
if (
|
|
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
|
-
|
|
939
|
-
const
|
|
940
|
-
const
|
|
941
|
-
|
|
942
|
-
const
|
|
943
|
-
const
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
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
|
-
//
|
|
959
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1691
|
+
const frameEndTime = performance.now();
|
|
1692
|
+
const totalFrameTime = frameEndTime - frameStartTime;
|
|
1693
|
+
this.recordFrameProcessing(totalFrameTime, detections.length);
|
|
968
1694
|
}
|
|
969
|
-
|
|
970
|
-
|
|
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$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H
|
|
|
981
1703
|
}
|
|
982
1704
|
}
|
|
983
1705
|
catch (e) {
|
|
984
|
-
this.
|
|
985
|
-
|
|
986
|
-
if (
|
|
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
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
|
|
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
|
-
|
|
1005
|
-
if (
|
|
1006
|
-
|
|
1007
|
-
|
|
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 (h("div", { key: '7af79a0ff25b51790a9477cd7b338a0584172fc2', class: "detector-container" }, h("div", { key: 'ebf6a3811e0e599f29e98325b975a645e3bfb5e0', class: "video-container" }, 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' } }), h("div", { key: 'b507c786eccbd21acdd884ef50bc6ec280b9d437', ref: el => this.detectionContainer = el, class: `detection-overlay ${this.shouldMirrorVideo ? 'mirror' : ''}` }, this.debug && this.detectionBoxes.map((box, index) => (h("div", { key: index, 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 && (h("div", { key: '53066c626b23daae351ea9a80409e8882434b0dd', class: "overlay-mask" }, h("div", { key: '77bb4048d43e328e57a5c7e1909e0a59c8957217', class: "card-outline" }, h("div", { key: 'ea0f2610d903f985286856ab69f8be24fd42148e', class: "side side-top" }), h("div", { key: 'dc671111ef4adf33aa41f4457fdf344ede23eb80', class: "side side-right" }), h("div", { key: '2475ec41577dca92b425542c8861c570ed7ecd3b', class: "side side-bottom" }), h("div", { key: 'a06171c8eb1bd6353a6464485604560d73ac04b7', class: "side side-left" }), !captureState.showFlipAnimation && !captureState.showSuccessAnimation && (h("div", { key: 'ecfd98f36d457fe7282b26f6a0efef5361380c76', class: "guide-text" }, "Alinee su identificaci\u00F3n con el marco"))), captureState.step === 'back' && !captureState.showFlipAnimation && !captureState.showSuccessAnimation && (h("button", { key: 'f3c7b66500110437e9e4a7442cb327f2fdc6d71f', class: "skip-button", onClick: () => this.skipBackCapture(), type: "button" }, "Saltar reverso")), captureState.isVideoActive && (h("div", { key: 'b5b2a8dfc6dbcf381c32c4caa562c27ced2e3e56', class: "camera-controls" }, 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 ? (h("div", { class: "button-spinner" })) : ('Cámaras')))), this.showCameraSelector && cameraInfo.availableCameras.length > 0 && (h("div", { key: '41feec90287510b08bd1090ad15586b323007c30', class: "camera-selector-dropdown" }, h("div", { key: '8310ebe3db842c463ad428b973f841053315a76f', class: "camera-selector-header" }, h("span", { key: '6693bdfa33643dfe73798d4f25b0c2d9de7aac7c' }, "Seleccionar C\u00E1mara"), h("button", { key: '8552d45e1482c570d7ff85588d4404eec7c369d7', class: "close-selector", onClick: () => this.toggleCameraSelector(), type: "button" }, "\u00D7")), h("div", { key: '5333ec0e5fb2c50a07a7c0b7d4dfb1bb4ee0df1c', class: "camera-list" }, cameraInfo.availableCameras.map((camera) => (h("button", { key: camera.id, class: `camera-option ${cameraInfo.selectedCameraId === camera.id ? 'selected' : ''}`, onClick: () => this.handleCameraSwitch(camera.id), type: "button" }, h("span", { class: "camera-label" }, camera.label || `Cámara ${cameraInfo.availableCameras.indexOf(camera) + 1}`), cameraInfo.selectedCameraId === camera.id && (h("span", { class: "selected-indicator" }, "\u2713")))))), h("div", { key: '8adf70b0e632c56a4784dec44621688809a3ff56', class: "device-info" }, h("small", { key: '2ea23922386ecda4a9011b50faba5efe4b4e60bb' }, "Dispositivo: ", cameraInfo.deviceType)))))), captureState.isCapturing && (h("div", { key: '8e693db67fe1e6ae8f11082b8993682b6d19b11d', class: "capture-animation" })), captureState.showFlipAnimation && (h("div", { key: '474489ed7848cdc163c492a5e19f5f13231e17b3', class: "flip-animation" }, h("div", { key: 'a9bd24ca21330882f001b7811077630eb1c30f50', class: "id-card-icon" }), h("div", { key: 'ffadb660a61e0f5e3e29bdc473d987e87dc4ad8a', class: "flip-text" }, "\u00A1Voltea tu identificaci\u00F3n!"))), captureState.showSuccessAnimation && (h("div", { key: 'd2522ee33aa159d49f040a293775892fb1cb81b5', class: "success-animation" }, h("div", { key: 'e7f899fac58bc9a3d51cf2cb89ee33bb320b241f', class: "check-icon" }), h("div", { key: 'd5d0ee1f37dbc659ca625ad03cbce325be0cf0a6', class: "success-text" }, "\u00A1Proceso completado!"))), h("div", { key: '425d347666032c3982a660ebee13b47670b996cb', class: `component-status status-${this.currentStatus.type}` }, (this.currentStatus.type === 'loading' || this.currentStatus.type === 'initializing') && (h("div", { key: '4d396fa107872f9a1e526fd59dc4edf279a05792', class: "status-spinner" })), h("div", { key: '232e9ae24c8cf5ef8ac0e3442e45a920799c724d', class: "status-content" }, h("div", { key: 'fe9dc0ca6d8e8276052bac7d2d44f1c7c9730364', class: "status-message" }, this.currentStatus.message), this.currentStatus.description && (h("div", { key: '6910c7ac78fd89e6fa1165446ec6d46fb356035c', class: "status-description" }, this.currentStatus.description)))), this.debug && (h("div", { key: '7282b8afaf03da53b01a23d04babd772528c3c14', class: "performance-monitor" }, h("div", { key: 'b582b3124fed13387cd70a02a34ab2bb541f3bfc', class: "performance-expanded" }, h("div", { key: '764bac2d61224b9a5f306f50934d410e1bd27787', class: "metrics-row" }, h("div", { key: '261563f8314a9f6069b1ac6362eb9c38936a9dc7', class: "metric-compact" }, h("span", { key: '4feea98eff86620c1bc90eb65d9799102423109d', class: "metric-label" }, "FPS"), h("span", { key: 'eb15f13b27b8aa50701ad3d11c4cf87200010b67', class: `metric-value ${this.performanceData.fps < 15 ? 'warning' : this.performanceData.fps < 10 ? 'danger' : 'good'}` }, this.performanceData.fps)), h("div", { key: '0813c35c2c33286f2276bfb5adce59b32c7bb597', class: "metric-compact" }, h("span", { key: '201e7bcb556e63b141e42a3ffc3419eb4284bfa8', class: "metric-label" }, "MEM"), h("span", { key: '4f6703cbe0128440d0f2f22f631035ab85422c64', class: `metric-value ${this.performanceData.memoryUsage > 100 ? 'warning' : this.performanceData.memoryUsage > 200 ? 'danger' : 'good'}` }, this.performanceData.memoryUsage, "MB"))), h("div", { key: '6343c361c93138b9ea66e8ae8acd361b93333f8c', class: "metrics-row" }, h("div", { key: 'd3c81fe597004bf380fae2d32f3a8314317e7769', class: "metric-compact" }, h("span", { key: 'fce572af3e200a611974dceef4da02f6aecedffc', class: "metric-label" }, "INF"), h("span", { key: '18dd78d54dcecfb70ddf59b782f87f8c6f208b0f', class: `metric-value ${this.performanceData.inferenceTime > 100 ? 'warning' : this.performanceData.inferenceTime > 200 ? 'danger' : 'good'}` }, this.performanceData.inferenceTime, "ms")), h("div", { key: '4c31ebfd835b017fd3e41b23d6bd9b19add511aa', class: "metric-compact" }, h("span", { key: '66b1a380b9479a8fc1e8c2385cb72aa4158dc74e', class: "metric-label" }, "FRAME"), h("span", { key: '3c6e41f7f11123c524d3a9df409345929d63f352', class: `metric-value ${this.performanceData.frameProcessingTime > 50 ? 'warning' : this.performanceData.frameProcessingTime > 100 ? 'danger' : 'good'}` }, this.performanceData.frameProcessingTime, "ms"))), h("div", { key: '3b522e2cdfe4bd9f1dd6eb0f91ee3577dc43e490', class: "metrics-row" }, h("div", { key: 'fa1e6f687b43aa2582b8b3426feb03a16c6493fc', class: "metric-compact" }, h("span", { key: 'a9355091e71a33a6a0d7cc6c11171dcda2e51b22', class: "metric-label" }, "DET"), h("span", { key: 'beca5a7ccf4853675cf8366bcf577ebfbd46c4f0', class: "metric-value good" }, this.performanceData.successfulDetections, "/", this.performanceData.totalDetections)), h("div", { key: '4b07fc9b3d35f99bc6e77c8726192cde0476a787', class: "metric-compact" }, h("span", { key: 'a1674b538f45328ee0afb00e582c07e0b4ccf553', class: "metric-label" }, "RATE"), h("span", { key: 'fd384a5137bc3df6c939d3d698a3ef80e9087030', class: `metric-value ${this.performanceData.detectionRate < 30 ? 'danger' : this.performanceData.detectionRate < 60 ? 'warning' : 'good'}` }, this.performanceData.detectionRate, "%")))))), h("div", { key: 'ebbaf15a0ad96e4da5bbf746c32d7a4abb51b973', class: "watermark" }, 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
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
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
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
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
|
-
|
|
1070
|
-
const
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
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$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H
|
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
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.
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
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
|
-
|
|
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
|
-
|
|
1141
|
-
this.
|
|
1142
|
-
this.
|
|
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
|
-
}
|
|
1176
|
-
else {
|
|
1177
|
-
// Video is taller - pillarboxed (black bars left/right)
|
|
1178
|
-
displayedVideoHeight = containerHeight;
|
|
1179
|
-
displayedVideoWidth = containerHeight * videoAspectRatio;
|
|
1180
|
-
videoOffsetX = (containerWidth - displayedVideoWidth) / 2;
|
|
1181
1880
|
}
|
|
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
|
-
|
|
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
|
-
//
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
this.captureCanvas.width
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
const
|
|
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
|
-
//
|
|
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
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
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
|
-
|
|
1233
|
-
if (
|
|
1234
|
-
|
|
1235
|
-
|
|
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
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
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.
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
this.
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
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
|
|
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
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
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
|
-
|
|
1302
|
-
|
|
1303
|
-
this.
|
|
1304
|
-
|
|
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.
|
|
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
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
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
|
-
|
|
1332
|
-
|
|
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
|
|
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
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
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
|
static get style() { return myComponentCss; }
|
|
1398
2132
|
}, [1, "jaak-stamps", {
|
|
@@ -1402,38 +2136,30 @@ const JaakStamps$1 = /*@__PURE__*/ proxyCustomElement(class JaakStamps extends H
|
|
|
1402
2136
|
"cropMargin": [2, "crop-margin"],
|
|
1403
2137
|
"useDocumentClassification": [4, "use-document-classification"],
|
|
1404
2138
|
"preferredCamera": [1, "preferred-camera"],
|
|
1405
|
-
"
|
|
1406
|
-
"
|
|
1407
|
-
"statusColor": [32],
|
|
1408
|
-
"bestScore": [32],
|
|
1409
|
-
"capturedFullFrame": [32],
|
|
1410
|
-
"capturedCroppedId": [32],
|
|
1411
|
-
"capturedBackFullFrame": [32],
|
|
1412
|
-
"capturedBackCroppedId": [32],
|
|
1413
|
-
"captureStep": [32],
|
|
1414
|
-
"isCapturing": [32],
|
|
1415
|
-
"showFlipAnimation": [32],
|
|
1416
|
-
"showSuccessAnimation": [32],
|
|
1417
|
-
"shouldMirrorVideo": [32],
|
|
2139
|
+
"captureDelay": [2, "capture-delay"],
|
|
2140
|
+
"detectionBoxes": [32],
|
|
1418
2141
|
"sideAlignment": [32],
|
|
1419
|
-
"isDetectionPaused": [32],
|
|
1420
|
-
"isLoading": [32],
|
|
1421
|
-
"isModelPreloaded": [32],
|
|
1422
2142
|
"isMaskReady": [32],
|
|
1423
|
-
"
|
|
1424
|
-
"selectedCameraId": [32],
|
|
2143
|
+
"shouldMirrorVideo": [32],
|
|
1425
2144
|
"showCameraSelector": [32],
|
|
1426
|
-
"
|
|
2145
|
+
"isSwitchingCamera": [32],
|
|
2146
|
+
"hasDocumentDetected": [32],
|
|
2147
|
+
"currentStatus": [32],
|
|
2148
|
+
"performanceData": [32],
|
|
1427
2149
|
"getCapturedImages": [64],
|
|
1428
2150
|
"isProcessCompleted": [64],
|
|
1429
2151
|
"startCapture": [64],
|
|
1430
2152
|
"stopCapture": [64],
|
|
1431
2153
|
"resetCapture": [64],
|
|
2154
|
+
"skipBackCapture": [64],
|
|
1432
2155
|
"getStatus": [64],
|
|
1433
2156
|
"preloadModel": [64],
|
|
1434
|
-
"skipBackCapture": [64],
|
|
1435
2157
|
"getCameraInfo": [64],
|
|
1436
|
-
"setPreferredCamera": [64]
|
|
2158
|
+
"setPreferredCamera": [64],
|
|
2159
|
+
"setCaptureDelay": [64],
|
|
2160
|
+
"getCaptureDelay": [64],
|
|
2161
|
+
"setTorchEnabled": [64],
|
|
2162
|
+
"focusAtPoint": [64]
|
|
1437
2163
|
}]);
|
|
1438
2164
|
function defineCustomElement$1() {
|
|
1439
2165
|
if (typeof customElements === "undefined") {
|