@camstack/addon-pipeline 1.2.31 → 1.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/detection-pipeline/index.js +839 -1013
- package/dist/detection-pipeline/index.mjs +839 -1013
- package/dist/pipeline-runner/index.js +30 -4
- package/dist/pipeline-runner/index.mjs +30 -4
- package/dist/{step-definitions-BkY9_IM6.mjs → step-definitions-C8tk9fPJ.mjs} +11 -2
- package/dist/{step-definitions-gC-Ovglc.js → step-definitions-i8O-hxyI.js} +16 -1
- package/dist/stream-broker/{_virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-BUXeX-vb.mjs → _virtual_mf-localSharedImportMap___mfe_internal__addon_stream_broker_widgets-C5m4hC2K.mjs} +3 -3
- package/dist/stream-broker/{hostInit-DJ3h-b1X.mjs → hostInit-WXFrgppm.mjs} +3 -3
- package/dist/stream-broker/remoteEntry.js +1 -1
- package/embed-dist/assets/{MaskShapeCanvas-DI4BY7W2-B0DyP46h.js → MaskShapeCanvas-DI4BY7W2-Dx-Vrpyt.js} +1 -1
- package/embed-dist/assets/{MotionZonesSettings-NcxxQN8r-CzGSy_EO.js → MotionZonesSettings-NcxxQN8r-9D-BWwQP.js} +1 -1
- package/embed-dist/assets/{PrivacyMaskSettings-APgPLF7p-CEgMcOOW.js → PrivacyMaskSettings-APgPLF7p-HvAetfA4.js} +1 -1
- package/embed-dist/assets/{index-CHXOWKHF.js → index-9Ob2YrIf.js} +5 -5
- package/embed-dist/index.html +1 -1
- package/package.json +1 -1
|
@@ -4,7 +4,7 @@ Object.defineProperties(exports, {
|
|
|
4
4
|
});
|
|
5
5
|
const require_chunk = require("../chunk-emK7D4bc.js");
|
|
6
6
|
const require_dist = require("../dist-BvFLZyhW.js");
|
|
7
|
-
const require_step_definitions = require("../step-definitions-
|
|
7
|
+
const require_step_definitions = require("../step-definitions-i8O-hxyI.js");
|
|
8
8
|
const require_node_topology_platform = require("../node-topology-platform-CFZ7F4xW.js");
|
|
9
9
|
const require_model_download_service_Cp9f4dk6 = require("../model-download-service-Cp9f4dk6-fsdDExML.js");
|
|
10
10
|
let node_os = require("node:os");
|
|
@@ -251,43 +251,6 @@ function normalizeEngineNodeId(rawNodeId) {
|
|
|
251
251
|
return raw.includes("/") ? raw.split("/")[0] ?? "hub" : raw;
|
|
252
252
|
}
|
|
253
253
|
//#endregion
|
|
254
|
-
//#region src/detection-pipeline/pipeline/native-crop-compose.ts
|
|
255
|
-
/** Clamp `v` into `[lo, hi]`. */
|
|
256
|
-
function clamp(v, lo, hi) {
|
|
257
|
-
if (v < lo) return lo;
|
|
258
|
-
if (v > hi) return hi;
|
|
259
|
-
return v;
|
|
260
|
-
}
|
|
261
|
-
/**
|
|
262
|
-
* Compose a child `roi` given in the parent CROP's normalized space into the
|
|
263
|
-
* FRAME's normalized space, given the crop's frame-space pixel rectangle and the
|
|
264
|
-
* frame dimensions. The result is clamped to the unit square (origin in
|
|
265
|
-
* `[0,1]`, extent bounded so `x + w ≤ 1` and `y + h ≤ 1`). Returns `null` for
|
|
266
|
-
* degenerate inputs (non-finite frame dims, empty crop rect, or an ROI that
|
|
267
|
-
* clamps to zero area) so the caller falls back to the downscaled tile crop.
|
|
268
|
-
*
|
|
269
|
-
* Pure — never mutates its arguments.
|
|
270
|
-
*/
|
|
271
|
-
function composeCropRoiToFrameNorm(roi, cropFrameSpace, frameWidth, frameHeight) {
|
|
272
|
-
if (!(frameWidth > 0) || !(frameHeight > 0)) return null;
|
|
273
|
-
if (!(cropFrameSpace.w > 0) || !(cropFrameSpace.h > 0)) return null;
|
|
274
|
-
const fx = (cropFrameSpace.x + roi.x * cropFrameSpace.w) / frameWidth;
|
|
275
|
-
const fy = (cropFrameSpace.y + roi.y * cropFrameSpace.h) / frameHeight;
|
|
276
|
-
const fw = roi.w * cropFrameSpace.w / frameWidth;
|
|
277
|
-
const fh = roi.h * cropFrameSpace.h / frameHeight;
|
|
278
|
-
const x = clamp(fx, 0, 1);
|
|
279
|
-
const y = clamp(fy, 0, 1);
|
|
280
|
-
const w = clamp(fw, 0, 1 - x);
|
|
281
|
-
const h = clamp(fh, 0, 1 - y);
|
|
282
|
-
if (!(w > 0) || !(h > 0)) return null;
|
|
283
|
-
return {
|
|
284
|
-
x,
|
|
285
|
-
y,
|
|
286
|
-
w,
|
|
287
|
-
h
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
//#endregion
|
|
291
254
|
//#region src/detection-pipeline/default-detection-model.ts
|
|
292
255
|
/** The object-detection step id — the only slot this resolver applies to. */
|
|
293
256
|
var OBJECT_DETECTION_STEP_ID$1 = "object-detection";
|
|
@@ -338,10 +301,12 @@ function classifyAccelerator(backend, device) {
|
|
|
338
301
|
*
|
|
339
302
|
* Guarantees:
|
|
340
303
|
* - never throws (hot default-tree path);
|
|
341
|
-
* - never returns a model id
|
|
342
|
-
*
|
|
343
|
-
*
|
|
344
|
-
*
|
|
304
|
+
* - never returns a model id without a build for `format` (unless the step
|
|
305
|
+
* has ZERO builds for `format`, which is unloadable regardless of pick and
|
|
306
|
+
* flagged by `collectZeroBuildIssues`) — an unmapped backend, a `'cpu'`
|
|
307
|
+
* class, a mapped id missing from the catalog, or a mapped id without a
|
|
308
|
+
* `format` build all fall back to the step's PER-FORMAT default
|
|
309
|
+
* (`getDefaultModelForFormatFromDef`), NOT the bare `defaultModelId`.
|
|
345
310
|
*
|
|
346
311
|
* `getStepDef` is injectable (defaults to the real catalog lookup) so the
|
|
347
312
|
* missing-build fallback branch is unit-testable without a live catalog —
|
|
@@ -354,12 +319,12 @@ function resolveDefaultDetectionModel(backend, device, format, getStepDef = requ
|
|
|
354
319
|
} catch {
|
|
355
320
|
return "yolo26n";
|
|
356
321
|
}
|
|
357
|
-
const fallback = def.defaultModelId;
|
|
358
322
|
const candidate = MODEL_BY_CLASS[classifyAccelerator(backend, device)];
|
|
359
|
-
if (candidate
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
323
|
+
if (candidate !== null) {
|
|
324
|
+
const entry = def.models.find((m) => m.id === candidate);
|
|
325
|
+
if (entry && entry.formats[format] !== void 0) return candidate;
|
|
326
|
+
}
|
|
327
|
+
return require_step_definitions.getDefaultModelForFormatFromDef(def, format);
|
|
363
328
|
}
|
|
364
329
|
//#endregion
|
|
365
330
|
//#region src/detection-pipeline/engine/shared-inference-pool.ts
|
|
@@ -476,10 +441,7 @@ var PoolHandle = class {
|
|
|
476
441
|
}
|
|
477
442
|
async infer(input) {
|
|
478
443
|
const start = performance.now();
|
|
479
|
-
return
|
|
480
|
-
structured: input.kind === "raw" ? await this.pool.inferRaw(this.modelIndex, input.data, input.width, input.height, input.format) : await this.pool.infer(this.modelIndex, input.data),
|
|
481
|
-
inferenceMs: performance.now() - start
|
|
482
|
-
};
|
|
444
|
+
return poolResultToEngineOutput(input.kind === "raw" ? await this.pool.inferRaw(this.modelIndex, input.data, input.width, input.height, input.format) : await this.pool.infer(this.modelIndex, input.data), performance.now() - start);
|
|
483
445
|
}
|
|
484
446
|
/**
|
|
485
447
|
* Inference on a frame previously cached in the Python pool via
|
|
@@ -488,20 +450,50 @@ var PoolHandle = class {
|
|
|
488
450
|
*/
|
|
489
451
|
async inferFromCache(frameId) {
|
|
490
452
|
const start = performance.now();
|
|
491
|
-
return
|
|
492
|
-
structured: await this.pool.inferCached(this.modelIndex, frameId),
|
|
493
|
-
inferenceMs: performance.now() - start
|
|
494
|
-
};
|
|
453
|
+
return poolResultToEngineOutput(await this.pool.inferCached(this.modelIndex, frameId), performance.now() - start);
|
|
495
454
|
}
|
|
496
455
|
async dispose() {}
|
|
497
456
|
};
|
|
498
457
|
/**
|
|
458
|
+
* Map a raw pool response record to an {@link EngineOutput}.
|
|
459
|
+
*
|
|
460
|
+
* An overload shed (`{dropped: true}` — from the Python pool's per-model bound
|
|
461
|
+
* OR the TS worker in-flight cap, which deliberately mirrors it) becomes a
|
|
462
|
+
* first-class `EngineOutput.dropped` with NO `structured` payload. Before this
|
|
463
|
+
* mapping the shed record rode through as `structured`, failed the StepOutput
|
|
464
|
+
* kind guard in the postprocess funnel, and every deliberate shed was logged
|
|
465
|
+
* as `runInference failed … unexpected kind: undefined` at error level on
|
|
466
|
+
* every node (~4/s cluster-wide, 2026-08-01). A shed is flow control, not a
|
|
467
|
+
* fault — it must never reach a postprocessor. Exported for tests.
|
|
468
|
+
*/
|
|
469
|
+
function poolResultToEngineOutput(result, inferenceMs) {
|
|
470
|
+
if (result["dropped"] === true) {
|
|
471
|
+
const shedReason = result["shedReason"];
|
|
472
|
+
return {
|
|
473
|
+
dropped: true,
|
|
474
|
+
...typeof shedReason === "string" ? { shedReason } : {},
|
|
475
|
+
inferenceMs
|
|
476
|
+
};
|
|
477
|
+
}
|
|
478
|
+
return {
|
|
479
|
+
structured: result,
|
|
480
|
+
inferenceMs
|
|
481
|
+
};
|
|
482
|
+
}
|
|
483
|
+
/**
|
|
499
484
|
* How long to wait for a worker to exit on SIGTERM before escalating to
|
|
500
485
|
* SIGKILL. A worker idle between frames exits well under this; only a worker
|
|
501
486
|
* stuck in a native inference call (openvino/onnx C++) needs the escalation.
|
|
502
487
|
*/
|
|
503
488
|
var POOL_WORKER_TERM_GRACE_MS = 2e3;
|
|
504
489
|
/**
|
|
490
|
+
* Sampling stride for the "Python pool shed frame under overload" debug
|
|
491
|
+
* line — see `trackDroppedResponse`. At the observed chronic-overload rate
|
|
492
|
+
* (~13 shed/s, 2026-08-01) a stride of 500 yields roughly one line every
|
|
493
|
+
* 40 s while `droppedTotal` in the line keeps the exact count.
|
|
494
|
+
*/
|
|
495
|
+
var SHED_LOG_SAMPLE_EVERY = 500;
|
|
496
|
+
/**
|
|
505
497
|
* Terminate a spawned child GRACEFULLY THEN FORCEFULLY: end stdin, send
|
|
506
498
|
* SIGTERM, and if the process hasn't exited within `graceMs`, send SIGKILL.
|
|
507
499
|
* Resolves once the process has exited (or was already dead).
|
|
@@ -1063,13 +1055,23 @@ var SharedInferencePool = class {
|
|
|
1063
1055
|
* single-frame inference paths. Previously indistinguishable from a
|
|
1064
1056
|
* genuine empty detection result — now counted + debug-logged so
|
|
1065
1057
|
* overload is measurable. The response passes through unchanged.
|
|
1058
|
+
*
|
|
1059
|
+
* SAMPLED log: one line per shed frame turned into 45 741 rows/hour on
|
|
1060
|
+
* the hub during the 2026-08-01 chronic overload (~13 shed/s) — 2/3 of
|
|
1061
|
+
* the hub's entire log volume, burying every other signal. The counter
|
|
1062
|
+
* keeps exact totals (`droppedTotal` is authoritative, surfaced in
|
|
1063
|
+
* `getStatus` consumers via `getDroppedResponseCount`); the log line
|
|
1064
|
+
* now fires on the FIRST shed and every `SHED_LOG_SAMPLE_EVERY`th,
|
|
1065
|
+
* carrying the running total so nothing is lost — only repeated.
|
|
1066
1066
|
*/
|
|
1067
1067
|
trackDroppedResponse(result, modelIndex) {
|
|
1068
1068
|
if (result["dropped"] === true) {
|
|
1069
1069
|
this.droppedResponseCount++;
|
|
1070
|
-
|
|
1070
|
+
const total = this.droppedResponseCount;
|
|
1071
|
+
if (total === 1 || total % SHED_LOG_SAMPLE_EVERY === 0) this.log.debug("Python pool shed frame under overload", { meta: {
|
|
1071
1072
|
modelIndex,
|
|
1072
|
-
droppedTotal:
|
|
1073
|
+
droppedTotal: total,
|
|
1074
|
+
sampledEvery: SHED_LOG_SAMPLE_EVERY,
|
|
1073
1075
|
runtime: this.poolRuntime,
|
|
1074
1076
|
device: this.device ?? "default"
|
|
1075
1077
|
} });
|
|
@@ -1146,6 +1148,66 @@ function flattenEnabledVideoSteps(steps) {
|
|
|
1146
1148
|
walk(steps);
|
|
1147
1149
|
return result;
|
|
1148
1150
|
}
|
|
1151
|
+
/**
|
|
1152
|
+
* The steps that EXECUTE in a `plane: 'frame'` dispatch (two-plane design),
|
|
1153
|
+
* mirroring the executor's frame-plane skip in `executeChildren`: every
|
|
1154
|
+
* enabled top-level step runs at the root; a CHILD runs only when its catalog
|
|
1155
|
+
* definition is itself root-plane (`isDetailStep(addonId)` false). The walk
|
|
1156
|
+
* continues only through steps that execute — a skipped detail child's
|
|
1157
|
+
* descendants ride ITS per-track detail-subtree call, never this one.
|
|
1158
|
+
* Disabled and audio-classifier steps execute on neither plane.
|
|
1159
|
+
*/
|
|
1160
|
+
function collectFramePlaneSteps(steps, isDetailStep) {
|
|
1161
|
+
const result = [];
|
|
1162
|
+
const walk = (nodes, topLevel) => {
|
|
1163
|
+
for (const step of nodes) {
|
|
1164
|
+
if (!step.enabled) continue;
|
|
1165
|
+
if (step.slot === "audio-classifier") continue;
|
|
1166
|
+
if (!topLevel && isDetailStep(step.addonId)) continue;
|
|
1167
|
+
result.push(step);
|
|
1168
|
+
if (step.children?.length) walk(step.children, false);
|
|
1169
|
+
}
|
|
1170
|
+
};
|
|
1171
|
+
walk(steps, true);
|
|
1172
|
+
return result;
|
|
1173
|
+
}
|
|
1174
|
+
/**
|
|
1175
|
+
* Immutably remove from a frame-plane dispatch tree every enabled DETAIL
|
|
1176
|
+
* subtree (at any depth below the top level) whose top step `isUnrunnable`.
|
|
1177
|
+
* Those steps can never load into the dispatch device's pool — leaving them
|
|
1178
|
+
* in the tree makes `ensureModelsForSteps` fail the whole call on a format
|
|
1179
|
+
* build that does not exist. They are NOT dropped work: each runs later as
|
|
1180
|
+
* its own detail-subtree dispatch, where the device-jump resolver
|
|
1181
|
+
* (`resolveStepDevice`) places it on a same-node device that can run it, or
|
|
1182
|
+
* warns no-candidate loudly. Runnable detail children are kept so their
|
|
1183
|
+
* models pre-warm the device pool as before. Disabled subtrees are kept
|
|
1184
|
+
* verbatim (never walked — `ensureModelsForSteps` skips them anyway).
|
|
1185
|
+
*/
|
|
1186
|
+
function pruneUnrunnableDetailSteps(steps, isDetailStep, isUnrunnable) {
|
|
1187
|
+
const prunedAddonIds = [];
|
|
1188
|
+
const walk = (nodes, topLevel) => {
|
|
1189
|
+
const kept = [];
|
|
1190
|
+
for (const step of nodes) {
|
|
1191
|
+
if (!step.enabled) {
|
|
1192
|
+
kept.push(step);
|
|
1193
|
+
continue;
|
|
1194
|
+
}
|
|
1195
|
+
if (!topLevel && isDetailStep(step.addonId) && isUnrunnable(step.addonId)) {
|
|
1196
|
+
prunedAddonIds.push(step.addonId);
|
|
1197
|
+
continue;
|
|
1198
|
+
}
|
|
1199
|
+
kept.push(step.children?.length ? {
|
|
1200
|
+
...step,
|
|
1201
|
+
children: walk(step.children, false)
|
|
1202
|
+
} : step);
|
|
1203
|
+
}
|
|
1204
|
+
return kept;
|
|
1205
|
+
};
|
|
1206
|
+
return {
|
|
1207
|
+
steps: walk(steps, true),
|
|
1208
|
+
prunedAddonIds
|
|
1209
|
+
};
|
|
1210
|
+
}
|
|
1149
1211
|
//#endregion
|
|
1150
1212
|
//#region src/detection-pipeline/engine/pipeline-model-manager.ts
|
|
1151
1213
|
var PipelineModelManager = class {
|
|
@@ -1543,7 +1605,7 @@ var RUNTIME_TO_FORMAT = {
|
|
|
1543
1605
|
edgetpu: "tflite"
|
|
1544
1606
|
};
|
|
1545
1607
|
/** The step whose detections are re-filtered downstream by the executor's
|
|
1546
|
-
* per-macro `minConfidence*` sliders (`
|
|
1608
|
+
* per-macro `minConfidence*` sliders (`macroFilterVerdict`). Its pool-side
|
|
1547
1609
|
* floor must stay BELOW those sliders or it silently pre-empts them. */
|
|
1548
1610
|
var OBJECT_DETECTION_STEP_ID = "object-detection";
|
|
1549
1611
|
/**
|
|
@@ -1988,601 +2050,6 @@ var EngineProvisioner = class {
|
|
|
1988
2050
|
}
|
|
1989
2051
|
};
|
|
1990
2052
|
//#endregion
|
|
1991
|
-
//#region src/detection-pipeline/postprocess/dispatch.ts
|
|
1992
|
-
/** Detector NMS IoU fallback — the historical hardcoded literal, used when the
|
|
1993
|
-
* step carries no `nmsIouThreshold` setting (unset == today). */
|
|
1994
|
-
var DEFAULT_NMS_IOU = .45;
|
|
1995
|
-
/**
|
|
1996
|
-
* Region plate grammars for the TS fallback CTC decoder (nodejs+onnx path).
|
|
1997
|
-
* VALIDATION-ONLY: this mirror annotates `formatValid` but does NOT rescore
|
|
1998
|
-
* confusables — the confusable repair needs the aligned per-timestep softmax
|
|
1999
|
-
* that only the Python path retains (see `python/postprocessors/ctc.py`). Keep
|
|
2000
|
-
* the pattern set in sync with `PLATE_GRAMMARS` there. `'off'`/unset disables it.
|
|
2001
|
-
*/
|
|
2002
|
-
var TS_PLATE_GRAMMARS = { DE: /^[A-ZÄÖÜ]{1,3}[- ]?[A-Z]{1,2}[- ]?[0-9]{1,4}[EH]?$/ };
|
|
2003
|
-
var VALID_KINDS = new Set([
|
|
2004
|
-
"detections",
|
|
2005
|
-
"classifications",
|
|
2006
|
-
"embedding",
|
|
2007
|
-
"text",
|
|
2008
|
-
"mask"
|
|
2009
|
-
]);
|
|
2010
|
-
/**
|
|
2011
|
-
* Type guard: validates that a structured payload from the Python pool is a
|
|
2012
|
-
* well-formed StepOutput discriminated union.
|
|
2013
|
-
*
|
|
2014
|
-
* The Python inference_pool.py always sets `output.structured` with a `kind`
|
|
2015
|
-
* field. This guard narrows `Record<string, unknown>` to `StepOutput` without
|
|
2016
|
-
* resorting to double-cast.
|
|
2017
|
-
*/
|
|
2018
|
-
function isStepOutput(value) {
|
|
2019
|
-
return typeof value === "object" && value !== null && typeof value["kind"] === "string" && VALID_KINDS.has(value["kind"]);
|
|
2020
|
-
}
|
|
2021
|
-
/**
|
|
2022
|
-
* Return the structured payload as `StepOutput`, or null if it fails validation.
|
|
2023
|
-
* Callers must handle null by proceeding to raw-tensor postprocessing.
|
|
2024
|
-
*/
|
|
2025
|
-
function tryStructured(output) {
|
|
2026
|
-
if (!output.structured) return null;
|
|
2027
|
-
if (!isStepOutput(output.structured)) throw new Error(`Python pool returned structured output with unexpected kind: ${JSON.stringify(output.structured["kind"])}`);
|
|
2028
|
-
return output.structured;
|
|
2029
|
-
}
|
|
2030
|
-
function postprocessYolo(output, stepDef, nmsIouThreshold) {
|
|
2031
|
-
const structured = tryStructured(output);
|
|
2032
|
-
if (structured) return structured;
|
|
2033
|
-
const tensor = output.tensor;
|
|
2034
|
-
if (!tensor) throw new Error("YOLO postprocessor: no tensor in engine output");
|
|
2035
|
-
const labels = stepDef.labels ?? [];
|
|
2036
|
-
const numClasses = labels.length || 80;
|
|
2037
|
-
const numBoxes = tensor.length / (4 + numClasses);
|
|
2038
|
-
const letterbox = output.letterbox;
|
|
2039
|
-
const dets = [];
|
|
2040
|
-
for (let i = 0; i < numBoxes; i++) {
|
|
2041
|
-
const cx = tensor[i];
|
|
2042
|
-
const cy = tensor[1 * numBoxes + i];
|
|
2043
|
-
const w = tensor[2 * numBoxes + i];
|
|
2044
|
-
const h = tensor[3 * numBoxes + i];
|
|
2045
|
-
let bestScore = -Infinity;
|
|
2046
|
-
let bestClass = 0;
|
|
2047
|
-
for (let j = 0; j < numClasses; j++) {
|
|
2048
|
-
const score = tensor[(4 + j) * numBoxes + i];
|
|
2049
|
-
if (score > bestScore) {
|
|
2050
|
-
bestScore = score;
|
|
2051
|
-
bestClass = j;
|
|
2052
|
-
}
|
|
2053
|
-
}
|
|
2054
|
-
if (bestScore <= 0) continue;
|
|
2055
|
-
let x1 = cx - w / 2;
|
|
2056
|
-
let y1 = cy - h / 2;
|
|
2057
|
-
let x2 = cx + w / 2;
|
|
2058
|
-
let y2 = cy + h / 2;
|
|
2059
|
-
if (letterbox) {
|
|
2060
|
-
x1 = (x1 - letterbox.padX) / letterbox.scale;
|
|
2061
|
-
y1 = (y1 - letterbox.padY) / letterbox.scale;
|
|
2062
|
-
x2 = (x2 - letterbox.padX) / letterbox.scale;
|
|
2063
|
-
y2 = (y2 - letterbox.padY) / letterbox.scale;
|
|
2064
|
-
}
|
|
2065
|
-
const label = labels[bestClass] ?? String(bestClass);
|
|
2066
|
-
dets.push({
|
|
2067
|
-
class: label,
|
|
2068
|
-
score: bestScore,
|
|
2069
|
-
bbox: [
|
|
2070
|
-
x1,
|
|
2071
|
-
y1,
|
|
2072
|
-
x2,
|
|
2073
|
-
y2
|
|
2074
|
-
]
|
|
2075
|
-
});
|
|
2076
|
-
}
|
|
2077
|
-
return {
|
|
2078
|
-
kind: "detections",
|
|
2079
|
-
detections: simpleNms(dets, nmsIouThreshold)
|
|
2080
|
-
};
|
|
2081
|
-
}
|
|
2082
|
-
function postprocessSsd(output, _stepDef) {
|
|
2083
|
-
const structured = tryStructured(output);
|
|
2084
|
-
if (structured) return structured;
|
|
2085
|
-
throw new Error("SSD postprocessing runs in the Python inference pool (ssd.py); no TypeScript raw-tensor path.");
|
|
2086
|
-
}
|
|
2087
|
-
function postprocessScrfd(output, stepDef, nmsIouThreshold) {
|
|
2088
|
-
const structured = tryStructured(output);
|
|
2089
|
-
if (structured) return structured;
|
|
2090
|
-
if (!output.tensors) throw new Error("SCRFD postprocessor: no tensors in engine output");
|
|
2091
|
-
const strides = [
|
|
2092
|
-
8,
|
|
2093
|
-
16,
|
|
2094
|
-
32
|
|
2095
|
-
];
|
|
2096
|
-
const anchorsPerStride = 2;
|
|
2097
|
-
const inputSize = Math.max(stepDef.models[0]?.inputSize.width ?? 640, stepDef.models[0]?.inputSize.height ?? 640);
|
|
2098
|
-
const strideData = matchTensorsToStrides(output.tensors, strides, inputSize, anchorsPerStride);
|
|
2099
|
-
const letterbox = output.letterbox;
|
|
2100
|
-
const scale = letterbox?.scale ?? 1;
|
|
2101
|
-
const padX = letterbox?.padX ?? 0;
|
|
2102
|
-
const padY = letterbox?.padY ?? 0;
|
|
2103
|
-
const origW = letterbox?.originalWidth ?? inputSize;
|
|
2104
|
-
const origH = letterbox?.originalHeight ?? inputSize;
|
|
2105
|
-
const candidates = [];
|
|
2106
|
-
for (const stride of strides) {
|
|
2107
|
-
const data = strideData.get(stride);
|
|
2108
|
-
if (!data) continue;
|
|
2109
|
-
const { scores, bboxes, landmarks } = data;
|
|
2110
|
-
const featSize = Math.ceil(inputSize / stride);
|
|
2111
|
-
const numAnchors = featSize * featSize * anchorsPerStride;
|
|
2112
|
-
for (let i = 0; i < numAnchors; i++) {
|
|
2113
|
-
if (i >= scores.length) break;
|
|
2114
|
-
const score = scores[i];
|
|
2115
|
-
if (score <= 0) continue;
|
|
2116
|
-
const gridIdx = Math.floor(i / anchorsPerStride);
|
|
2117
|
-
const cx = (gridIdx % featSize + .5) * stride;
|
|
2118
|
-
const cy = (Math.floor(gridIdx / featSize) + .5) * stride;
|
|
2119
|
-
const x1 = cx - bboxes[i * 4] * stride;
|
|
2120
|
-
const y1 = cy - bboxes[i * 4 + 1] * stride;
|
|
2121
|
-
const x2 = cx + bboxes[i * 4 + 2] * stride;
|
|
2122
|
-
const y2 = cy + bboxes[i * 4 + 3] * stride;
|
|
2123
|
-
const ox1 = Math.max(0, Math.min(origW, (x1 - padX) / scale));
|
|
2124
|
-
const oy1 = Math.max(0, Math.min(origH, (y1 - padY) / scale));
|
|
2125
|
-
const ox2 = Math.max(0, Math.min(origW, (x2 - padX) / scale));
|
|
2126
|
-
const oy2 = Math.max(0, Math.min(origH, (y2 - padY) / scale));
|
|
2127
|
-
if (ox2 - ox1 < 1 || oy2 - oy1 < 1) continue;
|
|
2128
|
-
const det = {
|
|
2129
|
-
class: "face",
|
|
2130
|
-
score: Math.round(score * 1e4) / 1e4,
|
|
2131
|
-
bbox: [
|
|
2132
|
-
Math.round(ox1 * 10) / 10,
|
|
2133
|
-
Math.round(oy1 * 10) / 10,
|
|
2134
|
-
Math.round(ox2 * 10) / 10,
|
|
2135
|
-
Math.round(oy2 * 10) / 10
|
|
2136
|
-
],
|
|
2137
|
-
_xyxy: [
|
|
2138
|
-
ox1,
|
|
2139
|
-
oy1,
|
|
2140
|
-
ox2,
|
|
2141
|
-
oy2
|
|
2142
|
-
]
|
|
2143
|
-
};
|
|
2144
|
-
if (landmarks && i * 10 + 9 < landmarks.length) {
|
|
2145
|
-
det.landmarks = [];
|
|
2146
|
-
for (let p = 0; p < 5; p++) {
|
|
2147
|
-
const lx = (cx + landmarks[i * 10 + p * 2] * stride - padX) / scale;
|
|
2148
|
-
const ly = (cy + landmarks[i * 10 + p * 2 + 1] * stride - padY) / scale;
|
|
2149
|
-
det.landmarks.push({
|
|
2150
|
-
x: Math.round(lx * 10) / 10,
|
|
2151
|
-
y: Math.round(ly * 10) / 10
|
|
2152
|
-
});
|
|
2153
|
-
}
|
|
2154
|
-
}
|
|
2155
|
-
candidates.push(det);
|
|
2156
|
-
}
|
|
2157
|
-
}
|
|
2158
|
-
return {
|
|
2159
|
-
kind: "detections",
|
|
2160
|
-
detections: simpleNms(candidates.map((c) => ({
|
|
2161
|
-
class: c.class,
|
|
2162
|
-
score: c.score,
|
|
2163
|
-
bbox: c.bbox,
|
|
2164
|
-
...c.landmarks ? { landmarks: c.landmarks } : {}
|
|
2165
|
-
})), nmsIouThreshold)
|
|
2166
|
-
};
|
|
2167
|
-
}
|
|
2168
|
-
/** Match ONNX output tensors to SCRFD strides by expected anchor count. */
|
|
2169
|
-
function matchTensorsToStrides(tensors, strides, inputSize, anchorsPerStride) {
|
|
2170
|
-
const scoresByN = /* @__PURE__ */ new Map();
|
|
2171
|
-
const bboxesByN = /* @__PURE__ */ new Map();
|
|
2172
|
-
const landmarksByN = /* @__PURE__ */ new Map();
|
|
2173
|
-
for (const [, tensor] of Object.entries(tensors)) for (const stride of strides) {
|
|
2174
|
-
const featSize = Math.ceil(inputSize / stride);
|
|
2175
|
-
const expectedN = featSize * featSize * anchorsPerStride;
|
|
2176
|
-
if (tensor.length === expectedN) scoresByN.set(expectedN, tensor);
|
|
2177
|
-
else if (tensor.length === expectedN * 4) bboxesByN.set(expectedN, tensor);
|
|
2178
|
-
else if (tensor.length === expectedN * 10) landmarksByN.set(expectedN, tensor);
|
|
2179
|
-
}
|
|
2180
|
-
const result = /* @__PURE__ */ new Map();
|
|
2181
|
-
for (const stride of strides) {
|
|
2182
|
-
const featSize = Math.ceil(inputSize / stride);
|
|
2183
|
-
const n = featSize * featSize * anchorsPerStride;
|
|
2184
|
-
const scores = scoresByN.get(n);
|
|
2185
|
-
const bboxes = bboxesByN.get(n);
|
|
2186
|
-
if (scores && bboxes) result.set(stride, {
|
|
2187
|
-
scores,
|
|
2188
|
-
bboxes,
|
|
2189
|
-
landmarks: landmarksByN.get(n)
|
|
2190
|
-
});
|
|
2191
|
-
}
|
|
2192
|
-
return result;
|
|
2193
|
-
}
|
|
2194
|
-
function postprocessArcface(output, _stepDef) {
|
|
2195
|
-
const structured = tryStructured(output);
|
|
2196
|
-
if (structured) return structured;
|
|
2197
|
-
const tensor = output.tensor;
|
|
2198
|
-
if (!tensor) throw new Error("ArcFace postprocessor: no tensor in engine output");
|
|
2199
|
-
let sumSq = 0;
|
|
2200
|
-
for (let i = 0; i < tensor.length; i++) sumSq += tensor[i] * tensor[i];
|
|
2201
|
-
const norm = Math.sqrt(sumSq);
|
|
2202
|
-
const normalized = Array.from({ length: tensor.length });
|
|
2203
|
-
for (let i = 0; i < tensor.length; i++) normalized[i] = norm === 0 ? 0 : tensor[i] / norm;
|
|
2204
|
-
return {
|
|
2205
|
-
kind: "embedding",
|
|
2206
|
-
embedding: Array.from(tensor),
|
|
2207
|
-
embeddingNorm: normalized
|
|
2208
|
-
};
|
|
2209
|
-
}
|
|
2210
|
-
function postprocessClip(output, _stepDef) {
|
|
2211
|
-
const structured = tryStructured(output);
|
|
2212
|
-
if (structured) return structured;
|
|
2213
|
-
const tensor = output.tensor;
|
|
2214
|
-
if (!tensor) throw new Error("CLIP postprocessor: no tensor in engine output");
|
|
2215
|
-
let sumSq = 0;
|
|
2216
|
-
for (let i = 0; i < tensor.length; i++) sumSq += tensor[i] * tensor[i];
|
|
2217
|
-
const norm = Math.sqrt(sumSq);
|
|
2218
|
-
const normalized = Array.from({ length: tensor.length });
|
|
2219
|
-
for (let i = 0; i < tensor.length; i++) normalized[i] = norm === 0 ? 0 : tensor[i] / norm;
|
|
2220
|
-
return {
|
|
2221
|
-
kind: "embedding",
|
|
2222
|
-
embedding: Array.from(tensor),
|
|
2223
|
-
embeddingNorm: normalized
|
|
2224
|
-
};
|
|
2225
|
-
}
|
|
2226
|
-
function postprocessSoftmax(output, stepDef) {
|
|
2227
|
-
const structured = tryStructured(output);
|
|
2228
|
-
if (structured) return structured;
|
|
2229
|
-
const tensor = output.tensor;
|
|
2230
|
-
if (!tensor) throw new Error("Softmax postprocessor: no tensor in engine output");
|
|
2231
|
-
const labels = stepDef.labels ?? [];
|
|
2232
|
-
let max = -Infinity;
|
|
2233
|
-
for (let i = 0; i < tensor.length; i++) if (tensor[i] > max) max = tensor[i];
|
|
2234
|
-
const exps = new Float32Array(tensor.length);
|
|
2235
|
-
let sum = 0;
|
|
2236
|
-
for (let i = 0; i < tensor.length; i++) {
|
|
2237
|
-
exps[i] = Math.exp(tensor[i] - max);
|
|
2238
|
-
sum += exps[i];
|
|
2239
|
-
}
|
|
2240
|
-
const classifications = [];
|
|
2241
|
-
for (let i = 0; i < exps.length; i++) {
|
|
2242
|
-
const score = exps[i] / sum;
|
|
2243
|
-
if (score >= .01) classifications.push({
|
|
2244
|
-
class: labels[i] ?? String(i),
|
|
2245
|
-
score
|
|
2246
|
-
});
|
|
2247
|
-
}
|
|
2248
|
-
classifications.sort((a, b) => b.score - a.score);
|
|
2249
|
-
return {
|
|
2250
|
-
kind: "classifications",
|
|
2251
|
-
classifications: classifications.slice(0, 5)
|
|
2252
|
-
};
|
|
2253
|
-
}
|
|
2254
|
-
function postprocessCtc(output, stepDef) {
|
|
2255
|
-
const structured = tryStructured(output);
|
|
2256
|
-
if (structured) return structured;
|
|
2257
|
-
const tensor = output.tensor;
|
|
2258
|
-
if (!tensor) throw new Error("CTC postprocessor: no tensor in engine output");
|
|
2259
|
-
const charset = stepDef.charset ?? [];
|
|
2260
|
-
const numChars = charset.length || 97;
|
|
2261
|
-
const seqLen = Math.floor(tensor.length / numChars);
|
|
2262
|
-
const chars = [];
|
|
2263
|
-
let totalScore = 0;
|
|
2264
|
-
let prev = -1;
|
|
2265
|
-
for (let t = 0; t < seqLen; t++) {
|
|
2266
|
-
let bestIdx = 0;
|
|
2267
|
-
let bestVal = tensor[t * numChars];
|
|
2268
|
-
for (let c = 1; c < numChars; c++) {
|
|
2269
|
-
const val = tensor[t * numChars + c];
|
|
2270
|
-
if (val > bestVal) {
|
|
2271
|
-
bestVal = val;
|
|
2272
|
-
bestIdx = c;
|
|
2273
|
-
}
|
|
2274
|
-
}
|
|
2275
|
-
totalScore += bestVal;
|
|
2276
|
-
if (bestIdx !== 0 && bestIdx !== prev) chars.push(charset[bestIdx] ?? "");
|
|
2277
|
-
prev = bestIdx;
|
|
2278
|
-
}
|
|
2279
|
-
const text = chars.join("");
|
|
2280
|
-
const region = stepDef.plateRegion;
|
|
2281
|
-
if (region !== void 0 && region !== "off") {
|
|
2282
|
-
const grammar = TS_PLATE_GRAMMARS[region];
|
|
2283
|
-
if (grammar) return {
|
|
2284
|
-
kind: "text",
|
|
2285
|
-
text,
|
|
2286
|
-
confidence: seqLen > 0 ? totalScore / seqLen : 0,
|
|
2287
|
-
formatValid: grammar.test(text)
|
|
2288
|
-
};
|
|
2289
|
-
}
|
|
2290
|
-
return {
|
|
2291
|
-
kind: "text",
|
|
2292
|
-
text,
|
|
2293
|
-
confidence: seqLen > 0 ? totalScore / seqLen : 0
|
|
2294
|
-
};
|
|
2295
|
-
}
|
|
2296
|
-
/**
|
|
2297
|
-
* Bounding box [x, y, w, h] (mask-pixel space) of the largest 4-connected
|
|
2298
|
-
* foreground component. Port of `_largest_component_bbox` from
|
|
2299
|
-
* `python/postprocessors/saliency.py`.
|
|
2300
|
-
*
|
|
2301
|
-
* Returns null when there are no foreground pixels.
|
|
2302
|
-
*/
|
|
2303
|
-
function largestComponentBbox(binary, w, h) {
|
|
2304
|
-
const seeds = [];
|
|
2305
|
-
for (let row = 0; row < h; row++) for (let col = 0; col < w; col++) if ((binary[row * w + col] ?? 0) > 0) seeds.push([row, col]);
|
|
2306
|
-
if (seeds.length === 0) return null;
|
|
2307
|
-
const visited = new Uint8Array(w * h);
|
|
2308
|
-
let best = null;
|
|
2309
|
-
for (const [sy, sx] of seeds) {
|
|
2310
|
-
const seedIdx = sy * w + sx;
|
|
2311
|
-
if (visited[seedIdx] === 1) continue;
|
|
2312
|
-
const stack = [[sy, sx]];
|
|
2313
|
-
visited[seedIdx] = 1;
|
|
2314
|
-
let minX = sx;
|
|
2315
|
-
let maxX = sx;
|
|
2316
|
-
let minY = sy;
|
|
2317
|
-
let maxY = sy;
|
|
2318
|
-
let area = 0;
|
|
2319
|
-
while (stack.length > 0) {
|
|
2320
|
-
const [cy, cx] = stack.pop();
|
|
2321
|
-
area += 1;
|
|
2322
|
-
if (cx < minX) minX = cx;
|
|
2323
|
-
if (cx > maxX) maxX = cx;
|
|
2324
|
-
if (cy < minY) minY = cy;
|
|
2325
|
-
if (cy > maxY) maxY = cy;
|
|
2326
|
-
const neighbours = [
|
|
2327
|
-
[cy - 1, cx],
|
|
2328
|
-
[cy + 1, cx],
|
|
2329
|
-
[cy, cx - 1],
|
|
2330
|
-
[cy, cx + 1]
|
|
2331
|
-
];
|
|
2332
|
-
for (const [ny, nx] of neighbours) {
|
|
2333
|
-
if (ny < 0 || ny >= h || nx < 0 || nx >= w) continue;
|
|
2334
|
-
const nIdx = ny * w + nx;
|
|
2335
|
-
if ((binary[nIdx] ?? 0) > 0 && visited[nIdx] !== 1) {
|
|
2336
|
-
visited[nIdx] = 1;
|
|
2337
|
-
stack.push([ny, nx]);
|
|
2338
|
-
}
|
|
2339
|
-
}
|
|
2340
|
-
}
|
|
2341
|
-
if (best === null || area > best.area) best = {
|
|
2342
|
-
area,
|
|
2343
|
-
minX,
|
|
2344
|
-
minY,
|
|
2345
|
-
maxX,
|
|
2346
|
-
maxY
|
|
2347
|
-
};
|
|
2348
|
-
}
|
|
2349
|
-
if (best === null) return null;
|
|
2350
|
-
return [
|
|
2351
|
-
best.minX,
|
|
2352
|
-
best.minY,
|
|
2353
|
-
best.maxX - best.minX + 1,
|
|
2354
|
-
best.maxY - best.minY + 1
|
|
2355
|
-
];
|
|
2356
|
-
}
|
|
2357
|
-
function postprocessSaliency(output, _stepDef) {
|
|
2358
|
-
const structured = tryStructured(output);
|
|
2359
|
-
if (structured) return structured;
|
|
2360
|
-
const tensor = output.tensor;
|
|
2361
|
-
if (!tensor) throw new Error("Saliency postprocessor: no tensor in engine output");
|
|
2362
|
-
const binary = new Uint8Array(tensor.length);
|
|
2363
|
-
for (let i = 0; i < tensor.length; i++) binary[i] = 1 / (1 + Math.exp(-tensor[i])) > .5 ? 255 : 0;
|
|
2364
|
-
const side = Math.round(Math.sqrt(tensor.length));
|
|
2365
|
-
const mask = Buffer.from(binary).toString("base64");
|
|
2366
|
-
const maskBbox = largestComponentBbox(binary, side, side);
|
|
2367
|
-
if (maskBbox !== null) return {
|
|
2368
|
-
kind: "mask",
|
|
2369
|
-
mask,
|
|
2370
|
-
maskWidth: side,
|
|
2371
|
-
maskHeight: side,
|
|
2372
|
-
maskBbox
|
|
2373
|
-
};
|
|
2374
|
-
return {
|
|
2375
|
-
kind: "mask",
|
|
2376
|
-
mask,
|
|
2377
|
-
maskWidth: side,
|
|
2378
|
-
maskHeight: side
|
|
2379
|
-
};
|
|
2380
|
-
}
|
|
2381
|
-
function postprocessYoloSeg(output, stepDef, nmsIouThreshold) {
|
|
2382
|
-
const structured = tryStructured(output);
|
|
2383
|
-
if (structured) return structured;
|
|
2384
|
-
const tensors = output.tensors;
|
|
2385
|
-
if (!tensors) throw new Error("YOLO-seg postprocessor: no tensors in engine output");
|
|
2386
|
-
const labels = stepDef.labels ?? [];
|
|
2387
|
-
const numClasses = labels.length || 80;
|
|
2388
|
-
const numMaskCoeffs = 32;
|
|
2389
|
-
const protoSize = 160;
|
|
2390
|
-
const letterbox = output.letterbox;
|
|
2391
|
-
let detTensor;
|
|
2392
|
-
let protoTensor;
|
|
2393
|
-
let detRows = 300;
|
|
2394
|
-
let detCols = 0;
|
|
2395
|
-
for (const [, tensor] of Object.entries(tensors)) {
|
|
2396
|
-
if (tensor.length === numMaskCoeffs * protoSize * protoSize) {
|
|
2397
|
-
protoTensor = tensor;
|
|
2398
|
-
continue;
|
|
2399
|
-
}
|
|
2400
|
-
const cols = 38;
|
|
2401
|
-
if (tensor.length % cols === 0) {
|
|
2402
|
-
detTensor = tensor;
|
|
2403
|
-
detRows = tensor.length / cols;
|
|
2404
|
-
detCols = cols;
|
|
2405
|
-
continue;
|
|
2406
|
-
}
|
|
2407
|
-
const rawCols = 4 + numClasses + numMaskCoeffs;
|
|
2408
|
-
if (tensor.length % rawCols === 0 && !detTensor) {
|
|
2409
|
-
detTensor = tensor;
|
|
2410
|
-
detRows = tensor.length / rawCols;
|
|
2411
|
-
detCols = rawCols;
|
|
2412
|
-
}
|
|
2413
|
-
}
|
|
2414
|
-
if (!detTensor) throw new Error("YOLO-seg postprocessor: could not find detection tensor");
|
|
2415
|
-
if (!protoTensor) throw new Error("YOLO-seg postprocessor: could not find prototype tensor");
|
|
2416
|
-
const isNmsFormat = detCols === 38;
|
|
2417
|
-
const dets = [];
|
|
2418
|
-
for (let i = 0; i < detRows; i++) {
|
|
2419
|
-
const offset = i * detCols;
|
|
2420
|
-
let x1, y1, x2, y2;
|
|
2421
|
-
let bestScore;
|
|
2422
|
-
let bestClass;
|
|
2423
|
-
let coeffStart;
|
|
2424
|
-
if (isNmsFormat) {
|
|
2425
|
-
x1 = detTensor[offset];
|
|
2426
|
-
y1 = detTensor[offset + 1];
|
|
2427
|
-
x2 = detTensor[offset + 2];
|
|
2428
|
-
y2 = detTensor[offset + 3];
|
|
2429
|
-
bestScore = detTensor[offset + 4];
|
|
2430
|
-
bestClass = detTensor[offset + 5];
|
|
2431
|
-
coeffStart = offset + 6;
|
|
2432
|
-
if (bestScore <= 0) continue;
|
|
2433
|
-
if (bestClass < 0) continue;
|
|
2434
|
-
} else {
|
|
2435
|
-
const cx = detTensor[offset];
|
|
2436
|
-
const cy = detTensor[offset + 1];
|
|
2437
|
-
const w = detTensor[offset + 2];
|
|
2438
|
-
const h = detTensor[offset + 3];
|
|
2439
|
-
bestScore = -Infinity;
|
|
2440
|
-
bestClass = 0;
|
|
2441
|
-
for (let j = 0; j < numClasses; j++) {
|
|
2442
|
-
const score = detTensor[offset + 4 + j];
|
|
2443
|
-
if (score > bestScore) {
|
|
2444
|
-
bestScore = score;
|
|
2445
|
-
bestClass = j;
|
|
2446
|
-
}
|
|
2447
|
-
}
|
|
2448
|
-
if (bestScore <= 0) continue;
|
|
2449
|
-
x1 = cx - w / 2;
|
|
2450
|
-
y1 = cy - h / 2;
|
|
2451
|
-
x2 = cx + w / 2;
|
|
2452
|
-
y2 = cy + h / 2;
|
|
2453
|
-
coeffStart = offset + 4 + numClasses;
|
|
2454
|
-
}
|
|
2455
|
-
const coeffs = new Float32Array(numMaskCoeffs);
|
|
2456
|
-
for (let j = 0; j < numMaskCoeffs; j++) coeffs[j] = detTensor[coeffStart + j];
|
|
2457
|
-
const maskPixels = protoSize * protoSize;
|
|
2458
|
-
const maskRaw = new Float32Array(maskPixels);
|
|
2459
|
-
for (let p = 0; p < maskPixels; p++) {
|
|
2460
|
-
let sum = 0;
|
|
2461
|
-
for (let c = 0; c < numMaskCoeffs; c++) sum += coeffs[c] * protoTensor[c * maskPixels + p];
|
|
2462
|
-
maskRaw[p] = 1 / (1 + Math.exp(-sum));
|
|
2463
|
-
}
|
|
2464
|
-
const protoScale = protoSize / (stepDef.models[0]?.inputSize.width ?? 640);
|
|
2465
|
-
const px1 = Math.max(0, Math.floor(x1 * protoScale));
|
|
2466
|
-
const py1 = Math.max(0, Math.floor(y1 * protoScale));
|
|
2467
|
-
const px2 = Math.min(protoSize, Math.ceil(x2 * protoScale));
|
|
2468
|
-
const py2 = Math.min(protoSize, Math.ceil(y2 * protoScale));
|
|
2469
|
-
const cropW = Math.max(1, px2 - px1);
|
|
2470
|
-
const cropH = Math.max(1, py2 - py1);
|
|
2471
|
-
const cropped = new Uint8Array(cropW * cropH);
|
|
2472
|
-
for (let row = 0; row < cropH; row++) for (let col = 0; col < cropW; col++) {
|
|
2473
|
-
const srcIdx = (py1 + row) * protoSize + (px1 + col);
|
|
2474
|
-
cropped[row * cropW + col] = maskRaw[srcIdx] > .5 ? 255 : 0;
|
|
2475
|
-
}
|
|
2476
|
-
let ox1 = x1;
|
|
2477
|
-
let oy1 = y1;
|
|
2478
|
-
let ox2 = x2;
|
|
2479
|
-
let oy2 = y2;
|
|
2480
|
-
if (letterbox) {
|
|
2481
|
-
ox1 = (x1 - letterbox.padX) / letterbox.scale;
|
|
2482
|
-
oy1 = (y1 - letterbox.padY) / letterbox.scale;
|
|
2483
|
-
ox2 = (x2 - letterbox.padX) / letterbox.scale;
|
|
2484
|
-
oy2 = (y2 - letterbox.padY) / letterbox.scale;
|
|
2485
|
-
}
|
|
2486
|
-
const label = labels[bestClass] ?? String(bestClass);
|
|
2487
|
-
const maskB64 = Buffer.from(cropped).toString("base64");
|
|
2488
|
-
dets.push({
|
|
2489
|
-
class: label,
|
|
2490
|
-
score: Math.round(bestScore * 1e4) / 1e4,
|
|
2491
|
-
bbox: [
|
|
2492
|
-
Math.round(ox1 * 10) / 10,
|
|
2493
|
-
Math.round(oy1 * 10) / 10,
|
|
2494
|
-
Math.round(ox2 * 10) / 10,
|
|
2495
|
-
Math.round(oy2 * 10) / 10
|
|
2496
|
-
],
|
|
2497
|
-
mask: maskB64,
|
|
2498
|
-
maskWidth: cropW,
|
|
2499
|
-
maskHeight: cropH
|
|
2500
|
-
});
|
|
2501
|
-
}
|
|
2502
|
-
const keptBoxes = simpleNms(dets.map((d) => ({
|
|
2503
|
-
class: d.class,
|
|
2504
|
-
score: d.score,
|
|
2505
|
-
bbox: d.bbox
|
|
2506
|
-
})), nmsIouThreshold);
|
|
2507
|
-
const keptSet = new Set(keptBoxes.map((d) => `${d.bbox[0]}_${d.bbox[1]}_${d.bbox[2]}_${d.bbox[3]}_${d.score}`));
|
|
2508
|
-
return {
|
|
2509
|
-
kind: "detections",
|
|
2510
|
-
detections: dets.filter((d) => keptSet.has(`${d.bbox[0]}_${d.bbox[1]}_${d.bbox[2]}_${d.bbox[3]}_${d.score}`))
|
|
2511
|
-
};
|
|
2512
|
-
}
|
|
2513
|
-
function postprocessYamnet(output, _stepDef) {
|
|
2514
|
-
const structured = tryStructured(output);
|
|
2515
|
-
if (structured) return structured;
|
|
2516
|
-
throw new Error("YAMNet TypeScript postprocessing not implemented. Use Python backend or Apple SoundAnalysis.");
|
|
2517
|
-
}
|
|
2518
|
-
var DISPATCH = {
|
|
2519
|
-
yolo: postprocessYolo,
|
|
2520
|
-
ssd: postprocessSsd,
|
|
2521
|
-
"yolo-seg": postprocessYoloSeg,
|
|
2522
|
-
scrfd: postprocessScrfd,
|
|
2523
|
-
arcface: postprocessArcface,
|
|
2524
|
-
clip: postprocessClip,
|
|
2525
|
-
softmax: postprocessSoftmax,
|
|
2526
|
-
ctc: postprocessCtc,
|
|
2527
|
-
saliency: postprocessSaliency,
|
|
2528
|
-
yamnet: postprocessYamnet
|
|
2529
|
-
};
|
|
2530
|
-
/**
|
|
2531
|
-
* Dispatch postprocessing based on step definition's postprocessor type.
|
|
2532
|
-
*
|
|
2533
|
-
* For Python backends: output.structured is already populated → passthrough.
|
|
2534
|
-
* For Node.js ONNX: raw tensors → postprocess in TypeScript.
|
|
2535
|
-
*
|
|
2536
|
-
* Both paths pass through normalizeOutput() to ensure consistent format
|
|
2537
|
-
* (e.g., classification top-K, alternates).
|
|
2538
|
-
*/
|
|
2539
|
-
function dispatchPostprocess(output, stepDef, settings) {
|
|
2540
|
-
const fn = DISPATCH[stepDef.postprocessor];
|
|
2541
|
-
if (!fn) throw new Error(`Unknown postprocessor type: "${stepDef.postprocessor}"`);
|
|
2542
|
-
const raw = settings?.["nmsIouThreshold"];
|
|
2543
|
-
return normalizeOutput(fn(output, stepDef, typeof raw === "number" && raw > 0 ? raw : DEFAULT_NMS_IOU));
|
|
2544
|
-
}
|
|
2545
|
-
/**
|
|
2546
|
-
* Normalize any StepOutput to a consistent format.
|
|
2547
|
-
* Single funnel for both Python and TypeScript postprocessor paths.
|
|
2548
|
-
*
|
|
2549
|
-
* Classifications: keep only top-1 in classifications, move full list to alternates.
|
|
2550
|
-
*/
|
|
2551
|
-
function normalizeOutput(output) {
|
|
2552
|
-
if (output.kind !== "classifications") return output;
|
|
2553
|
-
const all = output.classifications;
|
|
2554
|
-
if (all.length <= 1) return output;
|
|
2555
|
-
return {
|
|
2556
|
-
kind: "classifications",
|
|
2557
|
-
classifications: all.slice(0, 1),
|
|
2558
|
-
alternates: all
|
|
2559
|
-
};
|
|
2560
|
-
}
|
|
2561
|
-
function simpleNms(dets, iouThreshold) {
|
|
2562
|
-
if (dets.length === 0) return [];
|
|
2563
|
-
const sorted = [...dets].toSorted((a, b) => b.score - a.score);
|
|
2564
|
-
const kept = [];
|
|
2565
|
-
const suppressed = /* @__PURE__ */ new Set();
|
|
2566
|
-
for (let i = 0; i < sorted.length; i++) {
|
|
2567
|
-
if (suppressed.has(i)) continue;
|
|
2568
|
-
kept.push(sorted[i]);
|
|
2569
|
-
for (let j = i + 1; j < sorted.length; j++) {
|
|
2570
|
-
if (suppressed.has(j)) continue;
|
|
2571
|
-
if (iou(sorted[i].bbox, sorted[j].bbox) > iouThreshold) suppressed.add(j);
|
|
2572
|
-
}
|
|
2573
|
-
}
|
|
2574
|
-
return kept;
|
|
2575
|
-
}
|
|
2576
|
-
function iou(a, b) {
|
|
2577
|
-
const ix1 = Math.max(a[0], b[0]);
|
|
2578
|
-
const iy1 = Math.max(a[1], b[1]);
|
|
2579
|
-
const ix2 = Math.min(a[2], b[2]);
|
|
2580
|
-
const iy2 = Math.min(a[3], b[3]);
|
|
2581
|
-
const inter = Math.max(0, ix2 - ix1) * Math.max(0, iy2 - iy1);
|
|
2582
|
-
if (inter === 0) return 0;
|
|
2583
|
-
return inter / ((a[2] - a[0]) * (a[3] - a[1]) + (b[2] - b[0]) * (b[3] - b[1]) - inter);
|
|
2584
|
-
}
|
|
2585
|
-
//#endregion
|
|
2586
2053
|
//#region src/detection-pipeline/pipeline/crop-utils.ts
|
|
2587
2054
|
/**
|
|
2588
2055
|
* Crop utilities — ROI extraction and bbox coordinate transforms.
|
|
@@ -2632,40 +2099,250 @@ function isBboxDegenerate(bbox) {
|
|
|
2632
2099
|
return bbox[2] - bbox[0] < 1 || bbox[3] - bbox[1] < 1;
|
|
2633
2100
|
}
|
|
2634
2101
|
//#endregion
|
|
2635
|
-
//#region src/detection-pipeline/pipeline/
|
|
2102
|
+
//#region src/detection-pipeline/pipeline/crop-zone.ts
|
|
2636
2103
|
/**
|
|
2637
|
-
*
|
|
2638
|
-
*
|
|
2639
|
-
*
|
|
2640
|
-
*
|
|
2641
|
-
* must land on fixed canonical positions. Feeding a raw axis-aligned bbox crop
|
|
2642
|
-
* stretched to 112x112 (the previous behaviour) collapses embeddings toward a
|
|
2643
|
-
* common direction — different people end up with ~0.99 cosine similarity.
|
|
2644
|
-
*
|
|
2645
|
-
* This module computes the least-squares similarity transform (rotation +
|
|
2646
|
-
* uniform scale + translation, the cv2.estimateAffinePartial2D recipe) that
|
|
2647
|
-
* maps SCRFD's 5 facial landmarks onto the canonical template, then resamples
|
|
2648
|
-
* the source pixels into a fixed-size aligned crop with bilinear interpolation.
|
|
2104
|
+
* Resolve the absolute-pixel crop bbox for a `crop-zone` root detector: the
|
|
2105
|
+
* bounding box of the UNION of every polygon referenced by the device's
|
|
2106
|
+
* ENABLED `package`-stage zone rules. Zone polygons are normalized (0..1); the
|
|
2107
|
+
* union is clamped to [0,1] then scaled to the frame's pixel dimensions.
|
|
2649
2108
|
*
|
|
2650
|
-
*
|
|
2651
|
-
*
|
|
2652
|
-
*
|
|
2653
|
-
|
|
2654
|
-
/**
|
|
2655
|
-
* Canonical ArcFace 5-point template for a 112x112 aligned crop
|
|
2656
|
-
* (insightface reference points). Order matches SCRFD landmark output:
|
|
2657
|
-
* left-eye, right-eye, nose, left-mouth-corner, right-mouth-corner.
|
|
2109
|
+
* Returns `null` when there is nothing usable to crop to — no enabled rules, no
|
|
2110
|
+
* referenced geometry, or a degenerate result — in which case the caller falls
|
|
2111
|
+
* back to full-frame inference (behaviour identical to before the crop-zone
|
|
2112
|
+
* plumbing).
|
|
2658
2113
|
*/
|
|
2659
|
-
|
|
2660
|
-
|
|
2661
|
-
|
|
2662
|
-
|
|
2663
|
-
|
|
2664
|
-
|
|
2665
|
-
|
|
2666
|
-
|
|
2667
|
-
|
|
2668
|
-
|
|
2114
|
+
function resolvePackageCropBbox(zones, packageRules, frameWidth, frameHeight) {
|
|
2115
|
+
if (frameWidth <= 0 || frameHeight <= 0) return null;
|
|
2116
|
+
const enabledRules = packageRules.filter((r) => r.enabled !== false);
|
|
2117
|
+
if (enabledRules.length === 0) return null;
|
|
2118
|
+
const zoneIds = /* @__PURE__ */ new Set();
|
|
2119
|
+
for (const rule of enabledRules) for (const id of rule.zoneIds) zoneIds.add(id);
|
|
2120
|
+
if (zoneIds.size === 0) return null;
|
|
2121
|
+
const zoneById = new Map(zones.map((z) => [z.id, z]));
|
|
2122
|
+
let minX = Number.POSITIVE_INFINITY;
|
|
2123
|
+
let minY = Number.POSITIVE_INFINITY;
|
|
2124
|
+
let maxX = Number.NEGATIVE_INFINITY;
|
|
2125
|
+
let maxY = Number.NEGATIVE_INFINITY;
|
|
2126
|
+
let sawPoint = false;
|
|
2127
|
+
for (const id of zoneIds) {
|
|
2128
|
+
const zone = zoneById.get(id);
|
|
2129
|
+
if (!zone || zone.polygon.length === 0) continue;
|
|
2130
|
+
for (const point of zone.polygon) {
|
|
2131
|
+
sawPoint = true;
|
|
2132
|
+
if (point.x < minX) minX = point.x;
|
|
2133
|
+
if (point.y < minY) minY = point.y;
|
|
2134
|
+
if (point.x > maxX) maxX = point.x;
|
|
2135
|
+
if (point.y > maxY) maxY = point.y;
|
|
2136
|
+
}
|
|
2137
|
+
}
|
|
2138
|
+
if (!sawPoint) return null;
|
|
2139
|
+
const clamp01 = (v) => Math.max(0, Math.min(1, v));
|
|
2140
|
+
const bbox = [
|
|
2141
|
+
clamp01(minX) * frameWidth,
|
|
2142
|
+
clamp01(minY) * frameHeight,
|
|
2143
|
+
clamp01(maxX) * frameWidth,
|
|
2144
|
+
clamp01(maxY) * frameHeight
|
|
2145
|
+
];
|
|
2146
|
+
if (isBboxDegenerate(bbox)) return null;
|
|
2147
|
+
return bbox;
|
|
2148
|
+
}
|
|
2149
|
+
//#endregion
|
|
2150
|
+
//#region src/detection-pipeline/postprocess/dispatch.ts
|
|
2151
|
+
var VALID_KINDS = new Set([
|
|
2152
|
+
"detections",
|
|
2153
|
+
"classifications",
|
|
2154
|
+
"embedding",
|
|
2155
|
+
"text",
|
|
2156
|
+
"mask"
|
|
2157
|
+
]);
|
|
2158
|
+
/** Every postprocessor the Python pool implements — the dispatch table's keys
|
|
2159
|
+
* survived the raw-tensor removal as a config-drift guard: an unknown
|
|
2160
|
+
* postprocessor in a step definition still fails fast here. */
|
|
2161
|
+
var KNOWN_POSTPROCESSORS = new Set([
|
|
2162
|
+
"yolo",
|
|
2163
|
+
"ssd",
|
|
2164
|
+
"yolo-seg",
|
|
2165
|
+
"scrfd",
|
|
2166
|
+
"arcface",
|
|
2167
|
+
"clip",
|
|
2168
|
+
"softmax",
|
|
2169
|
+
"ctc",
|
|
2170
|
+
"saliency",
|
|
2171
|
+
"yamnet"
|
|
2172
|
+
]);
|
|
2173
|
+
/**
|
|
2174
|
+
* Type guard: validates that a structured payload from the Python pool is a
|
|
2175
|
+
* well-formed StepOutput discriminated union.
|
|
2176
|
+
*
|
|
2177
|
+
* The Python inference_pool.py always sets `output.structured` with a `kind`
|
|
2178
|
+
* field. This guard narrows `Record<string, unknown>` to `StepOutput` without
|
|
2179
|
+
* resorting to double-cast.
|
|
2180
|
+
*/
|
|
2181
|
+
function isStepOutput(value) {
|
|
2182
|
+
return typeof value === "object" && value !== null && typeof value["kind"] === "string" && VALID_KINDS.has(value["kind"]);
|
|
2183
|
+
}
|
|
2184
|
+
/**
|
|
2185
|
+
* Validate + normalize a Python-pool engine output into a StepOutput.
|
|
2186
|
+
*/
|
|
2187
|
+
function dispatchPostprocess(output, stepDef) {
|
|
2188
|
+
if (output.dropped === true) return {
|
|
2189
|
+
kind: "detections",
|
|
2190
|
+
detections: []
|
|
2191
|
+
};
|
|
2192
|
+
if (!KNOWN_POSTPROCESSORS.has(stepDef.postprocessor)) throw new Error(`Unknown postprocessor type: "${stepDef.postprocessor}"`);
|
|
2193
|
+
if (!output.structured) throw new Error(`Postprocessing for step "${stepDef.id}" (${stepDef.postprocessor}) runs in the Python inference pool — the engine output carried no structured payload. The Node.js raw-tensor path was removed; there is nothing to fall back to.`);
|
|
2194
|
+
if (!isStepOutput(output.structured)) throw new Error(`Python pool returned structured output with unexpected kind: ${JSON.stringify(output.structured["kind"])}`);
|
|
2195
|
+
return normalizeOutput(output.structured);
|
|
2196
|
+
}
|
|
2197
|
+
/**
|
|
2198
|
+
* Normalize any StepOutput to a consistent format — the single funnel every
|
|
2199
|
+
* pool payload passes through.
|
|
2200
|
+
*
|
|
2201
|
+
* Classifications: keep only top-1 in classifications, move full list to alternates.
|
|
2202
|
+
*/
|
|
2203
|
+
function normalizeOutput(output) {
|
|
2204
|
+
if (output.kind !== "classifications") return output;
|
|
2205
|
+
const all = output.classifications;
|
|
2206
|
+
if (all.length <= 1) return output;
|
|
2207
|
+
return {
|
|
2208
|
+
kind: "classifications",
|
|
2209
|
+
classifications: all.slice(0, 1),
|
|
2210
|
+
alternates: all
|
|
2211
|
+
};
|
|
2212
|
+
}
|
|
2213
|
+
//#endregion
|
|
2214
|
+
//#region src/detection-pipeline/pipeline/execution-trace.ts
|
|
2215
|
+
var traceCounter = 0;
|
|
2216
|
+
var ExecutionTraceBuilder = class {
|
|
2217
|
+
verbosity;
|
|
2218
|
+
deviceId;
|
|
2219
|
+
frameWidth;
|
|
2220
|
+
frameHeight;
|
|
2221
|
+
engineRuntime;
|
|
2222
|
+
steps = [];
|
|
2223
|
+
startTime;
|
|
2224
|
+
constructor(verbosity, deviceId, frameWidth, frameHeight, engineRuntime) {
|
|
2225
|
+
this.verbosity = verbosity;
|
|
2226
|
+
this.deviceId = deviceId;
|
|
2227
|
+
this.frameWidth = frameWidth;
|
|
2228
|
+
this.frameHeight = frameHeight;
|
|
2229
|
+
this.engineRuntime = engineRuntime;
|
|
2230
|
+
this.startTime = Date.now();
|
|
2231
|
+
}
|
|
2232
|
+
/** Whether trace collection is active. */
|
|
2233
|
+
get isActive() {
|
|
2234
|
+
return this.verbosity !== "off";
|
|
2235
|
+
}
|
|
2236
|
+
/**
|
|
2237
|
+
* Record a completed step execution.
|
|
2238
|
+
* No-op if verbosity is 'off'.
|
|
2239
|
+
*/
|
|
2240
|
+
addStep(params) {
|
|
2241
|
+
if (this.verbosity === "off") return;
|
|
2242
|
+
const totalMs = params.preprocessMs + params.inferenceMs + params.postprocessMs;
|
|
2243
|
+
const trace = {
|
|
2244
|
+
stepId: params.stepId,
|
|
2245
|
+
modelId: params.modelId,
|
|
2246
|
+
slot: params.slot,
|
|
2247
|
+
postprocessor: params.postprocessor,
|
|
2248
|
+
preprocessMs: Math.round(params.preprocessMs * 100) / 100,
|
|
2249
|
+
inferenceMs: Math.round(params.inferenceMs * 100) / 100,
|
|
2250
|
+
postprocessMs: Math.round(params.postprocessMs * 100) / 100,
|
|
2251
|
+
totalMs: Math.round(totalMs * 100) / 100,
|
|
2252
|
+
inputType: params.inputType,
|
|
2253
|
+
inputSize: {
|
|
2254
|
+
width: params.inputWidth,
|
|
2255
|
+
height: params.inputHeight
|
|
2256
|
+
},
|
|
2257
|
+
parentDetection: this.verbosity === "full" ? params.parentDetection : void 0,
|
|
2258
|
+
outputKind: params.output.kind,
|
|
2259
|
+
outputCount: countOutput(params.output),
|
|
2260
|
+
topResult: this.verbosity === "full" ? formatTopResult(params.output) : void 0,
|
|
2261
|
+
error: params.error
|
|
2262
|
+
};
|
|
2263
|
+
this.steps.push(trace);
|
|
2264
|
+
}
|
|
2265
|
+
/**
|
|
2266
|
+
* Finalize and return the complete execution trace.
|
|
2267
|
+
* Returns null if verbosity is 'off'.
|
|
2268
|
+
*/
|
|
2269
|
+
build(detectionCount) {
|
|
2270
|
+
if (this.verbosity === "off") return null;
|
|
2271
|
+
const totalMs = Date.now() - this.startTime;
|
|
2272
|
+
return {
|
|
2273
|
+
traceId: `trace-${Date.now()}-${++traceCounter}`,
|
|
2274
|
+
deviceId: this.deviceId,
|
|
2275
|
+
timestamp: this.startTime,
|
|
2276
|
+
frameSize: {
|
|
2277
|
+
width: this.frameWidth,
|
|
2278
|
+
height: this.frameHeight
|
|
2279
|
+
},
|
|
2280
|
+
engineRuntime: this.engineRuntime,
|
|
2281
|
+
steps: this.steps,
|
|
2282
|
+
totalMs,
|
|
2283
|
+
detectionCount
|
|
2284
|
+
};
|
|
2285
|
+
}
|
|
2286
|
+
};
|
|
2287
|
+
function countOutput(output) {
|
|
2288
|
+
switch (output.kind) {
|
|
2289
|
+
case "detections": return output.detections.length;
|
|
2290
|
+
case "classifications": return output.classifications.length;
|
|
2291
|
+
case "embedding": return 1;
|
|
2292
|
+
case "text": return output.text.length > 0 ? 1 : 0;
|
|
2293
|
+
case "mask": return 1;
|
|
2294
|
+
}
|
|
2295
|
+
}
|
|
2296
|
+
function formatTopResult(output) {
|
|
2297
|
+
switch (output.kind) {
|
|
2298
|
+
case "detections": {
|
|
2299
|
+
const top = output.detections[0];
|
|
2300
|
+
return top ? `${top.class} ${top.score.toFixed(2)}` : void 0;
|
|
2301
|
+
}
|
|
2302
|
+
case "classifications": {
|
|
2303
|
+
const top = output.classifications[0];
|
|
2304
|
+
return top ? `${top.class} ${top.score.toFixed(2)}` : void 0;
|
|
2305
|
+
}
|
|
2306
|
+
case "embedding": return `embedding[${output.embedding.length}]`;
|
|
2307
|
+
case "text": return output.text || void 0;
|
|
2308
|
+
case "mask": return `mask ${output.maskWidth}×${output.maskHeight}`;
|
|
2309
|
+
}
|
|
2310
|
+
}
|
|
2311
|
+
//#endregion
|
|
2312
|
+
//#region src/detection-pipeline/pipeline/face-align.ts
|
|
2313
|
+
/**
|
|
2314
|
+
* Face alignment — landmark-based similarity warp to the ArcFace template.
|
|
2315
|
+
*
|
|
2316
|
+
* ArcFace (and most face-recognition embedders) are only discriminative when
|
|
2317
|
+
* the input is a *landmark-aligned* 112x112 crop: eyes, nose and mouth corners
|
|
2318
|
+
* must land on fixed canonical positions. Feeding a raw axis-aligned bbox crop
|
|
2319
|
+
* stretched to 112x112 (the previous behaviour) collapses embeddings toward a
|
|
2320
|
+
* common direction — different people end up with ~0.99 cosine similarity.
|
|
2321
|
+
*
|
|
2322
|
+
* This module computes the least-squares similarity transform (rotation +
|
|
2323
|
+
* uniform scale + translation, the cv2.estimateAffinePartial2D recipe) that
|
|
2324
|
+
* maps SCRFD's 5 facial landmarks onto the canonical template, then resamples
|
|
2325
|
+
* the source pixels into a fixed-size aligned crop with bilinear interpolation.
|
|
2326
|
+
*
|
|
2327
|
+
* The warp is done in pure JS on a raw RGB buffer (a few thousand samples per
|
|
2328
|
+
* face — negligible cost) so it is fully deterministic and unit-testable, and
|
|
2329
|
+
* needs no native affine primitive nor any change to the Python inference pool.
|
|
2330
|
+
*/
|
|
2331
|
+
/**
|
|
2332
|
+
* Canonical ArcFace 5-point template for a 112x112 aligned crop
|
|
2333
|
+
* (insightface reference points). Order matches SCRFD landmark output:
|
|
2334
|
+
* left-eye, right-eye, nose, left-mouth-corner, right-mouth-corner.
|
|
2335
|
+
*/
|
|
2336
|
+
var ARCFACE_TEMPLATE_112 = [
|
|
2337
|
+
{
|
|
2338
|
+
x: 38.2946,
|
|
2339
|
+
y: 51.6963
|
|
2340
|
+
},
|
|
2341
|
+
{
|
|
2342
|
+
x: 73.5318,
|
|
2343
|
+
y: 51.5014
|
|
2344
|
+
},
|
|
2345
|
+
{
|
|
2669
2346
|
x: 56.0252,
|
|
2670
2347
|
y: 71.7366
|
|
2671
2348
|
},
|
|
@@ -2937,63 +2614,6 @@ async function alignFaceCrop(fullFrameJpeg, faceBbox, landmarksImageSpace, image
|
|
|
2937
2614
|
height: aligned.height
|
|
2938
2615
|
};
|
|
2939
2616
|
}
|
|
2940
|
-
//#endregion
|
|
2941
|
-
//#region src/detection-pipeline/pipeline/native-child-crop.ts
|
|
2942
|
-
/**
|
|
2943
|
-
* NATIVE-resolution crop of a LEAF crop-child ROI (plate-ocr, leaf classifiers)
|
|
2944
|
-
* — the plate-side mirror of the face path's {@link ./face-align.buildAlignedFaceCrop}.
|
|
2945
|
-
*
|
|
2946
|
-
* On the detail plane the executor runs a child model against a parent crop
|
|
2947
|
-
* (e.g. the native vehicle crop). A leaf child's ROI (`parentDetection.bbox`,
|
|
2948
|
-
* in the parent crop's PIXEL space) is what the child model reads. Cutting it
|
|
2949
|
-
* from the parent tile with {@link ./crop-utils.cropJpeg} bounds the child input
|
|
2950
|
-
* to the tile's resolution — fatal for OCR on a small, distant plate. When a
|
|
2951
|
-
* native-crop provider is bound to the frame, we instead resolve the SAME ROI
|
|
2952
|
-
* straight from the frame's retained NATIVE surface (the provider re-composes
|
|
2953
|
-
* the crop-normalized ROI into frame space — see {@link ./native-crop-compose}),
|
|
2954
|
-
* giving the model native pixels. A miss/degenerate returns `null` so the caller
|
|
2955
|
-
* falls back to the existing tile crop (never an upscale — native or the tile).
|
|
2956
|
-
*/
|
|
2957
|
-
/**
|
|
2958
|
-
* Generous native-width cap for a leaf child crop. A plate ROI is a few hundred
|
|
2959
|
-
* native pixels wide, so this never binds for plates (effectively uncapped —
|
|
2960
|
-
* the quality path the task requires); it only bounds a pathologically large
|
|
2961
|
-
* whole-object classifier ROI so the in-process native fetch/encode stays cheap.
|
|
2962
|
-
*/
|
|
2963
|
-
var NATIVE_CHILD_CROP_MAX_WIDTH = 1920;
|
|
2964
|
-
/**
|
|
2965
|
-
* Resolve `bbox` (a parent-crop PIXEL rectangle `[x1,y1,x2,y2]`) at native
|
|
2966
|
-
* resolution via `provider`, returning a JPEG crop + its native dimensions.
|
|
2967
|
-
* Returns `null` on a degenerate ROI or any provider miss (so the caller uses
|
|
2968
|
-
* the downscaled tile crop instead). Pure w.r.t. its inputs; the only effect is
|
|
2969
|
-
* the sharp encode of the returned pixels.
|
|
2970
|
-
*/
|
|
2971
|
-
async function nativeChildCrop(provider, bbox, imageWidth, imageHeight, maxWidth) {
|
|
2972
|
-
if (!(imageWidth > 0) || !(imageHeight > 0)) return null;
|
|
2973
|
-
const x1 = Math.max(0, bbox[0]);
|
|
2974
|
-
const y1 = Math.max(0, bbox[1]);
|
|
2975
|
-
const x2 = Math.min(imageWidth, bbox[2]);
|
|
2976
|
-
const y2 = Math.min(imageHeight, bbox[3]);
|
|
2977
|
-
const w = x2 - x1;
|
|
2978
|
-
const h = y2 - y1;
|
|
2979
|
-
if (w < 1 || h < 1) return null;
|
|
2980
|
-
const native = await provider({
|
|
2981
|
-
x: x1 / imageWidth,
|
|
2982
|
-
y: y1 / imageHeight,
|
|
2983
|
-
w: w / imageWidth,
|
|
2984
|
-
h: h / imageHeight
|
|
2985
|
-
}, maxWidth);
|
|
2986
|
-
if (!native || native.width < 2 || native.height < 2 || native.bytes.length < native.width * native.height * 3) return null;
|
|
2987
|
-
return {
|
|
2988
|
-
jpeg: await (0, sharp.default)(Buffer.from(native.bytes), { raw: {
|
|
2989
|
-
width: native.width,
|
|
2990
|
-
height: native.height,
|
|
2991
|
-
channels: 3
|
|
2992
|
-
} }).jpeg({ quality: 90 }).toBuffer(),
|
|
2993
|
-
width: native.width,
|
|
2994
|
-
height: native.height
|
|
2995
|
-
};
|
|
2996
|
-
}
|
|
2997
2617
|
/**
|
|
2998
2618
|
* Detection score at/above which a near-full-frame box is trusted as a REAL
|
|
2999
2619
|
* close subject rather than a phantom. Below this bar a full-frame box is
|
|
@@ -3075,6 +2695,63 @@ function isFullFramePhantomDetection(bbox, frameWidth, frameHeight, score, maxCo
|
|
|
3075
2695
|
return false;
|
|
3076
2696
|
}
|
|
3077
2697
|
//#endregion
|
|
2698
|
+
//#region src/detection-pipeline/pipeline/native-child-crop.ts
|
|
2699
|
+
/**
|
|
2700
|
+
* NATIVE-resolution crop of a LEAF crop-child ROI (plate-ocr, leaf classifiers)
|
|
2701
|
+
* — the plate-side mirror of the face path's {@link ./face-align.buildAlignedFaceCrop}.
|
|
2702
|
+
*
|
|
2703
|
+
* On the detail plane the executor runs a child model against a parent crop
|
|
2704
|
+
* (e.g. the native vehicle crop). A leaf child's ROI (`parentDetection.bbox`,
|
|
2705
|
+
* in the parent crop's PIXEL space) is what the child model reads. Cutting it
|
|
2706
|
+
* from the parent tile with {@link ./crop-utils.cropJpeg} bounds the child input
|
|
2707
|
+
* to the tile's resolution — fatal for OCR on a small, distant plate. When a
|
|
2708
|
+
* native-crop provider is bound to the frame, we instead resolve the SAME ROI
|
|
2709
|
+
* straight from the frame's retained NATIVE surface (the provider re-composes
|
|
2710
|
+
* the crop-normalized ROI into frame space — see {@link ./native-crop-compose}),
|
|
2711
|
+
* giving the model native pixels. A miss/degenerate returns `null` so the caller
|
|
2712
|
+
* falls back to the existing tile crop (never an upscale — native or the tile).
|
|
2713
|
+
*/
|
|
2714
|
+
/**
|
|
2715
|
+
* Generous native-width cap for a leaf child crop. A plate ROI is a few hundred
|
|
2716
|
+
* native pixels wide, so this never binds for plates (effectively uncapped —
|
|
2717
|
+
* the quality path the task requires); it only bounds a pathologically large
|
|
2718
|
+
* whole-object classifier ROI so the in-process native fetch/encode stays cheap.
|
|
2719
|
+
*/
|
|
2720
|
+
var NATIVE_CHILD_CROP_MAX_WIDTH = 1920;
|
|
2721
|
+
/**
|
|
2722
|
+
* Resolve `bbox` (a parent-crop PIXEL rectangle `[x1,y1,x2,y2]`) at native
|
|
2723
|
+
* resolution via `provider`, returning a JPEG crop + its native dimensions.
|
|
2724
|
+
* Returns `null` on a degenerate ROI or any provider miss (so the caller uses
|
|
2725
|
+
* the downscaled tile crop instead). Pure w.r.t. its inputs; the only effect is
|
|
2726
|
+
* the sharp encode of the returned pixels.
|
|
2727
|
+
*/
|
|
2728
|
+
async function nativeChildCrop(provider, bbox, imageWidth, imageHeight, maxWidth) {
|
|
2729
|
+
if (!(imageWidth > 0) || !(imageHeight > 0)) return null;
|
|
2730
|
+
const x1 = Math.max(0, bbox[0]);
|
|
2731
|
+
const y1 = Math.max(0, bbox[1]);
|
|
2732
|
+
const x2 = Math.min(imageWidth, bbox[2]);
|
|
2733
|
+
const y2 = Math.min(imageHeight, bbox[3]);
|
|
2734
|
+
const w = x2 - x1;
|
|
2735
|
+
const h = y2 - y1;
|
|
2736
|
+
if (w < 1 || h < 1) return null;
|
|
2737
|
+
const native = await provider({
|
|
2738
|
+
x: x1 / imageWidth,
|
|
2739
|
+
y: y1 / imageHeight,
|
|
2740
|
+
w: w / imageWidth,
|
|
2741
|
+
h: h / imageHeight
|
|
2742
|
+
}, maxWidth);
|
|
2743
|
+
if (!native || native.width < 2 || native.height < 2 || native.bytes.length < native.width * native.height * 3) return null;
|
|
2744
|
+
return {
|
|
2745
|
+
jpeg: await (0, sharp.default)(Buffer.from(native.bytes), { raw: {
|
|
2746
|
+
width: native.width,
|
|
2747
|
+
height: native.height,
|
|
2748
|
+
channels: 3
|
|
2749
|
+
} }).jpeg({ quality: 90 }).toBuffer(),
|
|
2750
|
+
width: native.width,
|
|
2751
|
+
height: native.height
|
|
2752
|
+
};
|
|
2753
|
+
}
|
|
2754
|
+
//#endregion
|
|
3078
2755
|
//#region src/detection-pipeline/pipeline/plate-deskew.ts
|
|
3079
2756
|
/**
|
|
3080
2757
|
* Plate-crop DESKEW — rotation rectification for oblique licence-plate crops.
|
|
@@ -3563,171 +3240,74 @@ function buildFrameResult(input) {
|
|
|
3563
3240
|
if (Object.keys(cleanDebug).length > 0) return {
|
|
3564
3241
|
...base,
|
|
3565
3242
|
debug: cleanDebug
|
|
3566
|
-
};
|
|
3567
|
-
}
|
|
3568
|
-
return base;
|
|
3569
|
-
};
|
|
3570
|
-
const detections = [];
|
|
3571
|
-
for (const d of input.firstLevel) detections.push(toImmutableObject(d));
|
|
3572
|
-
for (const d of input.details) detections.push(toImmutableObject(d));
|
|
3573
|
-
const frameDebug = {
|
|
3574
|
-
totalInferenceMs: input.totalMs,
|
|
3575
|
-
stepTimings: input.stepTimings,
|
|
3576
|
-
engine: input.engine,
|
|
3577
|
-
pipelineId: input.pipelineId,
|
|
3578
|
-
...input.poolTimings ? {
|
|
3579
|
-
preprocessMs: input.poolTimings.preprocessMs,
|
|
3580
|
-
predictMs: input.poolTimings.predictMs,
|
|
3581
|
-
batchSize: input.poolTimings.batchSize
|
|
3582
|
-
} : {}
|
|
3583
|
-
};
|
|
3584
|
-
return {
|
|
3585
|
-
kind: "frame",
|
|
3586
|
-
frameId: input.frameId ?? generateFrameId(),
|
|
3587
|
-
deviceId: input.deviceId,
|
|
3588
|
-
timestamp: input.timestamp,
|
|
3589
|
-
width: input.width,
|
|
3590
|
-
height: input.height,
|
|
3591
|
-
detections,
|
|
3592
|
-
debug: frameDebug
|
|
3593
|
-
};
|
|
3594
|
-
}
|
|
3595
|
-
function bboxTupleToRect(bbox) {
|
|
3596
|
-
const [x1, y1, x2, y2] = bbox;
|
|
3597
|
-
return {
|
|
3598
|
-
x: x1,
|
|
3599
|
-
y: y1,
|
|
3600
|
-
width: x2 - x1,
|
|
3601
|
-
height: y2 - y1
|
|
3602
|
-
};
|
|
3603
|
-
}
|
|
3604
|
-
function pruneUndefined(obj) {
|
|
3605
|
-
const out = {};
|
|
3606
|
-
for (const [k, v] of Object.entries(obj)) if (v !== void 0) out[k] = v;
|
|
3607
|
-
return out;
|
|
3608
|
-
}
|
|
3609
|
-
function generateFrameId() {
|
|
3610
|
-
return `frame-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
3611
|
-
}
|
|
3612
|
-
/** Seed a MutableObjectDetection from a root-level detector output. */
|
|
3613
|
-
function toMutableRootDetection(det, rootStep, idGen, rootStepLatencyMs) {
|
|
3614
|
-
return {
|
|
3615
|
-
id: idGen.next(),
|
|
3616
|
-
kind: "first-level",
|
|
3617
|
-
macroClass: det.class,
|
|
3618
|
-
originalClass: det.class,
|
|
3619
|
-
score: det.score,
|
|
3620
|
-
bbox: [...det.bbox],
|
|
3621
|
-
ownLabels: [],
|
|
3622
|
-
alternateLabels: {},
|
|
3623
|
-
stepLatencyMs: { [rootStep.stepId]: rootStepLatencyMs },
|
|
3624
|
-
modelIds: { [rootStep.stepId]: rootStep.modelId },
|
|
3625
|
-
extractMode: "full-frame",
|
|
3626
|
-
...det.mask !== void 0 ? {
|
|
3627
|
-
mask: det.mask,
|
|
3628
|
-
maskWidth: det.maskWidth,
|
|
3629
|
-
maskHeight: det.maskHeight
|
|
3630
|
-
} : {},
|
|
3631
|
-
...det.landmarks !== void 0 ? { landmarks: det.landmarks } : {}
|
|
3632
|
-
};
|
|
3633
|
-
}
|
|
3634
|
-
//#endregion
|
|
3635
|
-
//#region src/detection-pipeline/pipeline/execution-trace.ts
|
|
3636
|
-
var traceCounter = 0;
|
|
3637
|
-
var ExecutionTraceBuilder = class {
|
|
3638
|
-
verbosity;
|
|
3639
|
-
deviceId;
|
|
3640
|
-
frameWidth;
|
|
3641
|
-
frameHeight;
|
|
3642
|
-
engineRuntime;
|
|
3643
|
-
steps = [];
|
|
3644
|
-
startTime;
|
|
3645
|
-
constructor(verbosity, deviceId, frameWidth, frameHeight, engineRuntime) {
|
|
3646
|
-
this.verbosity = verbosity;
|
|
3647
|
-
this.deviceId = deviceId;
|
|
3648
|
-
this.frameWidth = frameWidth;
|
|
3649
|
-
this.frameHeight = frameHeight;
|
|
3650
|
-
this.engineRuntime = engineRuntime;
|
|
3651
|
-
this.startTime = Date.now();
|
|
3652
|
-
}
|
|
3653
|
-
/** Whether trace collection is active. */
|
|
3654
|
-
get isActive() {
|
|
3655
|
-
return this.verbosity !== "off";
|
|
3656
|
-
}
|
|
3657
|
-
/**
|
|
3658
|
-
* Record a completed step execution.
|
|
3659
|
-
* No-op if verbosity is 'off'.
|
|
3660
|
-
*/
|
|
3661
|
-
addStep(params) {
|
|
3662
|
-
if (this.verbosity === "off") return;
|
|
3663
|
-
const totalMs = params.preprocessMs + params.inferenceMs + params.postprocessMs;
|
|
3664
|
-
const trace = {
|
|
3665
|
-
stepId: params.stepId,
|
|
3666
|
-
modelId: params.modelId,
|
|
3667
|
-
slot: params.slot,
|
|
3668
|
-
postprocessor: params.postprocessor,
|
|
3669
|
-
preprocessMs: Math.round(params.preprocessMs * 100) / 100,
|
|
3670
|
-
inferenceMs: Math.round(params.inferenceMs * 100) / 100,
|
|
3671
|
-
postprocessMs: Math.round(params.postprocessMs * 100) / 100,
|
|
3672
|
-
totalMs: Math.round(totalMs * 100) / 100,
|
|
3673
|
-
inputType: params.inputType,
|
|
3674
|
-
inputSize: {
|
|
3675
|
-
width: params.inputWidth,
|
|
3676
|
-
height: params.inputHeight
|
|
3677
|
-
},
|
|
3678
|
-
parentDetection: this.verbosity === "full" ? params.parentDetection : void 0,
|
|
3679
|
-
outputKind: params.output.kind,
|
|
3680
|
-
outputCount: countOutput(params.output),
|
|
3681
|
-
topResult: this.verbosity === "full" ? formatTopResult(params.output) : void 0,
|
|
3682
|
-
error: params.error
|
|
3683
|
-
};
|
|
3684
|
-
this.steps.push(trace);
|
|
3685
|
-
}
|
|
3686
|
-
/**
|
|
3687
|
-
* Finalize and return the complete execution trace.
|
|
3688
|
-
* Returns null if verbosity is 'off'.
|
|
3689
|
-
*/
|
|
3690
|
-
build(detectionCount) {
|
|
3691
|
-
if (this.verbosity === "off") return null;
|
|
3692
|
-
const totalMs = Date.now() - this.startTime;
|
|
3693
|
-
return {
|
|
3694
|
-
traceId: `trace-${Date.now()}-${++traceCounter}`,
|
|
3695
|
-
deviceId: this.deviceId,
|
|
3696
|
-
timestamp: this.startTime,
|
|
3697
|
-
frameSize: {
|
|
3698
|
-
width: this.frameWidth,
|
|
3699
|
-
height: this.frameHeight
|
|
3700
|
-
},
|
|
3701
|
-
engineRuntime: this.engineRuntime,
|
|
3702
|
-
steps: this.steps,
|
|
3703
|
-
totalMs,
|
|
3704
|
-
detectionCount
|
|
3705
|
-
};
|
|
3706
|
-
}
|
|
3707
|
-
};
|
|
3708
|
-
function countOutput(output) {
|
|
3709
|
-
switch (output.kind) {
|
|
3710
|
-
case "detections": return output.detections.length;
|
|
3711
|
-
case "classifications": return output.classifications.length;
|
|
3712
|
-
case "embedding": return 1;
|
|
3713
|
-
case "text": return output.text.length > 0 ? 1 : 0;
|
|
3714
|
-
case "mask": return 1;
|
|
3715
|
-
}
|
|
3716
|
-
}
|
|
3717
|
-
function formatTopResult(output) {
|
|
3718
|
-
switch (output.kind) {
|
|
3719
|
-
case "detections": {
|
|
3720
|
-
const top = output.detections[0];
|
|
3721
|
-
return top ? `${top.class} ${top.score.toFixed(2)}` : void 0;
|
|
3722
|
-
}
|
|
3723
|
-
case "classifications": {
|
|
3724
|
-
const top = output.classifications[0];
|
|
3725
|
-
return top ? `${top.class} ${top.score.toFixed(2)}` : void 0;
|
|
3243
|
+
};
|
|
3726
3244
|
}
|
|
3727
|
-
|
|
3728
|
-
|
|
3729
|
-
|
|
3730
|
-
|
|
3245
|
+
return base;
|
|
3246
|
+
};
|
|
3247
|
+
const detections = [];
|
|
3248
|
+
for (const d of input.firstLevel) detections.push(toImmutableObject(d));
|
|
3249
|
+
for (const d of input.details) detections.push(toImmutableObject(d));
|
|
3250
|
+
const frameDebug = {
|
|
3251
|
+
totalInferenceMs: input.totalMs,
|
|
3252
|
+
stepTimings: input.stepTimings,
|
|
3253
|
+
engine: input.engine,
|
|
3254
|
+
pipelineId: input.pipelineId,
|
|
3255
|
+
...input.poolTimings ? {
|
|
3256
|
+
preprocessMs: input.poolTimings.preprocessMs,
|
|
3257
|
+
predictMs: input.poolTimings.predictMs,
|
|
3258
|
+
batchSize: input.poolTimings.batchSize
|
|
3259
|
+
} : {}
|
|
3260
|
+
};
|
|
3261
|
+
return {
|
|
3262
|
+
kind: "frame",
|
|
3263
|
+
frameId: input.frameId ?? generateFrameId(),
|
|
3264
|
+
deviceId: input.deviceId,
|
|
3265
|
+
timestamp: input.timestamp,
|
|
3266
|
+
width: input.width,
|
|
3267
|
+
height: input.height,
|
|
3268
|
+
detections,
|
|
3269
|
+
...input.discarded !== void 0 && input.discarded.length > 0 ? { discarded: input.discarded } : {},
|
|
3270
|
+
debug: frameDebug
|
|
3271
|
+
};
|
|
3272
|
+
}
|
|
3273
|
+
function bboxTupleToRect(bbox) {
|
|
3274
|
+
const [x1, y1, x2, y2] = bbox;
|
|
3275
|
+
return {
|
|
3276
|
+
x: x1,
|
|
3277
|
+
y: y1,
|
|
3278
|
+
width: x2 - x1,
|
|
3279
|
+
height: y2 - y1
|
|
3280
|
+
};
|
|
3281
|
+
}
|
|
3282
|
+
function pruneUndefined(obj) {
|
|
3283
|
+
const out = {};
|
|
3284
|
+
for (const [k, v] of Object.entries(obj)) if (v !== void 0) out[k] = v;
|
|
3285
|
+
return out;
|
|
3286
|
+
}
|
|
3287
|
+
function generateFrameId() {
|
|
3288
|
+
return `frame-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
|
3289
|
+
}
|
|
3290
|
+
/** Seed a MutableObjectDetection from a root-level detector output. */
|
|
3291
|
+
function toMutableRootDetection(det, rootStep, idGen, rootStepLatencyMs) {
|
|
3292
|
+
return {
|
|
3293
|
+
id: idGen.next(),
|
|
3294
|
+
kind: "first-level",
|
|
3295
|
+
macroClass: det.class,
|
|
3296
|
+
originalClass: det.class,
|
|
3297
|
+
score: det.score,
|
|
3298
|
+
bbox: [...det.bbox],
|
|
3299
|
+
ownLabels: [],
|
|
3300
|
+
alternateLabels: {},
|
|
3301
|
+
stepLatencyMs: { [rootStep.stepId]: rootStepLatencyMs },
|
|
3302
|
+
modelIds: { [rootStep.stepId]: rootStep.modelId },
|
|
3303
|
+
extractMode: "full-frame",
|
|
3304
|
+
...det.mask !== void 0 ? {
|
|
3305
|
+
mask: det.mask,
|
|
3306
|
+
maskWidth: det.maskWidth,
|
|
3307
|
+
maskHeight: det.maskHeight
|
|
3308
|
+
} : {},
|
|
3309
|
+
...det.landmarks !== void 0 ? { landmarks: det.landmarks } : {}
|
|
3310
|
+
};
|
|
3731
3311
|
}
|
|
3732
3312
|
//#endregion
|
|
3733
3313
|
//#region src/detection-pipeline/pipeline/executor.ts
|
|
@@ -3879,12 +3459,14 @@ var PipelineExecutor = class {
|
|
|
3879
3459
|
idGen,
|
|
3880
3460
|
details
|
|
3881
3461
|
};
|
|
3462
|
+
let discarded;
|
|
3882
3463
|
for (const rootStep of tree.roots) {
|
|
3883
3464
|
if (debug) console.log(`[executor] rootStep=${rootStep.stepId} settings=${JSON.stringify(rootStep.settings ?? {})}`);
|
|
3884
3465
|
const cropPrep = rootStep.definition.extractMode === "crop-zone" && cropZoneBbox !== void 0 ? await this.prepareCropZoneInput(cropZoneBbox, fullFrameJpegProvider, imageWidth, imageHeight, deviceId) : null;
|
|
3885
3466
|
const rootStart = Date.now();
|
|
3886
3467
|
const rawRootOutput = await this.executeStep(rootStep, cropPrep?.input ?? rootInput, cropPrep?.width ?? imageWidth, cropPrep?.height ?? imageHeight, "full-frame", void 0, void 0, traceBuilder, stepTimings, poolAgg);
|
|
3887
3468
|
const rootMs = Date.now() - rootStart;
|
|
3469
|
+
if (rawRootOutput === null) continue;
|
|
3888
3470
|
const rootOutput = cropPrep && rawRootOutput.kind === "detections" ? reprojectCropZoneDetections(rawRootOutput, cropPrep.origin) : rawRootOutput;
|
|
3889
3471
|
if (rootOutput.kind !== "detections") {
|
|
3890
3472
|
if (isEnrichmentOutput(rootOutput)) {
|
|
@@ -3914,10 +3496,35 @@ var PipelineExecutor = class {
|
|
|
3914
3496
|
if (mapped) {
|
|
3915
3497
|
mutable.originalClass = det.class;
|
|
3916
3498
|
mutable.macroClass = mapped;
|
|
3917
|
-
} else if (!rootStep.definition.classMap.preserveOriginal)
|
|
3499
|
+
} else if (!rootStep.definition.classMap.preserveOriginal) {
|
|
3500
|
+
(discarded ??= []).push({
|
|
3501
|
+
bbox: [
|
|
3502
|
+
mutable.bbox[0],
|
|
3503
|
+
mutable.bbox[1],
|
|
3504
|
+
mutable.bbox[2],
|
|
3505
|
+
mutable.bbox[3]
|
|
3506
|
+
],
|
|
3507
|
+
macroClass: mutable.macroClass,
|
|
3508
|
+
score: mutable.score,
|
|
3509
|
+
reason: "class-filter"
|
|
3510
|
+
});
|
|
3511
|
+
continue;
|
|
3512
|
+
}
|
|
3918
3513
|
}
|
|
3919
|
-
|
|
3920
|
-
|
|
3514
|
+
const filterVerdict = this.macroFilterVerdict(mutable.macroClass, mutable.score, rootStep.settings);
|
|
3515
|
+
if (filterVerdict !== "pass") {
|
|
3516
|
+
(discarded ??= []).push({
|
|
3517
|
+
bbox: [
|
|
3518
|
+
mutable.bbox[0],
|
|
3519
|
+
mutable.bbox[1],
|
|
3520
|
+
mutable.bbox[2],
|
|
3521
|
+
mutable.bbox[3]
|
|
3522
|
+
],
|
|
3523
|
+
macroClass: mutable.macroClass,
|
|
3524
|
+
score: mutable.score,
|
|
3525
|
+
reason: filterVerdict
|
|
3526
|
+
});
|
|
3527
|
+
if (debug) console.log(`[executor] drop det macro=${mutable.macroClass} score=${mutable.score} (${filterVerdict})`);
|
|
3921
3528
|
continue;
|
|
3922
3529
|
}
|
|
3923
3530
|
const fullFrameBar = rootStep.settings?.["fullFrameGuardMaxConfidence"];
|
|
@@ -3936,9 +3543,20 @@ var PipelineExecutor = class {
|
|
|
3936
3543
|
hardAreaRatio: typeof fullFrameHardArea === "number" ? fullFrameHardArea : void 0
|
|
3937
3544
|
}
|
|
3938
3545
|
});
|
|
3546
|
+
(discarded ??= []).push({
|
|
3547
|
+
bbox: [
|
|
3548
|
+
mutable.bbox[0],
|
|
3549
|
+
mutable.bbox[1],
|
|
3550
|
+
mutable.bbox[2],
|
|
3551
|
+
mutable.bbox[3]
|
|
3552
|
+
],
|
|
3553
|
+
macroClass: mutable.macroClass,
|
|
3554
|
+
score: mutable.score,
|
|
3555
|
+
reason: "full-frame-guard"
|
|
3556
|
+
});
|
|
3939
3557
|
continue;
|
|
3940
3558
|
}
|
|
3941
|
-
if (isFullFrameSurvivor(mutable.bbox, imageWidth, imageHeight, mutable.score, typeof fullFrameBar === "number" ? fullFrameBar : void 0)) this.opts.logger?.
|
|
3559
|
+
if (isFullFrameSurvivor(mutable.bbox, imageWidth, imageHeight, mutable.score, typeof fullFrameBar === "number" ? fullFrameBar : void 0)) this.opts.logger?.info("full-frame box SURVIVED the guard on score", {
|
|
3942
3560
|
tags: { deviceId },
|
|
3943
3561
|
meta: {
|
|
3944
3562
|
macroClass: mutable.macroClass,
|
|
@@ -3965,6 +3583,7 @@ var PipelineExecutor = class {
|
|
|
3965
3583
|
firstLevel.push(mutable);
|
|
3966
3584
|
}
|
|
3967
3585
|
}
|
|
3586
|
+
const totalMs = Date.now() - startMs;
|
|
3968
3587
|
return {
|
|
3969
3588
|
result: buildFrameResult({
|
|
3970
3589
|
deviceId,
|
|
@@ -3972,8 +3591,9 @@ var PipelineExecutor = class {
|
|
|
3972
3591
|
height: imageHeight,
|
|
3973
3592
|
firstLevel,
|
|
3974
3593
|
details,
|
|
3594
|
+
discarded,
|
|
3975
3595
|
stepTimings,
|
|
3976
|
-
totalMs
|
|
3596
|
+
totalMs,
|
|
3977
3597
|
engine: this.opts.engineRuntime,
|
|
3978
3598
|
debug,
|
|
3979
3599
|
timestamp: Date.now(),
|
|
@@ -4078,13 +3698,40 @@ var PipelineExecutor = class {
|
|
|
4078
3698
|
});
|
|
4079
3699
|
throw new Error(`Inference failed for step "${step.stepId}": ${errorMsg}`, { cause: err });
|
|
4080
3700
|
}
|
|
3701
|
+
if (engineOutput.dropped === true) {
|
|
3702
|
+
stepTimings.push({
|
|
3703
|
+
source: step.stepId,
|
|
3704
|
+
modelId: step.modelId,
|
|
3705
|
+
ms: Date.now() - preprocessStart,
|
|
3706
|
+
detectionCount: 0
|
|
3707
|
+
});
|
|
3708
|
+
if (traceBuilder.isActive) traceBuilder.addStep({
|
|
3709
|
+
stepId: step.stepId,
|
|
3710
|
+
modelId: step.modelId,
|
|
3711
|
+
slot: step.definition.slot,
|
|
3712
|
+
postprocessor: step.definition.postprocessor,
|
|
3713
|
+
preprocessMs,
|
|
3714
|
+
inferenceMs: Date.now() - inferenceStart,
|
|
3715
|
+
postprocessMs: 0,
|
|
3716
|
+
inputType,
|
|
3717
|
+
inputWidth,
|
|
3718
|
+
inputHeight,
|
|
3719
|
+
parentDetection: parentClass,
|
|
3720
|
+
output: {
|
|
3721
|
+
kind: "detections",
|
|
3722
|
+
detections: []
|
|
3723
|
+
},
|
|
3724
|
+
error: `shed:${engineOutput.shedReason ?? "pool-overload"}`
|
|
3725
|
+
});
|
|
3726
|
+
return null;
|
|
3727
|
+
}
|
|
4081
3728
|
const structured = engineOutput.structured ?? {};
|
|
4082
3729
|
const inferenceMs = typeof structured.inferenceMs === "number" ? structured.inferenceMs : Date.now() - inferenceStart;
|
|
4083
3730
|
if (typeof structured.preprocessMs === "number") poolAgg.preprocessMs += structured.preprocessMs;
|
|
4084
3731
|
if (typeof structured.predictMs === "number") poolAgg.predictMs += structured.predictMs;
|
|
4085
3732
|
if (typeof structured.batchSize === "number" && structured.batchSize > poolAgg.batchSize) poolAgg.batchSize = structured.batchSize;
|
|
4086
3733
|
const postprocessStart = Date.now();
|
|
4087
|
-
const output = dispatchPostprocess(engineOutput, step.definition
|
|
3734
|
+
const output = dispatchPostprocess(engineOutput, step.definition);
|
|
4088
3735
|
const postprocessMs = Date.now() - postprocessStart;
|
|
4089
3736
|
stepTimings.push({
|
|
4090
3737
|
source: step.stepId,
|
|
@@ -4227,6 +3874,7 @@ var PipelineExecutor = class {
|
|
|
4227
3874
|
data: cropJpegBuf
|
|
4228
3875
|
}, cropW, cropH, "crop-roi", parentDetection.bbox, parentDetection.macroClass, traceBuilder, stepTimings, poolAgg);
|
|
4229
3876
|
const childMs = Date.now() - childStart;
|
|
3877
|
+
if (childOutput === null) continue;
|
|
4230
3878
|
const detailsBefore = ctx.details.length;
|
|
4231
3879
|
applyChildOutput(parentDetection, child, childOutput, childMs, ctx);
|
|
4232
3880
|
if (childOutput.kind === "detections" && child.children.length > 0) {
|
|
@@ -4260,20 +3908,25 @@ var PipelineExecutor = class {
|
|
|
4260
3908
|
* Apply the object-detection step's macro filter + per-macro
|
|
4261
3909
|
* minConfidence sliders introduced in the Phase 6 step rework.
|
|
4262
3910
|
*
|
|
3911
|
+
* Returns WHICH gate failed rather than a bare boolean so the
|
|
3912
|
+
* discard trail can label the dropped box with the honest reason
|
|
3913
|
+
* (`class-filter` vs `below-threshold`) — the two are remediated
|
|
3914
|
+
* differently (enable the class vs lower a slider).
|
|
3915
|
+
*
|
|
4263
3916
|
* Expected `settings` shape:
|
|
4264
3917
|
* - `enabledMacroClasses`: readonly string[] (e.g. ['person','vehicle','animal']).
|
|
4265
3918
|
* Empty array = all allowed (legacy behaviour).
|
|
4266
3919
|
* - `minConfidence<Macro>`: number (e.g. `minConfidencePerson: 0.5`)
|
|
4267
3920
|
*/
|
|
4268
|
-
|
|
4269
|
-
if (!settings) return
|
|
3921
|
+
macroFilterVerdict(macroClass, score, settings) {
|
|
3922
|
+
if (!settings) return "pass";
|
|
4270
3923
|
const enabled = settings["enabledMacroClasses"];
|
|
4271
3924
|
if (Array.isArray(enabled) && enabled.length > 0) {
|
|
4272
|
-
if (!enabled.includes(macroClass)) return
|
|
3925
|
+
if (!enabled.includes(macroClass)) return "class-filter";
|
|
4273
3926
|
}
|
|
4274
3927
|
const perMacroThreshold = settings[`minConfidence${capitalize(macroClass)}`];
|
|
4275
|
-
if (typeof perMacroThreshold === "number" && score < perMacroThreshold) return
|
|
4276
|
-
return
|
|
3928
|
+
if (typeof perMacroThreshold === "number" && score < perMacroThreshold) return "below-threshold";
|
|
3929
|
+
return "pass";
|
|
4277
3930
|
}
|
|
4278
3931
|
};
|
|
4279
3932
|
function capitalize(s) {
|
|
@@ -4281,52 +3934,41 @@ function capitalize(s) {
|
|
|
4281
3934
|
return s.charAt(0).toUpperCase() + s.slice(1);
|
|
4282
3935
|
}
|
|
4283
3936
|
//#endregion
|
|
4284
|
-
//#region src/detection-pipeline/pipeline/crop-
|
|
3937
|
+
//#region src/detection-pipeline/pipeline/native-crop-compose.ts
|
|
3938
|
+
/** Clamp `v` into `[lo, hi]`. */
|
|
3939
|
+
function clamp(v, lo, hi) {
|
|
3940
|
+
if (v < lo) return lo;
|
|
3941
|
+
if (v > hi) return hi;
|
|
3942
|
+
return v;
|
|
3943
|
+
}
|
|
4285
3944
|
/**
|
|
4286
|
-
*
|
|
4287
|
-
*
|
|
4288
|
-
*
|
|
4289
|
-
*
|
|
3945
|
+
* Compose a child `roi` given in the parent CROP's normalized space into the
|
|
3946
|
+
* FRAME's normalized space, given the crop's frame-space pixel rectangle and the
|
|
3947
|
+
* frame dimensions. The result is clamped to the unit square (origin in
|
|
3948
|
+
* `[0,1]`, extent bounded so `x + w ≤ 1` and `y + h ≤ 1`). Returns `null` for
|
|
3949
|
+
* degenerate inputs (non-finite frame dims, empty crop rect, or an ROI that
|
|
3950
|
+
* clamps to zero area) so the caller falls back to the downscaled tile crop.
|
|
4290
3951
|
*
|
|
4291
|
-
*
|
|
4292
|
-
* referenced geometry, or a degenerate result — in which case the caller falls
|
|
4293
|
-
* back to full-frame inference (behaviour identical to before the crop-zone
|
|
4294
|
-
* plumbing).
|
|
3952
|
+
* Pure — never mutates its arguments.
|
|
4295
3953
|
*/
|
|
4296
|
-
function
|
|
4297
|
-
if (frameWidth
|
|
4298
|
-
|
|
4299
|
-
|
|
4300
|
-
const
|
|
4301
|
-
|
|
4302
|
-
|
|
4303
|
-
const
|
|
4304
|
-
|
|
4305
|
-
|
|
4306
|
-
|
|
4307
|
-
|
|
4308
|
-
|
|
4309
|
-
|
|
4310
|
-
|
|
4311
|
-
|
|
4312
|
-
|
|
4313
|
-
|
|
4314
|
-
if (point.x < minX) minX = point.x;
|
|
4315
|
-
if (point.y < minY) minY = point.y;
|
|
4316
|
-
if (point.x > maxX) maxX = point.x;
|
|
4317
|
-
if (point.y > maxY) maxY = point.y;
|
|
4318
|
-
}
|
|
4319
|
-
}
|
|
4320
|
-
if (!sawPoint) return null;
|
|
4321
|
-
const clamp01 = (v) => Math.max(0, Math.min(1, v));
|
|
4322
|
-
const bbox = [
|
|
4323
|
-
clamp01(minX) * frameWidth,
|
|
4324
|
-
clamp01(minY) * frameHeight,
|
|
4325
|
-
clamp01(maxX) * frameWidth,
|
|
4326
|
-
clamp01(maxY) * frameHeight
|
|
4327
|
-
];
|
|
4328
|
-
if (isBboxDegenerate(bbox)) return null;
|
|
4329
|
-
return bbox;
|
|
3954
|
+
function composeCropRoiToFrameNorm(roi, cropFrameSpace, frameWidth, frameHeight) {
|
|
3955
|
+
if (!(frameWidth > 0) || !(frameHeight > 0)) return null;
|
|
3956
|
+
if (!(cropFrameSpace.w > 0) || !(cropFrameSpace.h > 0)) return null;
|
|
3957
|
+
const fx = (cropFrameSpace.x + roi.x * cropFrameSpace.w) / frameWidth;
|
|
3958
|
+
const fy = (cropFrameSpace.y + roi.y * cropFrameSpace.h) / frameHeight;
|
|
3959
|
+
const fw = roi.w * cropFrameSpace.w / frameWidth;
|
|
3960
|
+
const fh = roi.h * cropFrameSpace.h / frameHeight;
|
|
3961
|
+
const x = clamp(fx, 0, 1);
|
|
3962
|
+
const y = clamp(fy, 0, 1);
|
|
3963
|
+
const w = clamp(fw, 0, 1 - x);
|
|
3964
|
+
const h = clamp(fh, 0, 1 - y);
|
|
3965
|
+
if (!(w > 0) || !(h > 0)) return null;
|
|
3966
|
+
return {
|
|
3967
|
+
x,
|
|
3968
|
+
y,
|
|
3969
|
+
w,
|
|
3970
|
+
h
|
|
3971
|
+
};
|
|
4330
3972
|
}
|
|
4331
3973
|
//#endregion
|
|
4332
3974
|
//#region src/detection-pipeline/pipeline/tree-builder.ts
|
|
@@ -4562,6 +4204,44 @@ function resolveInputSteps(steps, format, engine) {
|
|
|
4562
4204
|
};
|
|
4563
4205
|
}
|
|
4564
4206
|
//#endregion
|
|
4207
|
+
//#region src/detection-pipeline/zone-gate.ts
|
|
4208
|
+
function applyZoneRuleGate(result, zones, rules) {
|
|
4209
|
+
if (result.detections.length === 0) return result;
|
|
4210
|
+
if (zones.length === 0 || rules.length === 0) return result;
|
|
4211
|
+
const frameW = result.width;
|
|
4212
|
+
const frameH = result.height;
|
|
4213
|
+
if (frameW === 0 || frameH === 0) return result;
|
|
4214
|
+
const firstLevel = result.detections.filter((d) => d.kind === "first-level");
|
|
4215
|
+
const details = result.detections.filter((d) => d.kind === "detail");
|
|
4216
|
+
const { passed, excluded } = require_dist.evaluateZoneRules(firstLevel, zones, rules, (det) => ({
|
|
4217
|
+
x: (det.bbox.x + det.bbox.width / 2) / frameW,
|
|
4218
|
+
y: (det.bbox.y + det.bbox.height / 2) / frameH
|
|
4219
|
+
}), (det) => det.macroClass);
|
|
4220
|
+
if (passed.length === firstLevel.length) return result;
|
|
4221
|
+
const passedIds = new Set(passed.map((d) => d.id));
|
|
4222
|
+
const filteredDetails = details.filter((d) => {
|
|
4223
|
+
const parentId = d.parentId;
|
|
4224
|
+
return parentId === void 0 || passedIds.has(parentId);
|
|
4225
|
+
});
|
|
4226
|
+
const zoneDiscards = excluded.map((d) => ({
|
|
4227
|
+
bbox: [
|
|
4228
|
+
d.bbox.x,
|
|
4229
|
+
d.bbox.y,
|
|
4230
|
+
d.bbox.x + d.bbox.width,
|
|
4231
|
+
d.bbox.y + d.bbox.height
|
|
4232
|
+
],
|
|
4233
|
+
macroClass: d.macroClass,
|
|
4234
|
+
score: d.score,
|
|
4235
|
+
reason: "zone-gate"
|
|
4236
|
+
}));
|
|
4237
|
+
const mergedDiscarded = [...result.discarded ?? [], ...zoneDiscards];
|
|
4238
|
+
return {
|
|
4239
|
+
...result,
|
|
4240
|
+
detections: [...passed, ...filteredDetails],
|
|
4241
|
+
...mergedDiscarded.length > 0 ? { discarded: mergedDiscarded } : {}
|
|
4242
|
+
};
|
|
4243
|
+
}
|
|
4244
|
+
//#endregion
|
|
4565
4245
|
//#region src/detection-pipeline/provider.ts
|
|
4566
4246
|
/**
|
|
4567
4247
|
* DetectionPipelineProvider — implements IPipelineExecutorProvider.
|
|
@@ -5960,19 +5640,15 @@ var DetectionPipelineProvider = class DetectionPipelineProvider {
|
|
|
5960
5640
|
emit(`Image: ${imageWidth}×${imageHeight}`);
|
|
5961
5641
|
}
|
|
5962
5642
|
decodeMs = performance.now() - decodeT0;
|
|
5963
|
-
const
|
|
5964
|
-
|
|
5965
|
-
|
|
5966
|
-
|
|
5967
|
-
|
|
5968
|
-
|
|
5969
|
-
|
|
5970
|
-
|
|
5971
|
-
|
|
5972
|
-
backend: this.currentEngine.backend,
|
|
5973
|
-
device: this.currentEngine.device ?? null
|
|
5974
|
-
};
|
|
5975
|
-
const benchmarkSteps = this.inputStepsToPipelineSteps(input.steps, resolveFormat, resolveEngine);
|
|
5643
|
+
const dispatchResolution = this.resolveStepsForDispatch({
|
|
5644
|
+
steps: input.steps,
|
|
5645
|
+
deviceKey: input.deviceKey,
|
|
5646
|
+
engineOverride: input.engine,
|
|
5647
|
+
deviceId: input.deviceId,
|
|
5648
|
+
plane: input.plane
|
|
5649
|
+
});
|
|
5650
|
+
const dispatchDeviceKey = dispatchResolution.deviceKey;
|
|
5651
|
+
const benchmarkSteps = dispatchResolution.steps;
|
|
5976
5652
|
const stepsSignature = JSON.stringify(benchmarkSteps.map((s) => ({
|
|
5977
5653
|
id: s.addonId,
|
|
5978
5654
|
settings: s.settings ?? {}
|
|
@@ -6064,8 +5740,8 @@ var DetectionPipelineProvider = class DetectionPipelineProvider {
|
|
|
6064
5740
|
logger: this.log
|
|
6065
5741
|
});
|
|
6066
5742
|
this.executor = executor;
|
|
6067
|
-
const dispatchEngine =
|
|
6068
|
-
const dispatchFactory =
|
|
5743
|
+
const dispatchEngine = dispatchDeviceKey ? resolveDeviceEngine(dispatchDeviceKey) : runEngine;
|
|
5744
|
+
const dispatchFactory = dispatchDeviceKey ? await this.resolveDeviceFactory(dispatchDeviceKey) : this.engineFactory;
|
|
6069
5745
|
const needed = enabledSteps.filter((s) => !dispatchFactory.isLoadedWithModel(s.addonId, s.modelId));
|
|
6070
5746
|
if (needed.length > 0) {
|
|
6071
5747
|
this.log.info("Benchmark: models to load", { meta: {
|
|
@@ -6314,6 +5990,142 @@ var DetectionPipelineProvider = class DetectionPipelineProvider {
|
|
|
6314
5990
|
fn();
|
|
6315
5991
|
}
|
|
6316
5992
|
/**
|
|
5993
|
+
* Resolve a dispatch's step tree against its target engine, with the
|
|
5994
|
+
* CAPABILITY GATE + node-local engine fallback (cam-615, 2026-08-01;
|
|
5995
|
+
* per-step split 2026-08-01 evening).
|
|
5996
|
+
*
|
|
5997
|
+
* A per-call `deviceKey` (orchestrator device routing / detail-plane step
|
|
5998
|
+
* jump) selects an engine whose format every step EXECUTING IN THIS CALL
|
|
5999
|
+
* must actually ship a model build for. When such a step's catalog has
|
|
6000
|
+
* ZERO builds for that format (so not even `resolveModelForFormat`'s
|
|
6001
|
+
* substitution can rescue it), dispatching anyway means every frame
|
|
6002
|
+
* fails — before this gate it failed as a doomed 3-retry model download,
|
|
6003
|
+
* ~5.5s per frame, forever.
|
|
6004
|
+
*
|
|
6005
|
+
* The gated set is per-plane — the ROOT decides the dispatch device, a
|
|
6006
|
+
* child never bounces it (operator requirement: devices compensate for
|
|
6007
|
+
* each other's missing steps; the original whole-tree gate let ONE
|
|
6008
|
+
* tflite-less child knock the root off an otherwise-capable Coral):
|
|
6009
|
+
*
|
|
6010
|
+
* - `'frame'` (the live per-frame path) executes only root-plane steps,
|
|
6011
|
+
* so only those gate the device. Detail children that can NEVER run on
|
|
6012
|
+
* this device are pruned from THIS dispatch (so `ensureModelsForSteps`
|
|
6013
|
+
* doesn't fail the call on a format build that does not exist) and
|
|
6014
|
+
* logged once — NOT dropped work: each runs later as its own per-track
|
|
6015
|
+
* detail dispatch, where the runner's device-jump resolver
|
|
6016
|
+
* (`resolveStepDevice`) places it on a same-node device that can run
|
|
6017
|
+
* it, or warns no-candidate loudly.
|
|
6018
|
+
* - any other plane (detail subtrees, benchmark, batch) executes the
|
|
6019
|
+
* whole passed tree inline on ONE pool — a single call cannot split
|
|
6020
|
+
* devices — so the whole-tree gate stays.
|
|
6021
|
+
*
|
|
6022
|
+
* Fallback is strictly NODE-LOCAL and ordered: the node's own selected
|
|
6023
|
+
* engine (or the benchmark's explicit `engineOverride`) is the one and only
|
|
6024
|
+
* fallback — frames never migrate to another node from here (that is the
|
|
6025
|
+
* orchestrator's tier). The fallback is logged ONCE per distinct
|
|
6026
|
+
* (deviceKey, steps, format) signature, with `tags: { deviceId }` when the
|
|
6027
|
+
* dispatch is camera-scoped.
|
|
6028
|
+
*
|
|
6029
|
+
* When the node's own engine ALSO cannot run a step, this throws — fast,
|
|
6030
|
+
* before any download attempt — and logs the full picture once (model,
|
|
6031
|
+
* its available formats, both engines tried). A genuinely impossible
|
|
6032
|
+
* configuration must stay loud, not vanish into a silent fallback chain.
|
|
6033
|
+
*/
|
|
6034
|
+
resolveStepsForDispatch(args) {
|
|
6035
|
+
const { deviceKey, engineOverride, deviceId } = args;
|
|
6036
|
+
const nodeFormat = engineOverride?.format ?? this.currentEngine.format;
|
|
6037
|
+
const nodeEngine = engineOverride ? {
|
|
6038
|
+
backend: engineOverride.backend,
|
|
6039
|
+
device: engineOverride.device ?? null
|
|
6040
|
+
} : {
|
|
6041
|
+
backend: this.currentEngine.backend,
|
|
6042
|
+
device: this.currentEngine.device ?? null
|
|
6043
|
+
};
|
|
6044
|
+
const nodeEngineLabel = `${nodeEngine.backend}/${nodeEngine.device ?? "default"} (${nodeFormat})`;
|
|
6045
|
+
const deviceEngine = deviceKey ? resolveDeviceEngine(deviceKey) : void 0;
|
|
6046
|
+
if (deviceKey === void 0 || deviceEngine === void 0) {
|
|
6047
|
+
const steps = this.inputStepsToPipelineSteps(args.steps, nodeFormat, nodeEngine);
|
|
6048
|
+
this.assertStepsRunnable(steps, nodeFormat, deviceId, [nodeEngineLabel]);
|
|
6049
|
+
return {
|
|
6050
|
+
deviceKey: void 0,
|
|
6051
|
+
steps
|
|
6052
|
+
};
|
|
6053
|
+
}
|
|
6054
|
+
const deviceFormat = deviceEngine.format;
|
|
6055
|
+
const deviceStepEngine = {
|
|
6056
|
+
backend: deviceEngine.backend,
|
|
6057
|
+
device: deviceEngine.device ?? null
|
|
6058
|
+
};
|
|
6059
|
+
const steps = this.inputStepsToPipelineSteps(args.steps, deviceFormat, deviceStepEngine);
|
|
6060
|
+
const framePlane = args.plane === "frame";
|
|
6061
|
+
const zeroBuild = collectZeroBuildIssues(framePlane ? collectFramePlaneSteps(steps, isDetailPlaneStep) : flattenSteps(steps), deviceFormat);
|
|
6062
|
+
if (zeroBuild.length === 0) {
|
|
6063
|
+
if (!framePlane) return {
|
|
6064
|
+
deviceKey,
|
|
6065
|
+
steps
|
|
6066
|
+
};
|
|
6067
|
+
const pruneResult = pruneUnrunnableDetailSteps(steps, isDetailPlaneStep, (addonId) => stepHasZeroBuildsFor(addonId, deviceFormat));
|
|
6068
|
+
if (pruneResult.prunedAddonIds.length > 0) {
|
|
6069
|
+
const prunedList = pruneResult.prunedAddonIds.join(",");
|
|
6070
|
+
this.logLiveDispatchIssueOnce(`detail-defer:${deviceKey}:${deviceFormat}:${prunedList}`, () => this.log.info("Detail steps have no model build for the dispatch device format — deferred to the detail-plane device jump", {
|
|
6071
|
+
...deviceId !== void 0 ? { tags: { deviceId } } : {},
|
|
6072
|
+
meta: {
|
|
6073
|
+
deviceKey,
|
|
6074
|
+
deviceFormat,
|
|
6075
|
+
steps: [...pruneResult.prunedAddonIds]
|
|
6076
|
+
}
|
|
6077
|
+
}));
|
|
6078
|
+
}
|
|
6079
|
+
return {
|
|
6080
|
+
deviceKey,
|
|
6081
|
+
steps: pruneResult.steps
|
|
6082
|
+
};
|
|
6083
|
+
}
|
|
6084
|
+
const blockedSteps = zeroBuild.map((issue) => issue.addonId);
|
|
6085
|
+
this.logLiveDispatchIssueOnce(`capability-fallback:${deviceKey}:${deviceFormat}:${blockedSteps.join(",")}`, () => this.log.warn("Device pool cannot run step (no model build for its format) — falling back to the node-local default engine", {
|
|
6086
|
+
...deviceId !== void 0 ? { tags: { deviceId } } : {},
|
|
6087
|
+
meta: {
|
|
6088
|
+
deviceKey,
|
|
6089
|
+
deviceFormat,
|
|
6090
|
+
steps: blockedSteps,
|
|
6091
|
+
fallbackEngine: nodeEngineLabel
|
|
6092
|
+
}
|
|
6093
|
+
}));
|
|
6094
|
+
const fallbackSteps = this.inputStepsToPipelineSteps(args.steps, nodeFormat, nodeEngine);
|
|
6095
|
+
this.assertStepsRunnable(fallbackSteps, nodeFormat, deviceId, [`${deviceKey} (${deviceFormat})`, nodeEngineLabel]);
|
|
6096
|
+
return {
|
|
6097
|
+
deviceKey: void 0,
|
|
6098
|
+
steps: fallbackSteps
|
|
6099
|
+
};
|
|
6100
|
+
}
|
|
6101
|
+
/**
|
|
6102
|
+
* The loud, fast half of the capability gate: throw when any ENABLED step
|
|
6103
|
+
* has ZERO model builds for `format` — BEFORE any model download runs. The
|
|
6104
|
+
* error names the step, its chosen model, the formats the catalog actually
|
|
6105
|
+
* ships, and every engine that was tried, and is logged ONCE per distinct
|
|
6106
|
+
* signature (the throw itself still surfaces per dispatch, but costs
|
|
6107
|
+
* microseconds instead of a 3-retry download backoff).
|
|
6108
|
+
*/
|
|
6109
|
+
assertStepsRunnable(steps, format, deviceId, enginesTried) {
|
|
6110
|
+
const zeroBuild = collectZeroBuildIssues(flattenSteps(steps), format);
|
|
6111
|
+
if (zeroBuild.length === 0) return;
|
|
6112
|
+
const detail = zeroBuild.map((issue) => {
|
|
6113
|
+
const step = flattenSteps(steps).find((s) => s.addonId === issue.addonId);
|
|
6114
|
+
const formats = availableFormatsForStep(issue.addonId);
|
|
6115
|
+
return `step "${issue.addonId}" (model "${step?.modelId ?? "unknown"}") has no ${format} build (available: ${formats.join(", ") || "none"})`;
|
|
6116
|
+
}).join("; ");
|
|
6117
|
+
const message = `Pipeline dispatch impossible on this node: ${detail}. Engines tried: ${enginesTried.join(" → ")}.`;
|
|
6118
|
+
this.logLiveDispatchIssueOnce(`unrunnable:${format}:${zeroBuild.map((i) => i.addonId).join(",")}`, () => this.log.error("Pipeline step cannot run on any node-local engine", {
|
|
6119
|
+
...deviceId !== void 0 ? { tags: { deviceId } } : {},
|
|
6120
|
+
meta: {
|
|
6121
|
+
format,
|
|
6122
|
+
enginesTried: [...enginesTried],
|
|
6123
|
+
detail
|
|
6124
|
+
}
|
|
6125
|
+
}));
|
|
6126
|
+
throw new Error(message);
|
|
6127
|
+
}
|
|
6128
|
+
/**
|
|
6317
6129
|
* Single-flight gate around `ensureModelsForSteps`. Concurrent
|
|
6318
6130
|
* callers (every camera that fires motion in the same window calls
|
|
6319
6131
|
* `runPipeline` → `ensureModelsForSteps`) share the same in-flight
|
|
@@ -6340,6 +6152,7 @@ var DetectionPipelineProvider = class DetectionPipelineProvider {
|
|
|
6340
6152
|
for (const step of needed) {
|
|
6341
6153
|
const modelEntry = await this.resolveModelEntry(step.addonId, step.modelId);
|
|
6342
6154
|
if (modelEntry && !require_model_download_service_Cp9f4dk6.isModelDownloaded(this.modelsDir, modelEntry, format)) {
|
|
6155
|
+
if (modelEntry.formats[format] === void 0) throw new Error(`Model "${modelEntry.id}" has no ${format} format build (available: ${Object.keys(modelEntry.formats).join(", ") || "none"}) — not retrying a permanent format mismatch`);
|
|
6343
6156
|
this.log.info("Downloading model for step", { meta: {
|
|
6344
6157
|
modelId: step.modelId,
|
|
6345
6158
|
format,
|
|
@@ -6457,19 +6270,16 @@ var DetectionPipelineProvider = class DetectionPipelineProvider {
|
|
|
6457
6270
|
}
|
|
6458
6271
|
async runPipelineBatchImpl(input) {
|
|
6459
6272
|
if (input.frames.length === 0) return { results: [] };
|
|
6460
|
-
const
|
|
6461
|
-
|
|
6462
|
-
|
|
6463
|
-
|
|
6464
|
-
|
|
6465
|
-
|
|
6466
|
-
|
|
6467
|
-
|
|
6468
|
-
|
|
6469
|
-
|
|
6470
|
-
device: this.currentEngine.device ?? null
|
|
6471
|
-
};
|
|
6472
|
-
const benchmarkSteps = this.inputStepsToPipelineSteps(input.steps, resolveFormat, resolveEngine);
|
|
6273
|
+
const dispatchResolution = this.resolveStepsForDispatch({
|
|
6274
|
+
steps: input.steps,
|
|
6275
|
+
deviceKey: input.deviceKey,
|
|
6276
|
+
engineOverride: input.engine,
|
|
6277
|
+
deviceId: input.deviceId,
|
|
6278
|
+
plane: void 0
|
|
6279
|
+
});
|
|
6280
|
+
const dispatchDeviceKey = dispatchResolution.deviceKey;
|
|
6281
|
+
const resolveFormat = dispatchDeviceKey ? resolveDeviceEngine(dispatchDeviceKey).format : input.engine?.format ?? this.currentEngine.format;
|
|
6282
|
+
const benchmarkSteps = dispatchResolution.steps;
|
|
6473
6283
|
const enabledSteps = flattenEnabledVideoSteps(benchmarkSteps);
|
|
6474
6284
|
if (enabledSteps.length === 0) throw new Error("runPipelineBatch: no enabled steps");
|
|
6475
6285
|
const rootStep = enabledSteps[0];
|
|
@@ -6491,7 +6301,7 @@ var DetectionPipelineProvider = class DetectionPipelineProvider {
|
|
|
6491
6301
|
await this.ensureEngineFactory();
|
|
6492
6302
|
const restoreEngine = await this.applyEngineOverride(input.engine);
|
|
6493
6303
|
try {
|
|
6494
|
-
const factory =
|
|
6304
|
+
const factory = dispatchDeviceKey ? await this.resolveDeviceFactory(dispatchDeviceKey) : this.engineFactory;
|
|
6495
6305
|
if (!factory) throw new Error("runPipelineBatch: factory not initialised");
|
|
6496
6306
|
if (enabledSteps.filter((s) => !factory.isLoadedWithModel(s.addonId, s.modelId)).length > 0) await this.ensureModelsForSteps(benchmarkSteps, factory, resolveFormat);
|
|
6497
6307
|
const canFastPath = singleRoot && allRaw && uniformDims && factory.supportsBatch();
|
|
@@ -6508,7 +6318,7 @@ var DetectionPipelineProvider = class DetectionPipelineProvider {
|
|
|
6508
6318
|
frame,
|
|
6509
6319
|
deviceId: input.deviceId,
|
|
6510
6320
|
sessionId: input.sessionId,
|
|
6511
|
-
deviceKey:
|
|
6321
|
+
deviceKey: dispatchDeviceKey
|
|
6512
6322
|
}))) };
|
|
6513
6323
|
const items = input.frames.map((frame) => ({
|
|
6514
6324
|
raw: Buffer.from(frame.data),
|
|
@@ -6693,31 +6503,10 @@ var DetectionPipelineProvider = class DetectionPipelineProvider {
|
|
|
6693
6503
|
* detections).
|
|
6694
6504
|
*/
|
|
6695
6505
|
gateDetectionsByZoneRules(deviceId, result) {
|
|
6696
|
-
if (deviceId <= 0
|
|
6506
|
+
if (deviceId <= 0) return result;
|
|
6697
6507
|
const proxy = this.deviceProxies.get(deviceId);
|
|
6698
6508
|
if (!proxy) return result;
|
|
6699
|
-
|
|
6700
|
-
const rules = proxy.state.zoneRules.value?.detection ?? [];
|
|
6701
|
-
if (zones.length === 0 || rules.length === 0) return result;
|
|
6702
|
-
const frameW = result.width;
|
|
6703
|
-
const frameH = result.height;
|
|
6704
|
-
if (frameW === 0 || frameH === 0) return result;
|
|
6705
|
-
const firstLevel = result.detections.filter((d) => d.kind === "first-level");
|
|
6706
|
-
const details = result.detections.filter((d) => d.kind === "detail");
|
|
6707
|
-
const { passed } = require_dist.evaluateZoneRules(firstLevel, zones, rules, (det) => ({
|
|
6708
|
-
x: (det.bbox.x + det.bbox.width / 2) / frameW,
|
|
6709
|
-
y: (det.bbox.y + det.bbox.height / 2) / frameH
|
|
6710
|
-
}), (det) => det.macroClass);
|
|
6711
|
-
if (passed.length === firstLevel.length) return result;
|
|
6712
|
-
const passedIds = new Set(passed.map((d) => d.id));
|
|
6713
|
-
const filteredDetails = details.filter((d) => {
|
|
6714
|
-
const parentId = d.parentId;
|
|
6715
|
-
return parentId === void 0 || passedIds.has(parentId);
|
|
6716
|
-
});
|
|
6717
|
-
return {
|
|
6718
|
-
...result,
|
|
6719
|
-
detections: [...passed, ...filteredDetails]
|
|
6720
|
-
};
|
|
6509
|
+
return applyZoneRuleGate(result, proxy.state.zones.value?.zones ?? [], proxy.state.zoneRules.value?.detection ?? []);
|
|
6721
6510
|
}
|
|
6722
6511
|
async cacheFrameInPool(input) {
|
|
6723
6512
|
await this.ensureEngineFactory();
|
|
@@ -7307,12 +7096,49 @@ function stepsToPipelineConfig(steps, engine) {
|
|
|
7307
7096
|
} : {}
|
|
7308
7097
|
};
|
|
7309
7098
|
}
|
|
7310
|
-
/** Flatten a step tree into a flat list (DFS). */
|
|
7311
7099
|
/** Flatten a step tree into a flat list (DFS) — delegates to shared utility. */
|
|
7312
7100
|
function flattenSteps(steps) {
|
|
7313
7101
|
return flattenEnabledVideoSteps(steps);
|
|
7314
7102
|
}
|
|
7315
7103
|
/**
|
|
7104
|
+
* Catalog root-vs-detail plane of a step: a non-null `inputClasses` on the
|
|
7105
|
+
* DEFINITION marks a crop child served per-track on the detail plane —
|
|
7106
|
+
* mirrors the executor's frame-plane skip (`executeChildren`) and the
|
|
7107
|
+
* runner's `deriveDetailSteps`. Unknown addonIds (already dropped from
|
|
7108
|
+
* resolved trees) default to root-plane.
|
|
7109
|
+
*/
|
|
7110
|
+
function isDetailPlaneStep(addonId) {
|
|
7111
|
+
try {
|
|
7112
|
+
return require_step_definitions.getStepDefinition(addonId).inputClasses !== null;
|
|
7113
|
+
} catch {
|
|
7114
|
+
return false;
|
|
7115
|
+
}
|
|
7116
|
+
}
|
|
7117
|
+
/**
|
|
7118
|
+
* True when the step's FULL catalog ships no model with a build for
|
|
7119
|
+
* `format` — the single-step form of `collectZeroBuildIssues`. Unknown/custom
|
|
7120
|
+
* addonIds (no catalog to check) are never zero-build, mirroring the
|
|
7121
|
+
* collector's skip.
|
|
7122
|
+
*/
|
|
7123
|
+
function stepHasZeroBuildsFor(addonId, format) {
|
|
7124
|
+
return collectZeroBuildIssues([{ addonId }], format).length > 0;
|
|
7125
|
+
}
|
|
7126
|
+
/**
|
|
7127
|
+
* The union of model formats a step's catalog ships ANY build for — the
|
|
7128
|
+
* "Available: …" half of the capability-gate error. Unknown/custom addonIds
|
|
7129
|
+
* yield an empty list (no catalog to enumerate), never a throw.
|
|
7130
|
+
*/
|
|
7131
|
+
function availableFormatsForStep(addonId) {
|
|
7132
|
+
try {
|
|
7133
|
+
const def = require_step_definitions.getStepDefinition(addonId);
|
|
7134
|
+
const formats = /* @__PURE__ */ new Set();
|
|
7135
|
+
for (const model of def.models) for (const format of Object.keys(model.formats)) formats.add(format);
|
|
7136
|
+
return Array.from(formats).toSorted();
|
|
7137
|
+
} catch {
|
|
7138
|
+
return [];
|
|
7139
|
+
}
|
|
7140
|
+
}
|
|
7141
|
+
/**
|
|
7316
7142
|
* Return a shallow-cloned executable tree with `rootStepId`'s `settings`
|
|
7317
7143
|
* merged with `overrides` (per-device values win). Non-matching root steps
|
|
7318
7144
|
* pass through unchanged. Used by `runFrame` to apply per-device detection
|