Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(ai-research): detect faces at native size in image scrub (#106881)

Robbie5f811bc4d4f7
diff --git a/Dockerfile.ml-mirror-image-scrub b/Dockerfile.ml-mirror-image-scrub
index cb1ee520586c..8f60a2784b1c 100644
--- a/Dockerfile.ml-mirror-image-scrub
+++ b/Dockerfile.ml-mirror-image-scrub
@@ -61,8 +61,8 @@ COPY --from=native-addon /build/replay-anonymizer.node native/replay-anonymizer.
ADD --checksum=sha256:193bab7a04fca699a6c82e6abb5b81bdb28177f0abd4062552b04908dafb19f8 \
https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx/resolve/2ba1506c0380b8f0b03dd142459aac66d4421f6c/inference.onnx \
models/dbnet_det.onnx
-ADD --checksum=sha256:8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 \
- https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/face_detection_yunet_2023mar.onnx \
+ADD --checksum=sha256:ebafce4e3c118d6554634be5c27ab333b4c047a9a8c3faf1d7cf93101c22f0f0 \
+ https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/face_detection_yunet_2026may.onnx \
models/yunet.onnx
ADD --checksum=sha256:8c28c49d9075f3ad15ebdc2961f02d5b3f99be944815b848b49c9f0e6f3fb689 \
https://huggingface.co/OwenElliott/image-safety-classifier-xs/resolve/54f4560bd9c5ee92d45dc30418a8f8680e80de6d/onnx/image-safety-classifier-xs.onnx \
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
index 406488946902..7438623a4f93 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md
@@ -98,7 +98,7 @@ Given an image, `advancedScrub` (`src/scrub.ts`):
1. **Apply the image policy**: reject an image when its XMP `plus:DataMining` value prohibits AI training.
2. **Plan the sizes**: `planScales` (`src/scale-plan.ts`) decides every resize from the source dimensions alone, before a pixel is read — the decoded frame, what each detector sees, and what gets stored.
An area budget rather than a long-side cap, so tall pages keep legible native resolution instead of being squashed.
- Faces are detected on a letterboxed (never squashed) 640×640 input; frames beyond 3:1 aspect are tiled along their long axis (overlapping windows) so a face on a tall page stays above the detector's minimum size instead of shrinking past it.
+ Faces are detected at up to 640 px on the long side, never enlarged or squashed; frames beyond 3:1 aspect are tiled along their long axis (overlapping windows) so a face on a tall page stays above the detector's minimum size instead of shrinking past it.
3. **NSFW/gore gate**: if the image is explicit or gory (NSFL + NSFW probability over `NSFW_THRESHOLD`), it collapses to a 1x1 blank.
4. **Face redaction**: every detected face (YuNet) is filled with its **mean colour**.
5. **Text redaction**: every detected text region (DBNet) gets the same fill, with a margin scaled to the box height (= font size).
@@ -156,7 +156,7 @@ src/ (production — ships)
src-image.ts decode the source once to raw RGB, to the size the plan asked for
geometry.ts shared Box type + grid rounding
safety.ts NSFW/gore gate (SwiftFormer image-safety classifier, ONNX)
- smoke.ts image-build-time smoke test: models load + one scrub, with networking disabled
+ smoke.ts image-build-time smoke test: models load + text and face fixtures scrubbed, with networking disabled
env.ts validated numeric env knobs — invalid values refuse to start (never fail open)
metrics.ts Prometheus registry: HTTP outcomes + scrub outcome signals
image-input.ts accepted image decoders, pixel limits, and embedded metadata policy
@@ -189,7 +189,7 @@ npm run build:native # build the Rust addon into native/ (needs cargo); again af
npm run test:unit # fast unit tests (no models/network, but the addon)
npm run eval # scrub-quality suite (text + face) over real images
npm run bench # latency + per-stage breakdown
-npm run smoke # models load + one scrub end to end (what the image build runs)
+npm run smoke # models load + text and face fixtures scrubbed end to end (what the image build runs)
npm run start # the sidecar server (needs `npm run setup` for the models)
```
@@ -246,7 +246,7 @@ Re-derive the floors with `tsx dev/glyph-floor.ts` (text), `tsx dev/floors.ts` (
The three ONNX models (safety gate, YuNet, DBNet) are `ADD`ed in `Dockerfile.ml-mirror-image-scrub` (repo root) from commit-pinned upstream URLs with BuildKit `--checksum` verification (same pins + sha256 checks as `dev/setup.ts` — keep them in sync).
zxing's wasm loads from `node_modules`.
-A build-time smoke test (`src/smoke.ts`) then loads the models and runs one scrub with networking disabled, so a broken model, a native-binary mismatch, or an accidental runtime network dependency fails the image build instead of crash-looping the deploy.
+A build-time smoke test (`src/smoke.ts`) then loads the models and scrubs a text fixture and a face fixture with networking disabled. It checks that text is found and that the face is filled, so a broken model, a native-binary mismatch, or an accidental runtime network dependency fails the image build instead of crash-looping the deploy.
The sidecar makes no network fetches at startup.
## The native addon
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.ts
index cd30d34482bd..9ef69927b20d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.ts
@@ -6,16 +6,19 @@
* tsx dev/face-bench.ts --setup # models, WIDER FACE val, portraits, composites
* tsx dev/face-bench.ts --dump-calibration # int8 calibration inputs, in out/face-calibration
* uv run --with onnxruntime --with onnx python dev/text-det-quantize.py \
- * models/candidates/yunet_2026may.onnx out/face-calibration models/candidates/yunet_2026may_int8.onnx
+ * models/yunet.onnx out/face-calibration models/candidates/yunet_2026may_int8.onnx
* uv run --with onnxruntime --with onnx python dev/text-det-quantize.py \
* models/candidates/yunet_n_dynamic.onnx out/face-calibration models/candidates/yunet_n_dynamic_int8.onnx
* ORT_THREADS=1 tsx dev/face-bench.ts [--detectors a,b] [--sets a,b] [--limit N] [--label name]
*
- * Production letterboxes every frame into YuNet's fixed 640x640 input, so a frame smaller than 640
- * is upscaled and a 16:9 frame is padded with black to a square. The plan counts the face stage's
- * scale as min(1, 640 / long side), so neither the upscale nor the padding buys anything towards the
- * ratio guarantee. The "native" variants use the dynamic-shape YuNet export at that same scale on a
- * canvas that only pads to the model's stride.
+ * Production reads each frame at min(1, 640 / long side) with the dynamic-shape YuNet export, on a
+ * canvas that pads only to the model's stride, which is the scale the plan counts for the face stage.
+ * The fixed-shape builds take only a 640x640 input, so their "fixed" entries letterbox: a frame
+ * smaller than 640 is enlarged and a 16:9 frame is padded with black to a square, and neither buys
+ * anything towards the ratio guarantee.
+ *
+ * The int8 builds calibrate on WIDER FACE, which is CC BY-NC-ND, and on portrait sets that declare no
+ * licence, so they show what int8 would buy and cannot ship.
*
* Two sets: a fixed subset of WIDER FACE val (real faces with its own boxes), and composites that
* paste portrait photos into web-shaped frames at controlled sizes, whose boxes come from the
@@ -33,7 +36,7 @@ import sharp, { type OverlayOptions } from 'sharp'
import { numFromEnv } from '../src/env.ts'
import { FACE_FLOOR } from '../src/floors.ts'
import { type Box } from '../src/geometry.ts'
-import { limitsFromEnv, planScales } from '../src/scale-plan.ts'
+import { FACE_INPUT_SIDE, limitsFromEnv, planScales } from '../src/scale-plan.ts'
import { type Src, decodeSrc, probeDims, srcSharp } from '../src/src-image.ts'
import { type YunetModel, detectFacesYunet, detectionWindowsForTest, loadYunet } from '../src/yunet.ts'
import { coverage, mulberry32 } from './bench-common.ts'
@@ -53,9 +56,9 @@ const DOWNLOADS: { file: string; url: string; sha256: string }[] = [
sha256: '321aa5a6afabf7ecc46a3d06bfab2b579dc96eb5c3be7edd365fa04502ad9294',
},
{
- file: 'models/candidates/yunet_2026may.onnx',
- url: `${ZOO}/face_detection_yunet_2026may.onnx`,
- sha256: 'ebafce4e3c118d6554634be5c27ab333b4c047a9a8c3faf1d7cf93101c22f0f0',
+ file: 'models/candidates/yunet_2023mar.onnx',
+ url: `${ZOO}/face_detection_yunet_2023mar.onnx`,
+ sha256: '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4',
},
{
file: 'models/candidates/yunet_n_dynamic.onnx',
@@ -93,22 +96,22 @@ interface GtImage {
interface DetectorSpec {
name: string
file: string
- /** fixed: production's 640x640 letterbox. native: frame aspect at min(1, 640/long), stride-padded. */
+ /** native: production's input, the frame at min(1, 640/long), stride-padded. fixed: the 640x640 letterbox. */
input: 'fixed' | 'native'
}
const DETECTORS: DetectorSpec[] = [
- { name: 'yunet (prod)', file: 'models/yunet.onnx', input: 'fixed' },
- { name: 'yunet-int8', file: 'models/candidates/yunet_2023mar_int8.onnx', input: 'fixed' },
- { name: 'yunet-2026 fixed', file: 'models/candidates/yunet_2026may.onnx', input: 'fixed' },
- { name: 'yunet-2026 native', file: 'models/candidates/yunet_2026may.onnx', input: 'native' },
- { name: 'yunet-2026-int8 native', file: 'models/candidates/yunet_2026may_int8.onnx', input: 'native' },
+ { name: 'yunet (prod)', file: 'models/yunet.onnx', input: 'native' },
+ { name: 'yunet fixed', file: 'models/yunet.onnx', input: 'fixed' },
+ { name: 'yunet-int8 native', file: 'models/candidates/yunet_2026may_int8.onnx', input: 'native' },
+ { name: 'yunet-2023mar fixed', file: 'models/candidates/yunet_2023mar.onnx', input: 'fixed' },
+ { name: 'yunet-2023mar-int8 fixed', file: 'models/candidates/yunet_2023mar_int8.onnx', input: 'fixed' },
// YuNet-n is the larger of the two released YuNet sizes; production and the 2026 export are YuNet-s.
{ name: 'yunet-n native', file: 'models/candidates/yunet_n_dynamic.onnx', input: 'native' },
{ name: 'yunet-n-int8 native', file: 'models/candidates/yunet_n_dynamic_int8.onnx', input: 'native' },
]
-const YUNET_SIDE = 640
+const FIXED_SIDE = 640
const STRIDE = 32
const SCORE_MIN = numFromEnv('YUNET_SCORE', 0.7, 0.05, 0.95)
const NMS_IOU = 0.3
@@ -348,16 +351,22 @@ function iou(a: Box, b: Box): number {
return inter === 0 ? 0 : inter / (a.width * a.height + b.width * b.height - inter)
}
+function inputScale(input: DetectorSpec['input'], win: Box): number {
+ const long = Math.max(win.width, win.height)
+ return input === 'fixed' ? FIXED_SIDE / long : Math.min(1, FACE_INPUT_SIDE / long)
+}
+
// --dump-calibration builds its tensors here too, so that the int8 builds calibrate on the inputs the native variants see.
-async function nativeInput(
+async function modelInput(
src: Src,
- win: Box
+ win: Box,
+ input: DetectorSpec['input']
): Promise<{ chw: Float32Array; dw: number; dh: number; cw: number; ch: number }> {
- const scale = Math.min(1, YUNET_SIDE / Math.max(win.width, win.height))
+ const scale = inputScale(input, win)
const dw = Math.max(1, Math.round(win.width * scale))
const dh = Math.max(1, Math.round(win.height * scale))
- const cw = upToStride(dw)
- const ch = upToStride(dh)
+ const cw = input === 'fixed' ? FIXED_SIDE : upToStride(dw)
+ const ch = input === 'fixed' ? FIXED_SIDE : upToStride(dh)
const whole = win.width === src.W && win.height === src.H
const { data } = await (whole ? srcSharp(src) : srcSharp(src).extract(win))
.resize(dw, dh, { fit: 'fill' })
@@ -374,12 +383,12 @@ async function nativeInput(
return { chw, dw, dh, cw, ch }
}
-/** The native canvas: src/yunet.ts's windows and decode, without the upscale or the square padding. */
-async function detectNative(model: YunetModel, src: Src): Promise<Box[]> {
+/** The fixed-shape builds: src/yunet.ts's windows and decode, on the 640x640 letterbox those builds require. */
+async function detectFixed(model: YunetModel, src: Src): Promise<Box[]> {
const { W, H } = src
const cand: { b: Box; s: number }[] = []
for (const win of detectionWindowsForTest(W, H)) {
- const { chw, dw, dh, cw, ch } = await nativeInput(src, win)
+ const { chw, dw, dh, cw, ch } = await modelInput(src, win, 'fixed')
const out = await model.session.run({ [model.inputName]: new ort.Tensor('float32', chw, [1, 3, ch, cw]) })
const sx = win.width / dw
const sy = win.height / dh
@@ -426,9 +435,11 @@ async function detectNative(model: YunetModel, src: Src): Promise<Box[]> {
/** How much the face stage enlarges or shrinks the frame, which is what a face's size at the model depends on. */
function modelScale(spec: DetectorSpec, W: number, H: number): number {
- const windows = detectionWindowsForTest(W, H)
- const long = Math.max(windows[0].width, windows[0].height)
- return spec.input === 'fixed' ? YUNET_SIDE / long : Math.min(1, YUNET_SIDE / long)
+ return inputScale(spec.input, detectionWindowsForTest(W, H)[0])
+}
+
+function detect(d: Loaded, src: Src): Promise<Box[]> {
+ return d.spec.input === 'native' ? detectFacesYunet(d.model, src, src.W, src.H) : detectFixed(d.model, src)
}
interface FaceResult {
@@ -492,17 +503,13 @@ async function evaluate(): Promise<void> {
const storedOverSource = plan.stored.height / gt.height
if (!warmed) {
for (const d of detectors) {
- await (d.spec.input === 'fixed'
- ? detectFacesYunet(d.model, src, src.W, src.H)
- : detectNative(d.model, src))
+ await detect(d, src)
}
warmed = true
}
for (const d of detectors) {
const t0 = performance.now()
- const boxes = await (d.spec.input === 'fixed'
- ? detectFacesYunet(d.model, src, src.W, src.H)
- : detectNative(d.model, src))
+ const boxes = await detect(d, src)
const ms = performance.now() - t0
let filled = 0
const mask = new Uint8Array(src.W * src.H)
@@ -602,7 +609,7 @@ async function dumpCalibration(): Promise<void> {
for (const [n, { gt }] of images.entries()) {
const buf = await readFile(join(DATA, gt.file))
const src = await decodeSrc(buf, planScales({ width: gt.width, height: gt.height }, limits).frame)
- const { chw, cw, ch } = await nativeInput(src, detectionWindowsForTest(src.W, src.H)[0])
+ const { chw, cw, ch } = await modelInput(src, detectionWindowsForTest(src.W, src.H)[0], 'native')
const file = `face_${n}.bin`
await writeFile(join(dir, file), Buffer.from(chw.buffer))
index.push({ file, shape: [1, 3, ch, cw] })
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts
index 4c11fb5b0217..a65de50e2cd2 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/floors.ts
@@ -3,7 +3,7 @@
* Detection floors for faces and codes, against the floor at which each still carries information in
* the stored artifact. The text version of this lives in glyph-floor.ts; the same question has to be
* asked separately for each detector, because their inputs are sized on different rules: DBNet scales
- * with the frame, YuNet letterboxes into a fixed 640 square, and zxing reads the frame at the plan's
+ * with the frame, YuNet reads at most a 640px long side and never enlarges, and zxing reads the frame at the plan's
* code scale.
*
* For each subject size it reports two things:
@@ -26,7 +26,7 @@ import sharp from 'sharp'
import { prepareZXingModule, writeBarcode } from 'zxing-wasm/writer'
import { detectCodes } from '../src/qr.ts'
-import { limitsFromEnv, planScales } from '../src/scale-plan.ts'
+import { FACE_INPUT_SIDE, limitsFromEnv, planScales } from '../src/scale-plan.ts'
import { type Src } from '../src/src-image.ts'
import { detectFacesYunet, loadYunet } from '../src/yunet.ts'
@@ -79,6 +79,18 @@ async function atScale(frame: Buffer, targetPx: number): Promise<Src> {
return { data, W, H, format: 'raw', inputPixels: FRAME_W * FRAME_H }
}
+// A re-identification attempt can enlarge the stored image, and YuNet never enlarges a small input itself, so the survival check reads the stored image at YuNet's longest side.
+async function enlargedForReader(art: Src): Promise<Src> {
+ const scale = FACE_INPUT_SIDE / Math.max(art.W, art.H)
+ const W = Math.round(art.W * scale)
+ const H = Math.round(art.H * scale)
+ const { data } = await sharp(art.data, { raw: { width: art.W, height: art.H, channels: 3 } })
+ .resize(W, H, { fit: 'fill' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ return { data, W, H, format: 'raw', inputPixels: art.inputPixels }
+}
+
async function faceFloors(): Promise<void> {
const yunet = await loadYunet('models/yunet.onnx')
const dir = 'test-data/faces'
@@ -93,7 +105,7 @@ async function faceFloors(): Promise<void> {
for (const f of files) {
const frame = await place(await readFile(join(dir, f)), sidePx)
const det = await atScale(frame, DETECT_PX)
- const art = await atScale(frame, STORE_PX)
+ const art = await enlargedForReader(await atScale(frame, STORE_PX))
if ((await detectFacesYunet(yunet, det, det.W, det.H)).length > 0) {
detected++
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts
index 0a6f44cc2f68..5cb235952556 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts
@@ -26,9 +26,9 @@ const MODELS: { url: string; file: string; sha256: string }[] = [
sha256: '193bab7a04fca699a6c82e6abb5b81bdb28177f0abd4062552b04908dafb19f8',
},
{
- url: 'https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/face_detection_yunet_2023mar.onnx',
+ url: 'https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/face_detection_yunet_2026may.onnx',
file: 'models/yunet.onnx',
- sha256: '8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4',
+ sha256: 'ebafce4e3c118d6554634be5c27ab333b4c047a9a8c3faf1d7cf93101c22f0f0',
},
{
url: 'https://huggingface.co/OwenElliott/image-safety-classifier-xs/resolve/54f4560bd9c5ee92d45dc30418a8f8680e80de6d/onnx/image-safety-classifier-xs.onnx',
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts
index 5525000815dd..d34abbe6b6a7 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts
@@ -97,9 +97,8 @@ describe('scale-plan', () => {
expect(tight.stored.width * tight.stored.height).toBeLessThanOrEqual(2_000)
})
- it('lets a fixed-input detector enlarge a frame smaller than its square', () => {
- // The one allowed upscale: the size belongs to the model, and filling the square is what
- // maximises the subject at it. Only the reduction matters for the ratio, hence the cap at 1.
+ it('reads a frame smaller than the face input at its own size', () => {
+ // YuNet never enlarges a frame, so a scale above 1 would credit it with detail it never saw.
expect(faceInputScale({ width: 200, height: 100 }, 640, 3, 6)).toBe(1)
expect(faceInputScale({ width: 1280, height: 720 }, 640, 3, 6)).toBeCloseTo(0.5, 5)
})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts
index 07f2cbadf21d..5c9accfd41d0 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts
@@ -10,9 +10,7 @@
*
* The rules it encodes, in full:
*
- * 1. Never upscale. Enlarging pixels adds nothing and softens the edges detection depends on. The
- * one exception is a detector whose input size is fixed by its model, which is a property of the
- * model rather than a choice, and is marked as such.
+ * 1. Never upscale. Enlarging pixels adds nothing and softens the edges detection depends on.
* 2. Bound the work by the tensor, not by the frame. A budget on frame area does not bound the
* tensor once a collapsed axis is padded up to the encoder's stride.
* 3. Store small. The final consumer identifies what kind of site a session is on, so it needs
@@ -34,7 +32,7 @@ export interface ScalePlan {
frame: Dims
/** What DBNet sees: content, and the stride-padded canvas that is actually allocated. */
text: { content: Dims; canvas: Dims }
- /** What YuNet sees. Its input is a fixed square, so this is how much of the frame reaches it. */
+ /** What YuNet sees, as a fraction of the frame. */
face: { scale: number }
/** What zxing sees, as a fraction of the frame. */
code: { scale: number }
@@ -43,9 +41,9 @@ export interface ScalePlan {
}
export interface PlanLimits {
- /** Aspect past which the face detector tiles rather than letterboxing the whole frame, and the
+ /** Aspect past which the face detector tiles rather than reading the whole frame in one pass, and the
* aspect of each tile. The planner has to know these: modelling the detector as a single
- * letterbox understates how much of a long frame it really sees. */
+ * pass understates how much of a long frame it really sees. */
faceTileAbove: number
faceTileAspect: number
/** Area budget for the decoded frame. */
@@ -54,7 +52,7 @@ export interface PlanLimits {
textCanvasPixels: number
/** Upper bound on the stored image; the ratio may make it smaller still. */
storedPixels: number
- /** The fixed square YuNet's build requires. */
+ /** The longest side YuNet reads a frame or tile at. */
faceInputSide: number
/** Stride the text encoder needs its input to be a multiple of. */
stride: number
@@ -68,8 +66,9 @@ const atLeastOne = (n: number): number => Math.max(1, Math.floor(n))
* disagree, which is how a legal stored size produced an illegal frame size. */
const MIN_FRAME_PIXELS = 96 * 96
-/** The face detector's tiling rule, owned here because the plan has to model it. yunet.ts imports
+/** The face detector's input size and tiling rule, owned here because the plan has to model them. yunet.ts imports
* these rather than declaring its own, so the model and the plan cannot disagree. */
+export const FACE_INPUT_SIDE = 640
export const FACE_TILE_ABOVE = 3
export const FACE_TILE_ASPECT = 6
@@ -158,13 +157,8 @@ export function fitToCanvas(dims: Dims, budgetPixels: number, stride: number): {
/**
* How much of the frame the face detector sees.
*
- * Scaling the long side to fill the square maximises the subject at the model, which is what recall
- * wants, so enlarging a frame smaller than the square is deliberate and allowed by rule 1: the size
- * is the model's, not ours. What matters here is only the reduction, since that is what narrows the
- * ratio.
- *
- * It tiles rather than letterboxing once a frame is longer than `tileAbove`, so the scale is set by
- * the TILE and not by the whole frame. Modelling it as a single letterbox understated the scale on
+ * It tiles once a frame is longer than `tileAbove`, so the scale is set by
+ * the TILE and not by the whole frame. Modelling it as a single pass understated the scale on
* every long frame, and because the stored size is derived from the weakest detector that understating
* crushed the artifact: an 8000x60 banner planned a 1px-tall image where the real geometry supports
* nineteen, for a guarantee that never asked for it.
@@ -261,7 +255,7 @@ export function limitsFromEnv(): PlanLimits {
),
textCanvasPixels: numFromEnv('DET_CANVAS_PIXELS', 736 * 736, 256 * 256, 4096 * 4096),
storedPixels,
- faceInputSide: 640,
+ faceInputSide: FACE_INPUT_SIDE,
faceTileAbove: FACE_TILE_ABOVE,
faceTileAspect: FACE_TILE_ASPECT,
stride: 32,
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke-face.jpg b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke-face.jpg
new file mode 100644
index 000000000000..164a786c47ac
Binary files /dev/null and b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke-face.jpg differ
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts
index 8243dd1192be..22032f2e473b 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/smoke.ts
@@ -13,8 +13,12 @@
* detectors: with one the build would still pass while running no inference at all, so an ONNX
* binary that loads but cannot `run`, or a zxing wasm module that never instantiates, would reach
* production. Text is the assertion because it exercises the longest path, DBNet through to the
- * composite, and it is the detector whose output the scrub mostly consists of.
+ * composite, and it is the detector whose output the scrub mostly consists of. The face check reads
+ * the output pixels, because a face model can run and still put its boxes away from the face.
*/
+import { readFile } from 'node:fs/promises'
+import sharp from 'sharp'
+
import { startPool } from './pool.ts'
const WORKER_URL = new URL('./scrub-worker.ts', import.meta.url)
@@ -86,11 +90,47 @@ const TEXT_FIXTURE_PNG = Buffer.from(
'base64'
)
+// Eileen Collins' public-domain NASA portrait from scikit-image's `astronaut` sample, mirrored and cropped to 480x200: on this non-square canvas a row and column mix-up in the face detector's decode moves the fill off the face.
+const FACE_FIXTURE = new URL('./smoke-face.jpg', import.meta.url)
+// The middle half of the fixture's face, clear of the feathered edge of the fill.
+const FACE_MIDDLE = { left: 248, top: 60, width: 44, height: 51 }
+
+async function greySpreadOverFaceMiddle(
+ image: Buffer,
+ fixture: { width: number; height: number },
+ width: number,
+ height: number
+): Promise<number> {
+ const { data, info } = await sharp(image)
+ .resize(width, height, { fit: 'fill' })
+ .greyscale()
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ const x0 = Math.round((FACE_MIDDLE.left * width) / fixture.width)
+ const x1 = Math.round(((FACE_MIDDLE.left + FACE_MIDDLE.width) * width) / fixture.width)
+ const y0 = Math.round((FACE_MIDDLE.top * height) / fixture.height)
+ const y1 = Math.round(((FACE_MIDDLE.top + FACE_MIDDLE.height) * height) / fixture.height)
+ let count = 0
+ let sum = 0
+ let sumOfSquares = 0
+ for (let y = y0; y < y1; y++) {
+ for (let x = x0; x < x1; x++) {
+ const grey = data[(y * info.width + x) * info.channels]
+ count++
+ sum += grey
+ sumOfSquares += grey * grey
+ }
+ }
+ const mean = sum / count
+ return Math.sqrt(Math.max(0, sumOfSquares / count - mean * mean))
+}
+
async function main(): Promise<void> {
const pool = await startPool(2, WORKER_URL)
const png = TEXT_FIXTURE_PNG
+ const face = await readFile(FACE_FIXTURE)
// Two at once, so the build fails if a second worker cannot start or the pool mis-routes replies.
- const [first, second] = await Promise.all([pool.scrub(png), pool.scrub(png)])
+ const [first, second, faceScrub] = await Promise.all([pool.scrub(png), pool.scrub(png), pool.scrub(face)])
await pool.close()
for (const [label, result] of [
@@ -110,9 +150,21 @@ async function main(): Promise<void> {
throw new Error(`smoke scrub (${label}) found no text in a fixture that is mostly text`)
}
}
+ if (faceScrub.t.faces === 0) {
+ throw new Error('smoke scrub found no face in the face fixture')
+ }
+ const fixture = await sharp(face).metadata()
+ const stored = await sharp(faceScrub.out).metadata()
+ const before = await greySpreadOverFaceMiddle(face, fixture, stored.width, stored.height)
+ const after = await greySpreadOverFaceMiddle(faceScrub.out, fixture, stored.width, stored.height)
+ if (after > before / 4) {
+ throw new Error(
+ `smoke scrub left the fixture's face unfilled: grey spread ${after.toFixed(1)}, against ${before.toFixed(1)} before the scrub`
+ )
+ }
console.log(
`smoke scrub OK (${Math.round(first.t.totalMs)}ms, ${Math.round(second.t.totalMs)}ms, ` +
- `${first.t.textBoxes} text regions)`
+ `${first.t.textBoxes} text regions, face filled: grey spread ${after.toFixed(1)} from ${before.toFixed(1)})`
)
}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts
index e28da183ccec..6891ca7c0e65 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/yunet.ts
@@ -11,7 +11,7 @@ import { ORT_THREADS } from './cores.ts'
import { numFromEnv } from './env.ts'
import { type Box } from './geometry.ts'
import { rgbToChw } from './pixel-convert.ts'
-// Tiling bounds for extreme-aspect frames. A single letterboxed pass scales by 640/longSide, so on a
+// Tiling bounds for extreme-aspect frames. A single pass scales by 640/longSide, so on a
// very tall/wide image a face (at most ~shortSide across) can land below the detector's smallest
// stride. Above MAX_ASPECT the frame is cut along its long axis into windows of aspect TILE_ASPECT
// (overlapping by one shortSide, so a face — at most one shortSide across — is always fully inside
@@ -21,13 +21,13 @@ import { rgbToChw } from './pixel-convert.ts'
// Kept in step with PlanLimits.faceTileAbove / faceTileAspect: the planner needs the same rule to
// know how much of a long frame this stage really sees, and two copies of it is the drift the
// planner exists to remove.
-import { FACE_TILE_ABOVE, FACE_TILE_ASPECT, faceWindowLong } from './scale-plan.ts'
+import { FACE_INPUT_SIDE, FACE_TILE_ABOVE, FACE_TILE_ASPECT, faceWindowLong } from './scale-plan.ts'
import { type Src, srcSharp } from './src-image.ts'
-const YUNET_SIDE = 640 // this YuNet build has a FIXED 640x640 input (dynamic dims are rejected)
const SCORE_MIN = numFromEnv('YUNET_SCORE', 0.7, 0.05, 0.95)
const NMS_IOU = 0.3
const STRIDES = [8, 16, 32]
+const LARGEST_STRIDE = 32
const PAD = 0.25 // expand each detected face box so hairline/chin/ears are covered
export interface YunetModel {
@@ -50,6 +50,8 @@ export async function loadYunet(modelPath: string): Promise<YunetModel> {
return { session, inputName: session.inputNames[0] }
}
+const upToStride = (n: number): number => Math.max(LARGEST_STRIDE, Math.ceil(n / LARGEST_STRIDE) * LARGEST_STRIDE)
+
function iou(a: Box, b: Box): number {
const x1 = Math.max(a.left, b.left)
const y1 = Math.max(a.top, b.top)
@@ -118,29 +120,27 @@ async function detectInWindow(
win: Window,
scoreMin: number
): Promise<{ b: Box; s: number }[]> {
- // The model input is a fixed square, so LETTERBOX: uniform downscale (aspect preserved) into the
- // top-left of a black 640x640 canvas. A fit-to-square squash would smear faces on tall/wide
- // frames past detectability (a 13:1 page compresses faces 13x on one axis); letterboxing keeps
- // them undistorted, merely smaller.
- const scale = YUNET_SIDE / Math.max(win.width, win.height)
+ // Padding rather than resizing to reach the stride, because resizing up enlarges real pixels (rule 1 in scale-plan.ts).
+ const scale = Math.min(1, FACE_INPUT_SIDE / Math.max(win.width, win.height))
const dw = Math.max(1, Math.round(win.width * scale))
const dh = Math.max(1, Math.round(win.height * scale))
+ const cw = upToStride(dw)
+ const ch = upToStride(dh)
const isWholeFrame = win.width === W && win.height === H
const pipeline = isWholeFrame ? srcSharp(src) : srcSharp(src).extract(win)
const { data } = await pipeline
.resize(dw, dh, { fit: 'fill' })
- .extend({ top: 0, left: 0, right: YUNET_SIDE - dw, bottom: YUNET_SIDE - dh, background: '#000' })
+ .extend({ top: 0, left: 0, right: cw - dw, bottom: ch - dh, background: '#000' })
.raw()
.toBuffer({ resolveWithObject: true })
// RGB(HWC, 0-255) -> BGR(CHW, float32, no normalization), as OpenCV's YuNet expects.
- const side = YUNET_SIDE
- const chw = new Float32Array(3 * side * side)
+ const chw = new Float32Array(3 * cw * ch)
rgbToChw(data, chw, 'bgr')
- const out = await model.session.run({ [model.inputName]: new ort.Tensor('float32', chw, [1, 3, side, side]) })
+ const out = await model.session.run({ [model.inputName]: new ort.Tensor('float32', chw, [1, 3, ch, cw]) })
// Uniform inverse scale back to window coords, then offset to frame coords; boxes decoded in the
- // letterbox padding scale past the window edge and get clamped away.
+ // padding scale past the window edge and get clamped away.
const sx = win.width / dw
const sy = win.height / dh
const cand: { b: Box; s: number }[] = []
@@ -148,8 +148,8 @@ async function detectInWindow(
const cls = out[`cls_${s}`].data as Float32Array
const obj = out[`obj_${s}`].data as Float32Array
const bbox = out[`bbox_${s}`].data as Float32Array
- const fw = Math.floor(side / s)
- const fh = Math.floor(side / s)
+ const fw = cw / s
+ const fh = ch / s
for (let r = 0; r < fh; r++) {
for (let c = 0; c < fw; c++) {
const i = r * fw + c