@idmission/websdk-core 0.2.0-rc.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (82) hide show
  1. package/README.md +8 -1
  2. package/dist/client/IdmissionClient.d.ts +2 -0
  3. package/dist/client/IdmissionClient.d.ts.map +1 -1
  4. package/dist/client/IdmissionClient.js +3 -0
  5. package/dist/client/artifacts.d.ts +2 -0
  6. package/dist/client/artifacts.d.ts.map +1 -1
  7. package/dist/client/payload.d.ts.map +1 -1
  8. package/dist/client/payload.js +2 -1
  9. package/dist/client/types.d.ts +2 -0
  10. package/dist/client/types.d.ts.map +1 -1
  11. package/dist/documentCapture/autoCaptureEngine.d.ts +106 -0
  12. package/dist/documentCapture/autoCaptureEngine.d.ts.map +1 -0
  13. package/dist/documentCapture/autoCaptureEngine.js +456 -0
  14. package/dist/documentCapture/autoCaptureGeometry.d.ts +424 -0
  15. package/dist/documentCapture/autoCaptureGeometry.d.ts.map +1 -0
  16. package/dist/documentCapture/autoCaptureGeometry.js +394 -0
  17. package/dist/documentCapture/autoCaptureGuidance.d.ts +61 -0
  18. package/dist/documentCapture/autoCaptureGuidance.d.ts.map +1 -0
  19. package/dist/documentCapture/autoCaptureGuidance.js +73 -0
  20. package/dist/documentCapture/autoCaptureMetadata.d.ts +185 -0
  21. package/dist/documentCapture/autoCaptureMetadata.d.ts.map +1 -0
  22. package/dist/documentCapture/autoCaptureMetadata.js +197 -0
  23. package/dist/documentCapture/autoCaptureOptions.d.ts +212 -0
  24. package/dist/documentCapture/autoCaptureOptions.d.ts.map +1 -0
  25. package/dist/documentCapture/autoCaptureOptions.js +178 -0
  26. package/dist/documentCapture/autoCaptureShutter.d.ts +162 -0
  27. package/dist/documentCapture/autoCaptureShutter.d.ts.map +1 -0
  28. package/dist/documentCapture/autoCaptureShutter.js +183 -0
  29. package/dist/documentCapture/controller.d.ts +33 -1
  30. package/dist/documentCapture/controller.d.ts.map +1 -1
  31. package/dist/documentCapture/controller.js +604 -40
  32. package/dist/documentCapture/index.d.ts +8 -2
  33. package/dist/documentCapture/index.d.ts.map +1 -1
  34. package/dist/documentCapture/index.js +6 -0
  35. package/dist/documentCapture/reducer.d.ts +26 -1
  36. package/dist/documentCapture/reducer.d.ts.map +1 -1
  37. package/dist/documentCapture/reducer.js +43 -0
  38. package/dist/documentCapture/state.d.ts +118 -0
  39. package/dist/documentCapture/state.d.ts.map +1 -1
  40. package/dist/documentCapture/state.js +24 -0
  41. package/dist/idCapture/controller.d.ts +20 -0
  42. package/dist/idCapture/controller.d.ts.map +1 -1
  43. package/dist/idCapture/controller.js +42 -3
  44. package/dist/idCapture/index.d.ts +1 -1
  45. package/dist/idCapture/index.d.ts.map +1 -1
  46. package/dist/idCapture/index.js +12 -1
  47. package/dist/idCapture/pipeline.d.ts +30 -0
  48. package/dist/idCapture/pipeline.d.ts.map +1 -1
  49. package/dist/idCapture/pipeline.js +33 -10
  50. package/dist/models/DocumentDetection.d.ts +29 -1
  51. package/dist/models/DocumentDetection.d.ts.map +1 -1
  52. package/dist/models/DocumentDetection.js +37 -5
  53. package/dist/models/defaults/PoaDocumentDetectorLiteRT.d.ts +3 -0
  54. package/dist/models/defaults/PoaDocumentDetectorLiteRT.d.ts.map +1 -0
  55. package/dist/models/defaults/PoaDocumentDetectorLiteRT.js +15 -0
  56. package/dist/models/defaults/index.d.ts +4 -1
  57. package/dist/models/defaults/index.d.ts.map +1 -1
  58. package/dist/models/defaults/index.js +4 -0
  59. package/dist/models/preloadModels.d.ts +21 -14
  60. package/dist/models/preloadModels.d.ts.map +1 -1
  61. package/dist/models/preloadModels.js +10 -0
  62. package/dist/models/providers/litert/docDetectPrePost.d.ts.map +1 -1
  63. package/dist/models/providers/litert/docDetectPrePost.js +5 -0
  64. package/dist/selfieCapture/guidance.d.ts +49 -0
  65. package/dist/selfieCapture/guidance.d.ts.map +1 -1
  66. package/dist/selfieCapture/guidance.js +51 -0
  67. package/dist/selfieCapture/index.d.ts +1 -1
  68. package/dist/selfieCapture/index.d.ts.map +1 -1
  69. package/dist/selfieCapture/index.js +1 -1
  70. package/dist/signatureCapture/controller.d.ts.map +1 -1
  71. package/dist/signatureCapture/controller.js +71 -21
  72. package/dist/signatureCapture/pipeline.d.ts +14 -2
  73. package/dist/signatureCapture/pipeline.d.ts.map +1 -1
  74. package/dist/signatureCapture/pipeline.js +30 -7
  75. package/dist/signatureCapture/state.d.ts +15 -0
  76. package/dist/signatureCapture/state.d.ts.map +1 -1
  77. package/dist/version.d.ts +1 -1
  78. package/dist/version.d.ts.map +1 -1
  79. package/dist/version.js +1 -1
  80. package/dist/videoIdCapture/controller.d.ts.map +1 -1
  81. package/dist/videoIdCapture/controller.js +64 -3
  82. package/package.json +1 -1
@@ -0,0 +1,456 @@
1
+ // The lean POA detection loop — deliberately NOT `idCapture/pipeline.ts`.
2
+ //
3
+ // That file is 1612 lines of barcode readability, MRZ reasoning, aggressive
4
+ // decode and recapture phases, none of which will ever apply to a sheet of
5
+ // paper, and every future change to which would become a POA regression risk
6
+ // (#347). This composes the same shared primitives directly:
7
+ // `models/FrameLoop`, `models/DocumentDetection`, `models/Focus`,
8
+ // `models/modelLifecycle`, and the POA geometry next door.
9
+ //
10
+ // SCOPE: this engine MEASURES. It never fires a capture. The guidance ladder,
11
+ // the satisfied condition and the shutter are #345's to decide, and the
12
+ // thresholds the gates below compare against are #343's and #344's — this
13
+ // exists so those three tickets can be answered from real numbers on real
14
+ // devices instead of from seeded estimates. It is the instrument, and the
15
+ // diagnostics it emits are its only output.
16
+ //
17
+ // Two things it pointedly does not reuse:
18
+ //
19
+ // - `processDocumentDetectorPrediction`. Its boundary filter drops any box
20
+ // within 20px of a frame edge, which is exactly the POA case: a correctly
21
+ // framed sheet sits 1.3% of frame from the edge (#342), so the shared
22
+ // post-processor would discard the very detection we are here to measure.
23
+ // Raw detections are read straight off the prediction instead.
24
+ // - `DocumentDetection.ts`'s module-level `lastNBoxes` / `lastNPairs`
25
+ // stability trackers. Those are shared mutable state that `idCapture`'s
26
+ // pipeline writes to; a second consumer would silently corrupt both. This
27
+ // keeps its own window.
28
+ import { calculateIoU, } from '../models/helpers';
29
+ import { createFrameLoop } from '../models/FrameLoop';
30
+ import { defaultDocumentDetectionModelLoadTimeoutMs, defaultDocumentDetectionScoreThreshold, loadDocumentDetector, makeDocumentDetectorPrediction, testDocumentDetectorAgainstKnownImage, closeDocumentDetector, } from '../models/DocumentDetection';
31
+ import { classifyFocusModelForVideo, closeFocusModel, loadFocusModel, makeFocusModelPrediction, } from '../models/Focus';
32
+ import { runModelLoadLifecycle } from '../models/modelLifecycle';
33
+ import { resolveRuntime } from '../models/runtimeSelection';
34
+ import { isMobile } from '../utils/isMobile';
35
+ import { warn } from '../utils/logger';
36
+ import { computePoaFillWindow, computeGuideRect, computePoaFraming, failingPoaGates, isAutoCaptureSatisfied, peakScoresByLabel, selectPoaTarget, } from './autoCaptureGeometry';
37
+ import { advancePoaGuidance, createPoaGuidanceState, poaGuidanceCode, poaGuidanceDiagnostics, } from './autoCaptureGuidance';
38
+ import { resolveAutoCapture, } from './autoCaptureOptions';
39
+ /**
40
+ * ~300 frames is 10-20 seconds of loop at the 15-35fps this model runs at —
41
+ * long enough to hold a whole framing attempt, short enough to paste into an
42
+ * issue. #341 made this the actual deliverable of a tuning session: the
43
+ * on-glass text is only a liveness check, the log is what gets replayed into
44
+ * Storybook and pinned as fixtures.
45
+ */
46
+ export const AUTO_CAPTURE_LOG_FRAMES = 300;
47
+ /** Rolling window the reported frame rate is averaged over. */
48
+ const FRAME_RATE_SAMPLES = 25;
49
+ export function createAutoCaptureEngine(config) {
50
+ const now = config.io?.now ?? (() => Date.now());
51
+ const createCanvas = config.io?.createCanvas ?? (() => document.createElement('canvas'));
52
+ const makeFrameLoop = config.io?.createFrameLoop ?? createFrameLoop;
53
+ // isMobile()'s userAgentData fallback can return undefined (kept verbatim
54
+ // from sdk2's isMobile.ts); coerce to the boolean this surface promises,
55
+ // exactly as idCapture's pipeline does.
56
+ const onMobile = (config.io?.isMobile ?? (() => isMobile() === true))() === true;
57
+ // Every default this engine runs on comes from here and nowhere else. Do not
58
+ // reintroduce a `??` against a constant anywhere below — see the header on
59
+ // autoCaptureOptions.ts.
60
+ const resolved = resolveAutoCapture(config.autoCapture, {
61
+ onMobile,
62
+ documentDetectorRuntime: config.documentDetectorRuntime,
63
+ });
64
+ const { targetLabels, minScore, stabilityFrames } = resolved;
65
+ const stabilityThreshold = resolved.thresholds.stability;
66
+ // The fill window is the same length as the IoU window, per #343: one
67
+ // aggregation length, so a `fill` verdict and a stability verdict can never
68
+ // be taken over different spans of time.
69
+ const fillWindowOptions = {
70
+ fillMin: resolved.thresholds.fillMin,
71
+ fillMax: resolved.thresholds.fillMax,
72
+ framesNeeded: stabilityFrames,
73
+ };
74
+ const documentDetectorRuntime = resolved.documentDetectorRuntime;
75
+ const focusRuntime = resolveRuntime(config.focusRuntime, config.runtime);
76
+ const modelLoadTimeoutMs = config.modelLoadTimeoutMs ?? defaultDocumentDetectionModelLoadTimeoutMs;
77
+ // Frame canvas for the detector, plus focus's two scratch canvases — the
78
+ // same three `FocusModelProvider` mounts (:79-80) and the frame loop owns
79
+ // (DocumentDetectionModelProvider.tsx:119).
80
+ const frameCanvas = createCanvas();
81
+ const focusCropCanvas = createCanvas();
82
+ const focusRotateCanvas = createCanvas();
83
+ let video = null;
84
+ let loop = null;
85
+ let stopped = true;
86
+ let detectorLoad = null;
87
+ let focusLoad = null;
88
+ let detectorState = 'not-started';
89
+ let focusState = 'not-started';
90
+ /** See `setMeasureFocusEveryFrame`. Off is the loop's normal, cheap mode. */
91
+ let measureFocusEveryFrame = false;
92
+ let detectorProgress = 0;
93
+ let modelError = null;
94
+ // Stability window. Local to this engine — see the header on why the shared
95
+ // module-level trackers are not reused.
96
+ let boxWindow = [];
97
+ // Newest first, same length as `boxWindow`. Held as `fill` rather than
98
+ // recomputed from `boxWindow` because the frame dimensions a reading was
99
+ // taken against are not carried on the box, and a resolution change
100
+ // mid-window would silently re-scale the older entries.
101
+ let fillWindow = [];
102
+ let frameIntervals = [];
103
+ let lastFrameAt = 0;
104
+ // The displayed message. Initialised at 'none' with `displayedAt: 0`, so the
105
+ // min-hold never gates the first real code (#345).
106
+ let guidance = createPoaGuidanceState();
107
+ // Ring buffer, allocated on first write so `debugMode: false` costs nothing
108
+ // but the branch below.
109
+ let log = null;
110
+ // Whether `frameCanvas` holds a real frame. Distinguishes "not started" from
111
+ // "drawn", which a 0x0 check alone cannot once the canvas has been sized.
112
+ let frameCanvasDrawn = false;
113
+ function publishModels() {
114
+ config.onModelsChanged?.({
115
+ // The loop needs the detector; focus is additive, so overall readiness
116
+ // is the detector's. A focus failure degrades the reading (`focus: null`)
117
+ // rather than stopping the instrument — which is itself one of #344's
118
+ // possible answers.
119
+ state: detectorState,
120
+ downloadProgress: detectorProgress,
121
+ error: modelError,
122
+ });
123
+ }
124
+ /**
125
+ * Resolves once the attached video reports real dimensions, matching the
126
+ * `videoReady` seam `runModelLoadLifecycle` expects. Polls rather than
127
+ * listening for `loadedmetadata`: the camera may already be live when the
128
+ * lifecycle starts, in which case that event has already fired.
129
+ */
130
+ function videoReady() {
131
+ let timer = null;
132
+ let cancelled = false;
133
+ const promise = new Promise((resolve) => {
134
+ const check = () => {
135
+ if (cancelled)
136
+ return;
137
+ if (video && video.videoWidth > 0 && video.videoHeight > 0) {
138
+ resolve();
139
+ return;
140
+ }
141
+ timer = setTimeout(check, 100);
142
+ };
143
+ check();
144
+ });
145
+ return [
146
+ promise,
147
+ () => {
148
+ cancelled = true;
149
+ if (timer)
150
+ clearTimeout(timer);
151
+ },
152
+ ];
153
+ }
154
+ function trackFrameRate() {
155
+ const at = now();
156
+ if (lastFrameAt > 0) {
157
+ frameIntervals.unshift(at - lastFrameAt);
158
+ if (frameIntervals.length > FRAME_RATE_SAMPLES) {
159
+ frameIntervals.length = FRAME_RATE_SAMPLES;
160
+ }
161
+ }
162
+ lastFrameAt = at;
163
+ if (frameIntervals.length === 0)
164
+ return 0;
165
+ const mean = frameIntervals.reduce((sum, ms) => sum + ms, 0) / frameIntervals.length;
166
+ return mean > 0 ? 1000 / mean : 0;
167
+ }
168
+ /**
169
+ * Push a box and report the window. Returns the WORST pairwise IoU rather
170
+ * than the latest, because that is the value the verdict is taken on and the
171
+ * one an operator needs to see when a "stable" reading refuses to settle.
172
+ */
173
+ function trackStability(box) {
174
+ if (!box) {
175
+ boxWindow = [];
176
+ // Losing the box drops the fill history with it. A window spanning a gap
177
+ // would average a reading from before the sheet left frame against one
178
+ // from after it came back — two different framings, one mean.
179
+ fillWindow = [];
180
+ return {
181
+ worstIou: null,
182
+ threshold: stabilityThreshold,
183
+ framesTracked: 0,
184
+ framesNeeded: stabilityFrames,
185
+ isStable: false,
186
+ };
187
+ }
188
+ boxWindow.unshift(box);
189
+ if (boxWindow.length > stabilityFrames)
190
+ boxWindow.length = stabilityFrames;
191
+ let worstIou = null;
192
+ for (let i = 1; i < boxWindow.length; i++) {
193
+ const iou = calculateIoU(boxWindow[i - 1], boxWindow[i]);
194
+ if (worstIou === null || iou < worstIou)
195
+ worstIou = iou;
196
+ }
197
+ return {
198
+ worstIou,
199
+ threshold: stabilityThreshold,
200
+ framesTracked: boxWindow.length,
201
+ framesNeeded: stabilityFrames,
202
+ isStable: boxWindow.length >= stabilityFrames &&
203
+ worstIou !== null &&
204
+ worstIou >= stabilityThreshold,
205
+ };
206
+ }
207
+ /** Push this frame's `fill` and report #343's aggregate window. */
208
+ function trackFill(fill) {
209
+ if (fill === null)
210
+ return computePoaFillWindow([], fillWindowOptions);
211
+ fillWindow.unshift(fill);
212
+ if (fillWindow.length > stabilityFrames)
213
+ fillWindow.length = stabilityFrames;
214
+ return computePoaFillWindow(fillWindow, fillWindowOptions);
215
+ }
216
+ async function measureFocus(box) {
217
+ if (focusState !== 'ready' || !video || !box)
218
+ return null;
219
+ const prediction = await makeFocusModelPrediction(frameCanvas, focusCropCanvas, focusRotateCanvas, box);
220
+ if (!prediction)
221
+ return null;
222
+ // A POA-SPECIFIC slot, not `defaultFocusThresholds.singlePage` — #344
223
+ // found that slot's 0.3 mobile value was a never-tuned copy of the idCard
224
+ // entry, and #361 established class 22 still owns paper IDs, so the
225
+ // `detectedDocumentType`-keyed slot cannot be retuned for POA without
226
+ // moving paper IDs with it. The branch and the value are both reported so
227
+ // which one is in force is answerable from the overlay, not the source.
228
+ const threshold = resolved.thresholds.focus;
229
+ return {
230
+ score: prediction.score,
231
+ threshold,
232
+ branch: resolved.focusBranch,
233
+ thresholdMet: prediction.score >= threshold,
234
+ predictionTimeMs: prediction.predictionTime,
235
+ };
236
+ }
237
+ async function runFrame(frameId, timeRunning) {
238
+ const videoEl = video;
239
+ if (stopped || detectorState !== 'ready' || !videoEl)
240
+ return;
241
+ if (videoEl.readyState !== 4)
242
+ return;
243
+ const videoWidth = videoEl.videoWidth;
244
+ const videoHeight = videoEl.videoHeight;
245
+ if (videoWidth <= 0 || videoHeight <= 0)
246
+ return;
247
+ frameCanvas.width = videoWidth;
248
+ frameCanvas.height = videoHeight;
249
+ const ctx = frameCanvas.getContext('2d');
250
+ if (!ctx)
251
+ return;
252
+ ctx.drawImage(videoEl, 0, 0, videoWidth, videoHeight);
253
+ frameCanvasDrawn = true;
254
+ const prediction = await makeDocumentDetectorPrediction(frameCanvas);
255
+ if (stopped || !prediction)
256
+ return;
257
+ // Raw detections — see the header on why the shared post-processor's
258
+ // boundary filter is skipped.
259
+ const detectedObjects = [];
260
+ for (const detection of prediction.detections) {
261
+ const category = detection.categories[0];
262
+ const boundingBox = detection.boundingBox;
263
+ if (!category || !boundingBox)
264
+ continue;
265
+ const xMin = boundingBox.originX;
266
+ const yMin = boundingBox.originY;
267
+ detectedObjects.push({
268
+ label: category.categoryName,
269
+ score: category.score,
270
+ box: {
271
+ xMin,
272
+ yMin,
273
+ xMax: xMin + boundingBox.width,
274
+ yMax: yMin + boundingBox.height,
275
+ width: boundingBox.width,
276
+ height: boundingBox.height,
277
+ },
278
+ });
279
+ }
280
+ // The rectangle the applicant was asked to fill, not the raw frame. See
281
+ // `computeGuideRect` for why grading the frame picked the wrong axis on
282
+ // every landscape camera.
283
+ const guideRect = computeGuideRect(prediction.frameWidth, prediction.frameHeight, config.aspectRatio);
284
+ const target = selectPoaTarget(detectedObjects, targetLabels, minScore);
285
+ const framing = target ? computePoaFraming(target.box, guideRect) : null;
286
+ const stability = trackStability(target?.box ?? null);
287
+ // AFTER trackStability, which clears both windows when the box is lost.
288
+ const fillWindowReading = trackFill(framing ? framing.fill : null);
289
+ // FOCUS RUNS LAST, AND ONLY IF EVERYTHING ELSE ALREADY PASSED.
290
+ //
291
+ // Borrowed from `idCapture`, whose focus prediction lives inside the
292
+ // good-frame branch (pipeline.ts: detected && in-bounds && !tooClose &&
293
+ // stable) rather than on the frame path. This engine took that ladder's
294
+ // ORDER but not its gating, and paid a focus inference on every frame with
295
+ // a box — including every frame the fill window or the stability window was
296
+ // going to reject anyway. On a desktop browser the POA focus threshold is
297
+ // 0, so those predictions could not change a verdict at all.
298
+ //
299
+ // Safe by construction rather than by care: `failingPoaGates` treats a
300
+ // `null` focus verdict as ABSENT, not failing, and `outOfFocus` is last in
301
+ // `POA_GATE_ORDER` — so a frame that skips the prediction reports exactly
302
+ // the gates that were actually measured, and the displayed message is
303
+ // unchanged. That null-is-absent rule already existed for the
304
+ // focus-model-failed case; this is a second producer of it.
305
+ //
306
+ // It also does not cost the tuning corpus anything: #380 tuned the
307
+ // threshold on "frames that would have captured but for focus", which IS
308
+ // this set.
309
+ const preFocusGates = {
310
+ framing,
311
+ fillWindow: fillWindowReading,
312
+ focusThresholdMet: null,
313
+ isStable: stability.isStable,
314
+ };
315
+ const focus = measureFocusEveryFrame || failingPoaGates(preFocusGates).length === 0
316
+ ? await measureFocus(target?.box ?? null)
317
+ : null;
318
+ if (stopped)
319
+ return;
320
+ // ONE call's worth of gate inputs, shared by the verdict, the failing-gate
321
+ // list the overlay renders, and the message. Recomputing them per consumer
322
+ // is how "it captured while the pill said move back" becomes possible for
323
+ // a reason other than the deliberate one below.
324
+ const gateInputs = {
325
+ ...preFocusGates,
326
+ focusThresholdMet: focus ? focus.thresholdMet : null,
327
+ };
328
+ const satisfied = isAutoCaptureSatisfied(gateInputs);
329
+ const rawGuidance = poaGuidanceCode(gateInputs);
330
+ // Display only. The shutter reads `satisfied` live, so a capture can fire
331
+ // while a stale message is still held on screen — `idCapture`'s shipped
332
+ // behaviour, not a POA wart.
333
+ guidance = advancePoaGuidance(guidance, gateInputs, timeRunning);
334
+ const frameRate = trackFrameRate();
335
+ const diagnostics = {
336
+ frameId,
337
+ timeRunning,
338
+ detectedObjects,
339
+ scores: peakScoresByLabel(detectedObjects),
340
+ target,
341
+ targetMinScore: minScore,
342
+ framing,
343
+ fillWindow: fillWindowReading,
344
+ focus,
345
+ stability,
346
+ failingGates: failingPoaGates(gateInputs),
347
+ satisfied,
348
+ guidance: poaGuidanceDiagnostics(guidance, rawGuidance, timeRunning),
349
+ detectionTimeMs: prediction.time,
350
+ frameRate,
351
+ frameWidth: prediction.frameWidth,
352
+ frameHeight: prediction.frameHeight,
353
+ guideRect,
354
+ videoWidth,
355
+ videoHeight,
356
+ };
357
+ // The one branch `debugMode: false` pays for.
358
+ if (config.debugMode) {
359
+ if (!log)
360
+ log = [];
361
+ log.push(diagnostics);
362
+ if (log.length > AUTO_CAPTURE_LOG_FRAMES)
363
+ log.shift();
364
+ }
365
+ config.onDiagnostics(diagnostics);
366
+ }
367
+ return {
368
+ start(attachedVideo) {
369
+ if (!stopped)
370
+ return;
371
+ stopped = false;
372
+ video = attachedVideo;
373
+ modelError = null;
374
+ detectorLoad = runModelLoadLifecycle({
375
+ load: () => loadDocumentDetector(config.assets?.documentDetectionModelUrl, defaultDocumentDetectionScoreThreshold, documentDetectorRuntime,
376
+ // ALONGSIDE the shared detector, never replacing it (#355): this
377
+ // picks both the default path and the preloaded (SRI-verified)
378
+ // artifact, so the two cannot disagree.
379
+ { artifact: 'poa' }),
380
+ testAgainstKnownImage: () => testDocumentDetectorAgainstKnownImage(),
381
+ // `idmission.preloadProgress.<model>` is the name `preloadModels`
382
+ // actually dispatches, and the one `idCapture` listens on
383
+ // (pipeline.ts:815). The invented `documentDetectorDownloadProgress`
384
+ // matched nothing, so the pane jumped 0 -> loaded with no progress in
385
+ // between. LiteRT is pinned for this artifact, so the runtime is not
386
+ // in question the way it is for idCapture.
387
+ progressEventName: 'idmission.preloadProgress.documentDetectorLiteRT',
388
+ timeoutMs: modelLoadTimeoutMs,
389
+ videoReady,
390
+ onCleanup: closeDocumentDetector,
391
+ onChange: (snapshot) => {
392
+ detectorState = snapshot.state;
393
+ detectorProgress = snapshot.downloadProgress;
394
+ if (snapshot.error)
395
+ modelError = snapshot.error;
396
+ publishModels();
397
+ },
398
+ });
399
+ focusLoad = runModelLoadLifecycle({
400
+ load: () => loadFocusModel(config.assets?.focusModelUrl, focusRuntime),
401
+ warmUp: () => {
402
+ if (video)
403
+ classifyFocusModelForVideo(video);
404
+ },
405
+ progressEventName: focusRuntime === 'litert'
406
+ ? 'idmission.preloadProgress.focusLiteRT'
407
+ : 'idmission.preloadProgress.focus',
408
+ timeoutMs: modelLoadTimeoutMs,
409
+ videoReady,
410
+ onCleanup: closeFocusModel,
411
+ onChange: (snapshot) => {
412
+ focusState = snapshot.state;
413
+ // A focus failure is reported but not fatal: the detector half of
414
+ // the instrument still reads, and `focus: null` on every frame is
415
+ // itself a finding for #344.
416
+ if (snapshot.error) {
417
+ warn('[documentCapture] focus model failed to load', snapshot.error);
418
+ }
419
+ publishModels();
420
+ },
421
+ });
422
+ loop = makeFrameLoop(runFrame, { throttleMs: config.throttleMs ?? 0 });
423
+ loop.start();
424
+ },
425
+ stop() {
426
+ stopped = true;
427
+ loop?.stop();
428
+ loop = null;
429
+ detectorLoad?.cancel();
430
+ focusLoad?.cancel();
431
+ detectorLoad = null;
432
+ focusLoad = null;
433
+ video = null;
434
+ boxWindow = [];
435
+ fillWindow = [];
436
+ frameIntervals = [];
437
+ lastFrameAt = 0;
438
+ guidance = createPoaGuidanceState();
439
+ // A stopped engine must not hand out its last frame: the next capture
440
+ // through this document would submit a picture taken before the retry.
441
+ frameCanvasDrawn = false;
442
+ // Nor stay in the expensive mode a burst window left it in.
443
+ measureFocusEveryFrame = false;
444
+ },
445
+ getGradedFrame: () => frameCanvasDrawn && frameCanvas.width > 0 && frameCanvas.height > 0
446
+ ? frameCanvas
447
+ : null,
448
+ setMeasureFocusEveryFrame(on) {
449
+ measureFocusEveryFrame = on;
450
+ },
451
+ getDiagnosticsLog: () => (log ? log.slice() : []),
452
+ clearDiagnosticsLog() {
453
+ log = null;
454
+ },
455
+ };
456
+ }