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.

chore(ai-research): add detector benchmarks for the image-scrub sidecar (#106612)

Robbie2d3ee16a10ce
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 9c4617d202e3..eacf6cfc212a 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
@@ -165,6 +165,10 @@ dev/ (non-production)
bench.ts scale.ts worker-proc.ts latency + throughput benchmarks
make-corpus.ts synthetic screenshot corpus
setup.ts download ONNX models + sample test images (npm run setup)
+ text-det-bench.ts text detector comparison: cost and per-word redaction recall, per model and canvas size
+ text-det-setup.ts text-det-corpus.ts text-det-quantize.py text-det-dynamic-hw.py its models, labelled images and int8 builds
+ face-bench.ts face detector comparison: YuNet variants and input sizes, cost and per-face redaction recall
+ code-bench.ts code detector cost against zxing's input scale, and which codes stay decodable from the stored image
fixtures/ committed eval fixtures (e.g. a retina Wikipedia page: dense text + a face)
models/ test-data/ corpus/ out/ downloaded/generated by setup (gitignored)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/bench-common.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/bench-common.ts
new file mode 100644
index 000000000000..5fe19377e049
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/bench-common.ts
@@ -0,0 +1,34 @@
+import { type Box } from '../src/geometry.ts'
+
+export function mulberry32(seed: number): () => number {
+ let a = seed >>> 0
+ return () => {
+ a = (a + 0x6d2b79f5) >>> 0
+ let t = a
+ t = Math.imul(t ^ (t >>> 15), t | 1)
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61)
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296
+ }
+}
+
+/** The fraction of `gt` ([left, top, right, bottom)) that the union of `boxes` covers. */
+export function coverage(boxes: Box[], gt: [number, number, number, number]): number {
+ const [x0, y0, x1, y1] = gt
+ const W = Math.max(1, x1 - x0)
+ const H = Math.max(1, y1 - y0)
+ const mask = new Uint8Array(W * H)
+ for (const b of boxes) {
+ const l = Math.max(x0, b.left)
+ const t = Math.max(y0, b.top)
+ const r = Math.min(x1, b.left + b.width)
+ const bt = Math.min(y1, b.top + b.height)
+ for (let y = t; y < bt; y++) {
+ mask.fill(1, (y - y0) * W + (l - x0), (y - y0) * W + (r - x0))
+ }
+ }
+ let n = 0
+ for (const v of mask) {
+ n += v
+ }
+ return n / (W * H)
+}
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/code-bench.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/code-bench.ts
new file mode 100644
index 000000000000..5126ed322006
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/code-bench.ts
@@ -0,0 +1,342 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Code detector cost against scale: how small the frame handed to zxing can get before a code that
+ * is still decodable from the stored image goes unredacted.
+ *
+ * tsx dev/code-bench.ts [--limit N] [--label name] [--shard k/n]
+ *
+ * --limit keeps the first N frame, code, size and degradation combinations. --shard k/n renders and
+ * checks every nth of those, starting at k, so n processes together cover the whole set once.
+ *
+ * zxing reads the full frame today. A code only leaks if a reader can decode it from the stored
+ * image, and the stored image is several times smaller than the frame, so zxing may not need the
+ * whole frame to find every code that could leak. Each generated image is checked twice: zxing on the
+ * unredacted stored image (at 1x, 2x and 3x, since an attacker can upscale) decides whether the code
+ * could leak, and zxing on the frame at each scale decides whether the scrub would have covered it.
+ *
+ * Scales are either a fraction of the frame (fN), a multiple of the stored image's scale (sN), or
+ * "plan": the multiple the scale plan already requires of every detector (binding ratio times the
+ * safety factor). None is ever above the frame. The sN points answer the ratio question directly: the smallest multiple at
+ * which every leakable code is still covered is the ratio codes need.
+ */
+import { readFileSync } from 'node:fs'
+import { mkdir, writeFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import { join } from 'node:path'
+import sharp from 'sharp'
+import { prepareZXingModule, writeBarcode } from 'zxing-wasm/writer'
+
+import { bindingRatio } from '../src/floors.ts'
+import { detectCodes } from '../src/qr.ts'
+import { limitsFromEnv, planScales } from '../src/scale-plan.ts'
+import { type Src, decodeSrc } from '../src/src-image.ts'
+import { coverage } from './bench-common.ts'
+
+// src-image.ts loads image-input.ts, which blocks the SVG loader for the whole process, and the codes
+// are drawn from zxing's SVG output.
+sharp.unblock({ operation: ['VipsForeignLoadSvg'] })
+
+const writerWasm = readFileSync(createRequire(`${process.cwd()}/`).resolve('zxing-wasm/writer/zxing_writer.wasm'))
+prepareZXingModule({
+ overrides: {
+ wasmBinary: writerWasm.buffer.slice(writerWasm.byteOffset, writerWasm.byteOffset + writerWasm.byteLength),
+ },
+})
+
+const ROOT = new URL('..', import.meta.url).pathname
+
+type Format = 'QRCode' | 'DataMatrix' | 'Aztec' | 'PDF417' | 'Code128'
+
+const CODES: { payload: string; format: Format }[] = [
+ { payload: 'otpauth://totp/Acme:[email protected]?secret=JBSWY3DPEHPK3PXP&issuer=Acme', format: 'QRCode' },
+ { payload: 'https://acme.example.com/t/b7f3a91c', format: 'QRCode' },
+ { payload: 'ACCT-0098761234', format: 'DataMatrix' },
+ { payload: 'TICKET-A1B2C3-SEAT-14F', format: 'Aztec' },
+ { payload: 'PNR X7Q2LM FLIGHT 0421', format: 'PDF417' },
+ { payload: '4242424242424242', format: 'Code128' },
+]
+
+const FRAMES: { name: string; width: number; height: number }[] = [
+ { name: 'desktop', width: 1920, height: 1080 },
+ { name: 'laptop', width: 1280, height: 720 },
+ { name: 'mobile', width: 1170, height: 2532 },
+ { name: 'product', width: 800, height: 800 },
+ { name: 'thumbnail', width: 480, height: 270 },
+ { name: 'ad', width: 300, height: 250 },
+]
+
+/** Longest code side as a fraction of the frame's short side. */
+const CODE_FRACTIONS = [0.06, 0.09, 0.13, 0.18, 0.26, 0.38, 0.55]
+
+const DEGRADATIONS = ['none', 'blur', 'rotate', 'jpeg'] as const
+type Degradation = (typeof DEGRADATIONS)[number]
+
+const FRAME_SCALES = [1, 0.7, 0.5, 0.35, 0.25]
+const STORED_MULTIPLES = [1, 1.3, 1.6, 2, 3, 4]
+const COVERED = 0.9
+
+interface Sample {
+ file: string
+ frame: { name: string; width: number; height: number }
+ code: (typeof CODES)[number]
+ fraction: number
+ degradation: Degradation
+ png: Buffer
+ /** Where the code's pixels sit in the source image: [left, top, right, bottom). */
+ box: [number, number, number, number]
+ /** Modules along the code's long side, including zxing's quiet zone. */
+ modules: number
+ /** The code's long side in source px before any rotation, which is the length `modules` spans. */
+ codeSide: number
+}
+
+async function renderCode(code: (typeof CODES)[number], side: number): Promise<{ png: Buffer; modules: number }> {
+ const { svg } = await writeBarcode(code.payload, { format: code.format })
+ const meta = await sharp(Buffer.from(svg)).metadata()
+ const modules = Math.max(meta.width!, meta.height!)
+ const png = await sharp(Buffer.from(svg))
+ .resize(side, side, { fit: 'inside', kernel: 'nearest' })
+ .flatten({ background: '#ffffff' })
+ .png()
+ .toBuffer()
+ return { png, modules }
+}
+
+async function makeSample(
+ frame: (typeof FRAMES)[number],
+ code: (typeof CODES)[number],
+ fraction: number,
+ degradation: Degradation,
+ n: number
+): Promise<Sample | null> {
+ const side = Math.round(Math.min(frame.width, frame.height) * fraction)
+ let { png, modules } = await renderCode(code, side)
+ const upright = await sharp(png).metadata()
+ if (degradation === 'rotate') {
+ png = await sharp(png).rotate(8, { background: '#ffffff' }).png().toBuffer()
+ }
+ const { width: cw, height: ch } = await sharp(png).metadata()
+ if (cw! >= frame.width || ch! >= frame.height) {
+ return null
+ }
+ const left = Math.round((frame.width - cw!) * 0.62)
+ const top = Math.round((frame.height - ch!) * 0.38)
+ const lines = Array.from(
+ { length: 6 },
+ (_, i) =>
+ `<text x="${Math.round(frame.width * 0.05)}" y="${Math.round(frame.height * (0.1 + i * 0.05))}" font-family="Arial" font-size="${Math.max(9, Math.round(frame.height * 0.02))}" fill="#374151">Order #A1B2C3 scan to confirm your booking</text>`
+ ).join('')
+ const background = Buffer.from(
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${frame.width}" height="${frame.height}"><rect width="100%" height="100%" fill="#f3f4f6"/>${lines}</svg>`
+ )
+ let out = sharp(background).composite([{ input: png, left, top }])
+ if (degradation === 'blur') {
+ out = sharp(await out.png().toBuffer()).blur(0.9)
+ }
+ const encoded = degradation === 'jpeg' ? await out.jpeg({ quality: 70 }).toBuffer() : await out.png().toBuffer()
+ return {
+ file: `code_${frame.name}_${code.format}_${Math.round(fraction * 100)}_${degradation}_${n}`,
+ frame,
+ code,
+ fraction,
+ degradation,
+ png: encoded,
+ box: [left, top, left + cw!, top + ch!],
+ modules,
+ codeSide: Math.max(upright.width!, upright.height!),
+ }
+}
+
+async function scaled(src: Src, width: number, height: number): Promise<Src> {
+ if (width === src.W && height === src.H) {
+ return src
+ }
+ const { data } = await sharp(src.data, { raw: { width: src.W, height: src.H, channels: 3 } })
+ .resize(width, height, { fit: 'fill' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ return { data, W: width, H: height, format: 'raw', inputPixels: src.inputPixels }
+}
+
+/** Whether zxing decodes the code from the stored image, as it is or upscaled the way an attacker would. */
+async function decodableFromStored(src: Src, stored: { width: number; height: number }): Promise<boolean> {
+ const art = await scaled(src, stored.width, stored.height)
+ for (const factor of [1, 2, 3]) {
+ const probe =
+ factor === 1
+ ? art
+ : await (async (): Promise<Src> => {
+ const { data } = await sharp(art.data, { raw: { width: art.W, height: art.H, channels: 3 } })
+ .resize(art.W * factor, art.H * factor, { kernel: 'cubic' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ return { data, W: art.W * factor, H: art.H * factor, format: 'raw', inputPixels: art.inputPixels }
+ })()
+ if ((await detectCodes(probe)).length > 0) {
+ return true
+ }
+ }
+ return false
+}
+
+interface Result {
+ file: string
+ frame: string
+ format: Format
+ degradation: Degradation
+ sourcePixels: number
+ leakable: boolean
+ point: string
+ zxingPixels: number
+ modulePxAtZxing: number
+ ms: number
+ coverage: number
+}
+
+function arg(name: string): string | undefined {
+ const i = process.argv.indexOf(`--${name}`)
+ return i >= 0 ? process.argv[i + 1] : undefined
+}
+
+async function main(): Promise<void> {
+ const limit = Number(arg('limit') ?? 1e9)
+ const [shard, shards] = (arg('shard') ?? '0/1').split('/').map(Number)
+ const limits = limitsFromEnv()
+ const combinations = FRAMES.flatMap((frame) =>
+ CODES.flatMap((code) =>
+ CODE_FRACTIONS.flatMap((fraction) =>
+ DEGRADATIONS.map((degradation) => ({ frame, code, fraction, degradation }))
+ )
+ )
+ ).slice(0, limit)
+ const samples: Sample[] = []
+ for (const [seed, { frame, code, fraction, degradation }] of combinations.entries()) {
+ if (seed % shards !== shard) {
+ continue
+ }
+ const s = await makeSample(frame, code, fraction, degradation, seed)
+ if (s) {
+ samples.push(s)
+ }
+ }
+ console.log(`${samples.length} images`)
+
+ const results: Result[] = []
+ for (const [i, s] of samples.entries()) {
+ const source = { width: s.frame.width, height: s.frame.height }
+ const plan = planScales(source, limits)
+ const src = await decodeSrc(s.png, plan.frame)
+ const leakable = await decodableFromStored(src, plan.stored)
+ const fx = src.W / source.width
+ const fy = src.H / source.height
+ const gt: [number, number, number, number] = [
+ Math.floor(s.box[0] * fx),
+ Math.floor(s.box[1] * fy),
+ Math.ceil(s.box[2] * fx),
+ Math.ceil(s.box[3] * fy),
+ ]
+ const storedScale = Math.max(plan.stored.width / src.W, plan.stored.height / src.H)
+ const points: [string, number][] = [
+ ...FRAME_SCALES.map((f): [string, number] => [`f${f}`, f]),
+ ...STORED_MULTIPLES.map((m): [string, number] => [`s${m}`, Math.min(1, m * storedScale)]),
+ ['plan', Math.min(1, bindingRatio() * limits.safetyFactor * storedScale)],
+ ]
+ for (const [point, scale] of points) {
+ const w = Math.max(1, Math.round(src.W * scale))
+ const h = Math.max(1, Math.round(src.H * scale))
+ const input = await scaled(src, w, h)
+ const t0 = performance.now()
+ const boxes = await detectCodes(input)
+ const ms = performance.now() - t0
+ const back = boxes.map((b) => ({
+ left: Math.floor((b.left * src.W) / w),
+ top: Math.floor((b.top * src.H) / h),
+ width: Math.ceil((b.width * src.W) / w),
+ height: Math.ceil((b.height * src.H) / h),
+ }))
+ const codeSideAtZxing = s.codeSide * fx * (w / src.W)
+ results.push({
+ file: s.file,
+ frame: s.frame.name,
+ format: s.code.format,
+ degradation: s.degradation,
+ sourcePixels: source.width * source.height,
+ leakable,
+ point,
+ zxingPixels: w * h,
+ modulePxAtZxing: codeSideAtZxing / s.modules,
+ ms,
+ coverage: coverage(back, gt),
+ })
+ }
+ if ((i + 1) % 50 === 0) {
+ console.error(` ${i + 1}/${samples.length}`)
+ }
+ }
+
+ const label = arg('label') ?? 'code-bench'
+ await mkdir(join(ROOT, 'out/code-bench'), { recursive: true })
+ await writeFile(join(ROOT, `out/code-bench/${label}.json`), JSON.stringify(results))
+ report(results)
+}
+
+function report(results: Result[]): void {
+ const points = [...new Set(results.map((r) => r.point))]
+ const images = new Set(results.map((r) => r.file)).size
+ const leakable = new Set(results.filter((r) => r.leakable).map((r) => r.file)).size
+ console.log(`\n${images} images, ${leakable} with a code still decodable from the stored image\n`)
+ console.log(
+ ` ${'point'.padEnd(8)}${'zxing MP'.padStart(10)}${'ms/img'.padStart(9)}${'leakable covered'.padStart(18)}${'all covered'.padStart(13)}`
+ )
+ const mean = (xs: number[]): number => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
+ for (const point of points) {
+ const rs = results.filter((r) => r.point === point)
+ const leak = rs.filter((r) => r.leakable)
+ const covered = leak.filter((r) => r.coverage >= COVERED).length
+ console.log(
+ ` ${point.padEnd(8)}${(mean(rs.map((r) => r.zxingPixels)) / 1e6).toFixed(3).padStart(10)}${mean(
+ rs.map((r) => r.ms)
+ )
+ .toFixed(1)
+ .padStart(9)}` +
+ `${`${covered}/${leak.length}`.padStart(18)}${`${rs.filter((r) => r.coverage >= COVERED).length}/${rs.length}`.padStart(13)}`
+ )
+ }
+ console.log('\n leakable codes missed, by point and format')
+ for (const point of points) {
+ const missed = results.filter((r) => r.point === point && r.leakable && r.coverage < COVERED)
+ if (missed.length) {
+ const byFormat = new Map<string, number>()
+ for (const r of missed) {
+ byFormat.set(`${r.format}/${r.degradation}`, (byFormat.get(`${r.format}/${r.degradation}`) ?? 0) + 1)
+ }
+ console.log(` ${point.padEnd(8)}${[...byFormat].map(([k, v]) => `${k}:${v}`).join(' ')}`)
+ }
+ }
+ console.log('\n detection rate by module size at the zxing input (px per module), all points pooled')
+ const edges = [0, 0.5, 0.75, 1, 1.25, 1.5, 2, 3, 4, 1e9]
+ for (const format of new Set(results.map((r) => r.format))) {
+ const cells = edges.slice(0, -1).map((lo, i) => {
+ const b = results.filter(
+ (r) => r.format === format && r.modulePxAtZxing >= lo && r.modulePxAtZxing < edges[i + 1]
+ )
+ return (
+ b.length >= 10
+ ? `${Math.round((100 * b.filter((r) => r.coverage >= COVERED).length) / b.length)}%`
+ : '.'
+ ).padStart(7)
+ })
+ console.log(` ${format.padEnd(12)}${cells.join('')}`)
+ }
+ console.log(
+ ` ${''.padEnd(12)}${edges
+ .slice(0, -1)
+ .map((lo, i) => `${lo}-${edges[i + 1] === 1e9 ? '' : edges[i + 1]}`.padStart(7))
+ .join('')}`
+ )
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
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
new file mode 100644
index 000000000000..cd30d34482bd
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/face-bench.ts
@@ -0,0 +1,622 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Face detector comparison: what each YuNet variant costs, and which faces its redaction covers, on
+ * the frames the production plan hands the face stage.
+ *
+ * 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
+ * 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.
+ *
+ * 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
+ * production detector on the full-size portrait. A face counts as redacted when the fills cover 90%
+ * of its box. "Readable" faces are at least FACE_FLOOR.readableAt px in the stored image.
+ */
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import { existsSync, readFileSync } from 'node:fs'
+import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import * as ort from 'onnxruntime-node'
+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 { 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'
+
+const ROOT = new URL('..', import.meta.url).pathname
+const DATA = join(ROOT, 'test-data/face-bench')
+const UA = 'Mozilla/5.0 posthog-replay-image-scrub'
+
+const ZOO =
+ 'https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet'
+const WIDER =
+ 'https://huggingface.co/datasets/CUHK-CSE/wider_face/resolve/db171f1b7fedf4d3453e81297ff02f9915356d19/data'
+const DOWNLOADS: { file: string; url: string; sha256: string }[] = [
+ {
+ file: 'models/candidates/yunet_2023mar_int8.onnx',
+ url: `${ZOO}/face_detection_yunet_2023mar_int8.onnx`,
+ sha256: '321aa5a6afabf7ecc46a3d06bfab2b579dc96eb5c3be7edd365fa04502ad9294',
+ },
+ {
+ file: 'models/candidates/yunet_2026may.onnx',
+ url: `${ZOO}/face_detection_yunet_2026may.onnx`,
+ sha256: 'ebafce4e3c118d6554634be5c27ab333b4c047a9a8c3faf1d7cf93101c22f0f0',
+ },
+ {
+ file: 'models/candidates/yunet_n_dynamic.onnx',
+ url: 'https://github.com/ShiqiYu/libfacedetection.train/raw/dca340aa082c71081a68d17db8e58b33a58a914b/onnx/yunet_n_dynamic.onnx',
+ sha256: '104ee26c71d5c270ce79a6b3dced91c91013260d29a6bf18f9296c5b8c4c2b12',
+ },
+ // WIDER FACE is CC BY-NC-ND 4.0: an internal eval only, and nothing derived from it is committed.
+ {
+ file: 'test-data/face-bench/wider/wider_face_split.zip',
+ url: `${WIDER}/wider_face_split.zip`,
+ sha256: 'c7561e4f5e7a118c249e0a5c5c902b0de90bbf120d7da9fa28d99041f68a8a5c',
+ },
+ {
+ file: 'test-data/face-bench/wider/WIDER_val.zip',
+ url: `${WIDER}/WIDER_val.zip`,
+ sha256: 'f9efbd09f28c5d2d884be8c0eaef3967158c866a593fc36ab0413e4b2a58a17a',
+ },
+]
+const PORTRAITS: { dataset: string; count: number }[] = [
+ { dataset: 'tonyassi/celebrity-1000', count: 50 },
+ { dataset: 'logasja/lfw', count: 30 },
+]
+const WIDER_EVAL_EVERY = 10
+
+interface GtFace {
+ box: [number, number, number, number]
+}
+interface GtImage {
+ file: string
+ width: number
+ height: number
+ faces: GtFace[]
+}
+
+interface DetectorSpec {
+ name: string
+ file: string
+ /** fixed: production's 640x640 letterbox. native: frame aspect at min(1, 640/long), stride-padded. */
+ 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' },
+ // 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 STRIDE = 32
+const SCORE_MIN = numFromEnv('YUNET_SCORE', 0.7, 0.05, 0.95)
+const NMS_IOU = 0.3
+const PAD = 0.25
+const COVERED = 0.9
+
+async function getBuf(url: string): Promise<Buffer> {
+ for (let i = 0; ; i++) {
+ try {
+ const res = await fetch(url, { signal: AbortSignal.timeout(300000), headers: { 'user-agent': UA } })
+ if (!res.ok) {
+ throw new Error(`HTTP ${res.status}`)
+ }
+ return Buffer.from(await res.arrayBuffer())
+ } catch (e) {
+ if (i >= 2) {
+ throw e
+ }
+ }
+ }
+}
+
+const sha256 = (buf: Buffer): string => createHash('sha256').update(buf).digest('hex')
+
+async function setup(): Promise<void> {
+ for (const d of DOWNLOADS) {
+ const path = join(ROOT, d.file)
+ if (existsSync(path) && sha256(readFileSync(path)) === d.sha256) {
+ continue
+ }
+ await mkdir(join(path, '..'), { recursive: true })
+ const buf = await getBuf(d.url)
+ if (sha256(buf) !== d.sha256) {
+ throw new Error(`${d.file}: sha256 does not match the pin`)
+ }
+ await writeFile(path, buf)
+ console.log(` ${d.file} (${(buf.length / 1e6).toFixed(1)} MB)`)
+ }
+ const wider = join(DATA, 'wider')
+ if (!existsSync(join(wider, 'WIDER_val'))) {
+ execFileSync('unzip', ['-q', '-o', 'wider_face_split.zip'], { cwd: wider })
+ execFileSync('unzip', ['-q', '-o', 'WIDER_val.zip'], { cwd: wider })
+ }
+ await writeWiderSubset()
+ await downloadPortraits()
+ await writeComposites()
+}
+
+/** Every WIDER_EVAL_EVERY-th val image for the eval, and the ones halfway between for calibration. */
+async function writeWiderSubset(): Promise<void> {
+ const lines = (await readFile(join(DATA, 'wider/wider_face_split/wider_face_val_bbx_gt.txt'), 'utf8')).split('\n')
+ const images: { file: string; faces: GtFace[] }[] = []
+ for (let i = 0; i < lines.length && lines[i].trim(); ) {
+ const file = lines[i].trim()
+ const count = Number(lines[i + 1])
+ const faces: GtFace[] = []
+ for (let k = 0; k < Math.max(1, count); k++) {
+ const [x, y, w, h, , , , invalid] = lines[i + 2 + k].trim().split(/\s+/).map(Number)
+ if (count > 0 && !invalid && w > 0 && h > 0) {
+ faces.push({ box: [x, y, x + w, y + h] })
+ }
+ }
+ images.push({ file, faces })
+ i += 2 + Math.max(1, count)
+ }
+ for (const [set, offset] of [
+ ['wider', 0],
+ ['wider-calibration', WIDER_EVAL_EVERY / 2],
+ ] as const) {
+ const picked: GtImage[] = []
+ for (const [idx, im] of images.entries()) {
+ if (idx % WIDER_EVAL_EVERY !== offset) {
+ continue
+ }
+ const path = join(DATA, 'wider/WIDER_val/images', im.file)
+ const { width, height } = await sharp(path).metadata()
+ picked.push({ file: `wider/WIDER_val/images/${im.file}`, width: width!, height: height!, faces: im.faces })
+ }
+ await writeFile(join(DATA, `${set}.json`), JSON.stringify(picked))
+ console.log(` ${set}: ${picked.length} images, ${picked.reduce((n, p) => n + p.faces.length, 0)} faces`)
+ }
+}
+
+async function downloadPortraits(): Promise<void> {
+ const dir = join(DATA, 'portraits')
+ if (existsSync(dir) && (await readdir(dir)).length >= 60) {
+ return
+ }
+ await mkdir(dir, { recursive: true })
+ for (const p of PORTRAITS) {
+ const splits = JSON.parse(
+ (
+ await getBuf(`https://datasets-server.huggingface.co/splits?dataset=${encodeURIComponent(p.dataset)}`)
+ ).toString()
+ )
+ const split = splits.splits[0]
+ const page = JSON.parse(
+ (
+ await getBuf(
+ `https://datasets-server.huggingface.co/rows?dataset=${encodeURIComponent(p.dataset)}&config=${split.config}&split=${split.split}&offset=0&length=${p.count}`
+ )
+ ).toString()
+ )
+ for (const [i, r] of page.rows.entries()) {
+ const image = Object.values(r.row as Record<string, unknown>).find(
+ (v): v is { src: string } => typeof v === 'object' && v !== null && 'src' in v
+ )
+ if (image) {
+ await writeFile(
+ join(dir, `${p.dataset.replace(/\W+/g, '_')}_${i}.jpg`),
+ await sharp(await getBuf(image.src))
+ .jpeg()
+ .toBuffer()
+ )
+ }
+ }
+ }
+ console.log(` portraits: ${(await readdir(dir)).length}`)
+}
+
+const COMPOSITE_FRAMES = [
+ { name: 'desktop', width: 1920, height: 1080 },
+ { name: 'laptop', width: 1280, height: 720 },
+ { name: 'mobile', width: 1170, height: 2532 },
+ { name: 'profile', width: 800, height: 800 },
+ { name: 'thumbnail', width: 480, height: 270 },
+ { name: 'ad', width: 300, height: 250 },
+ { name: 'avatar', width: 400, height: 400 },
+ { name: 'story', width: 320, height: 480 },
+]
+
+/** Portraits pasted into web-shaped frames with face sizes swept from 12px to most of the frame. */
+async function writeComposites(): Promise<void> {
+ const prod = await loadYunet(join(ROOT, 'models/yunet.onnx'))
+ const dir = join(DATA, 'composites')
+ await mkdir(dir, { recursive: true })
+ const portraits: { buf: Buffer; face: [number, number, number, number]; width: number; height: number }[] = []
+ for (const f of (await readdir(join(DATA, 'portraits'))).sort()) {
+ const buf = await readFile(join(DATA, 'portraits', f))
+ const src = await decodeSrc(buf, await probeDims(buf))
+ const found = await detectFacesYunet(prod, src, src.W, src.H, { scoreMin: 0.9 })
+ if (found.length !== 1) {
+ continue
+ }
+ const b = found[0]
+ // Undo the detector's PAD so the stored box is the face itself.
+ const w = b.width / (1 + 2 * PAD)
+ const h = b.height / (1 + 2 * PAD)
+ const cx = b.left + b.width / 2
+ const cy = b.top + b.height / 2
+ portraits.push({ buf, face: [cx - w / 2, cy - h / 2, cx + w / 2, cy + h / 2], width: src.W, height: src.H })
+ }
+ for (const [set, seeds] of [
+ ['composites', [0, 1, 2, 3, 4, 5, 6, 7]],
+ ['composites-calibration', [100, 101]],
+ ] as const) {
+ const images: GtImage[] = []
+ for (const frame of COMPOSITE_FRAMES) {
+ for (const seed of seeds) {
+ const random = mulberry32(seed * 131 + frame.width)
+ // Small frames get fewer, larger cells so they also carry faces big enough to stay
+ // readable in their stored image; otherwise nothing there tests the no-upscale path.
+ const small = Math.min(frame.width, frame.height) < 600
+ const cols = small ? (frame.width > frame.height ? 2 : 1) : 3
+ const rows = small ? (frame.width > frame.height ? 1 : 2) : frame.height > frame.width ? 4 : 2
+ const cellW = Math.floor(frame.width / cols)
+ const cellH = Math.floor(frame.height / rows)
+ const layers: OverlayOptions[] = []
+ const faces: GtFace[] = []
+ for (let r = 0; r < rows; r++) {
+ for (let c = 0; c < cols; c++) {
+ const p = portraits[Math.floor(random() * portraits.length)]
+ const faceW = p.face[2] - p.face[0]
+ const maxFace = Math.min(cellW, cellH) * (small ? 0.9 : 0.55)
+ const minFace = small ? 24 : 12
+ const target = Math.exp(Math.log(minFace) + random() * (Math.log(maxFace) - Math.log(minFace)))
+ const scale = target / faceW
+ const pw = Math.max(1, Math.round(p.width * scale))
+ const ph = Math.max(1, Math.round(p.height * scale))
+ const cropW = Math.min(pw, cellW)
+ const cropH = Math.min(ph, cellH)
+ const fx0 = p.face[0] * scale
+ const fy0 = p.face[1] * scale
+ const cropLeft = Math.max(0, Math.min(pw - cropW, Math.round(fx0 + target / 2 - cropW / 2)))
+ const cropTop = Math.max(
+ 0,
+ Math.min(ph - cropH, Math.round(fy0 + ((p.face[3] - p.face[1]) * scale) / 2 - cropH / 2))
+ )
+ const piece = await sharp(p.buf)
+ .resize(pw, ph, { fit: 'fill' })
+ .extract({ left: cropLeft, top: cropTop, width: cropW, height: cropH })
+ .toBuffer()
+ const left = c * cellW
+ const top = r * cellH
+ layers.push({ input: piece, left, top })
+ const renderedScaleX = pw / p.width
+ const renderedScaleY = ph / p.height
+ faces.push({
+ box: [
+ Math.round(left + p.face[0] * renderedScaleX - cropLeft),
+ Math.round(top + p.face[1] * renderedScaleY - cropTop),
+ Math.round(left + p.face[2] * renderedScaleX - cropLeft),
+ Math.round(top + p.face[3] * renderedScaleY - cropTop),
+ ],
+ })
+ }
+ }
+ const file = `composites/${set}_${frame.name}_${seed}.png`
+ await sharp({
+ create: { width: frame.width, height: frame.height, channels: 3, background: '#f3f4f6' },
+ })
+ .composite(layers)
+ .png()
+ .toFile(join(DATA, file))
+ images.push({ file, width: frame.width, height: frame.height, faces })
+ }
+ }
+ await writeFile(join(DATA, `${set}.json`), JSON.stringify(images))
+ console.log(` ${set}: ${images.length} images, ${images.reduce((n, im) => n + im.faces.length, 0)} faces`)
+ }
+ await prod.session.release()
+}
+
+interface Loaded {
+ spec: DetectorSpec
+ model: YunetModel
+}
+
+const upToStride = (n: number): number => Math.max(STRIDE, Math.ceil(n / STRIDE) * STRIDE)
+
+function iou(a: Box, b: Box): number {
+ const x1 = Math.max(a.left, b.left)
+ const y1 = Math.max(a.top, b.top)
+ const x2 = Math.min(a.left + a.width, b.left + b.width)
+ const y2 = Math.min(a.top + a.height, b.top + b.height)
+ const inter = Math.max(0, x2 - x1) * Math.max(0, y2 - y1)
+ return inter === 0 ? 0 : inter / (a.width * a.height + b.width * b.height - inter)
+}
+
+// --dump-calibration builds its tensors here too, so that the int8 builds calibrate on the inputs the native variants see.
+async function nativeInput(
+ src: Src,
+ win: Box
+): 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 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 whole = win.width === src.W && win.height === src.H
+ const { data } = await (whole ? srcSharp(src) : srcSharp(src).extract(win))
+ .resize(dw, dh, { fit: 'fill' })
+ .extend({ top: 0, left: 0, right: cw - dw, bottom: ch - dh, background: '#000' })
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ const chw = new Float32Array(3 * cw * ch)
+ const plane = cw * ch
+ for (let i = 0, p = 0; i < data.length; i += 3, p++) {
+ chw[p] = data[i + 2]
+ chw[plane + p] = data[i + 1]
+ chw[2 * plane + p] = data[i]
+ }
+ 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[]> {
+ 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 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
+ for (const s of [8, 16, 32]) {
+ 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 = cw / s
+ const fh = ch / s
+ if (cls.length !== fw * fh) {
+ throw new Error(`cls_${s} has ${cls.length} cells for a ${fw}x${fh} grid`)
+ }
+ for (let r = 0; r < fh; r++) {
+ for (let c = 0; c < fw; c++) {
+ const i = r * fw + c
+ const score = Math.sqrt(Math.max(0, cls[i]) * Math.max(0, obj[i]))
+ if (score < SCORE_MIN) {
+ continue
+ }
+ const cx = (c + bbox[i * 4]) * s
+ const cy = (r + bbox[i * 4 + 1]) * s
+ const bw = Math.exp(bbox[i * 4 + 2]) * s
+ const bh = Math.exp(bbox[i * 4 + 3]) * s
+ const left = Math.max(0, Math.round((cx - bw / 2 - bw * PAD) * sx) + win.left)
+ const top = Math.max(0, Math.round((cy - bh / 2 - bh * PAD) * sy) + win.top)
+ const right = Math.min(W, Math.round((cx + bw / 2 + bw * PAD) * sx) + win.left)
+ const bottom = Math.min(H, Math.round((cy + bh / 2 + bh * PAD) * sy) + win.top)
+ if (right - left >= 2 && bottom - top >= 2) {
+ cand.push({ b: { left, top, width: right - left, height: bottom - top }, s: score })
+ }
+ }
+ }
+ }
+ }
+ cand.sort((a, b) => b.s - a.s)
+ const keep: Box[] = []
+ for (const { b } of cand) {
+ if (!keep.some((k) => iou(k, b) > NMS_IOU)) {
+ keep.push(b)
+ }
+ }
+ return keep
+}
+
+/** 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)
+}
+
+interface FaceResult {
+ set: string
+ detector: string
+ faceAtModel: number
+ readable: boolean
+ coverage: number
+}
+interface RunResult {
+ set: string
+ image: string
+ detector: string
+ ms: number
+ boxes: number
+ filledFraction: number
+ sourcePixels: number
+}
+
+function arg(name: string): string | undefined {
+ const i = process.argv.indexOf(`--${name}`)
+ return i >= 0 ? process.argv[i + 1] : undefined
+}
+
+async function loadSet(set: string, limit: number): Promise<{ set: string; gt: GtImage }[]> {
+ const path = join(DATA, `${set}.json`)
+ if (!existsSync(path)) {
+ console.warn(` skipping ${set}: run --setup first`)
+ return []
+ }
+ return (JSON.parse(await readFile(path, 'utf8')) as GtImage[]).slice(0, limit).map((gt) => ({ set, gt }))
+}
+
+async function loadDetectors(names: string[] | undefined): Promise<Loaded[]> {
+ const specs = DETECTORS.filter((d) => (names ? names.includes(d.name) : true)).filter((d) => {
+ const ok = existsSync(join(ROOT, d.file))
+ if (!ok) {
+ console.warn(` skipping ${d.name}: no ${d.file}`)
+ }
+ return ok
+ })
+ return Promise.all(specs.map(async (spec) => ({ spec, model: await loadYunet(join(ROOT, spec.file)) })))
+}
+
+async function evaluate(): Promise<void> {
+ const limit = Number(arg('limit') ?? 1e9)
+ const sets = arg('sets')?.split(',') ?? ['wider', 'composites']
+ const images = (await Promise.all(sets.map((s) => loadSet(s, limit)))).flat()
+ const detectors = await loadDetectors(arg('detectors')?.split(','))
+ console.log(`${images.length} images, detectors: ${detectors.map((d) => d.spec.name).join(', ')}\n`)
+ const limits = limitsFromEnv()
+ const faces: FaceResult[] = []
+ const runs: RunResult[] = []
+ let warmed = false
+ for (const [n, { set, gt }] of images.entries()) {
+ const buf = await readFile(join(DATA, gt.file))
+ const plan = planScales({ width: gt.width, height: gt.height }, limits)
+ const src = await decodeSrc(buf, plan.frame)
+ const fx = src.W / gt.width
+ const fy = src.H / gt.height
+ 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))
+ }
+ 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 ms = performance.now() - t0
+ let filled = 0
+ const mask = new Uint8Array(src.W * src.H)
+ for (const b of boxes) {
+ for (let y = b.top; y < b.top + b.height; y++) {
+ mask.fill(1, y * src.W + b.left, y * src.W + b.left + b.width)
+ }
+ }
+ for (const v of mask) {
+ filled += v
+ }
+ runs.push({
+ set,
+ image: gt.file,
+ detector: d.spec.name,
+ ms,
+ boxes: boxes.length,
+ filledFraction: filled / (src.W * src.H),
+ sourcePixels: gt.width * gt.height,
+ })
+ const atModel = modelScale(d.spec, src.W, src.H)
+ for (const f of gt.faces) {
+ const [x0, y0, x1, y1] = f.box
+ const side = Math.max(x1 - x0, y1 - y0)
+ faces.push({
+ set,
+ detector: d.spec.name,
+ faceAtModel: side * fx * atModel,
+ readable: side * storedOverSource >= FACE_FLOOR.readableAt,
+ coverage: coverage(boxes, [
+ Math.floor(x0 * fx),
+ Math.floor(y0 * fy),
+ Math.ceil(x1 * fx),
+ Math.ceil(y1 * fy),
+ ]),
+ })
+ }
+ }
+ if ((n + 1) % 50 === 0) {
+ console.error(` ${n + 1}/${images.length}`)
+ }
+ }
+ const label = arg('label') ?? 'face-bench'
+ await mkdir(join(ROOT, 'out/face-bench'), { recursive: true })
+ await writeFile(join(ROOT, `out/face-bench/${label}.json`), JSON.stringify({ faces, runs }))
+ report(faces, runs, sets)
+}
+
+function report(faces: FaceResult[], runs: RunResult[], sets: string[]): void {
+ const detectors = [...new Set(runs.map((r) => r.detector))]
+ const mean = (xs: number[]): number => xs.reduce((a, b) => a + b, 0) / Math.max(1, xs.length)
+ const pct = (n: number, d: number): string => (d ? `${((100 * n) / d).toFixed(1)}%` : '-')
+ console.log(
+ ` ${'detector'.padEnd(24)}${'ms/img'.padStart(8)}${'readable'.padStart(10)}${'visible'.padStart(9)}${'all faces'.padStart(11)}${'filled'.padStart(8)}`
+ )
+ for (const d of detectors) {
+ const r = runs.filter((x) => x.detector === d)
+ const f = faces.filter((x) => x.detector === d)
+ const readable = f.filter((x) => x.readable)
+ console.log(
+ ` ${d.padEnd(24)}${mean(r.map((x) => x.ms))
+ .toFixed(1)
+ .padStart(8)}` +
+ `${pct(readable.filter((x) => x.coverage >= COVERED).length, readable.length).padStart(10)}` +
+ `${String(readable.filter((x) => x.coverage < 0.1).length).padStart(9)}` +
+ `${pct(f.filter((x) => x.coverage >= COVERED).length, f.length).padStart(11)}` +
+ `${pct(mean(r.map((x) => x.filledFraction)), 1).padStart(8)}`
+ )
+ }
+ for (const set of sets) {
+ const n = faces.filter((x) => x.detector === detectors[0] && x.set === set)
+ console.log(` ${set}: ${n.length} faces, ${n.filter((x) => x.readable).length} readable in the stored image`)
+ }
+ console.log('\n recall by face size at the model input (px), all sets')
+ const edges = [0, 8, 12, 16, 24, 32, 48, 64, 96, 1e9]
+ console.log(
+ ` ${'detector'.padEnd(24)}${edges
+ .slice(0, -1)
+ .map((lo, i) => `${lo}-${edges[i + 1] === 1e9 ? '' : edges[i + 1]}`.padStart(8))
+ .join('')}`
+ )
+ for (const d of detectors) {
+ const cells = edges.slice(0, -1).map((lo, i) => {
+ const b = faces.filter((x) => x.detector === d && x.faceAtModel >= lo && x.faceAtModel < edges[i + 1])
+ return (b.length >= 20 ? pct(b.filter((x) => x.coverage >= COVERED).length, b.length) : '.').padStart(8)
+ })
+ console.log(` ${d.padEnd(24)}${cells.join('')}`)
+ }
+}
+
+async function dumpCalibration(): Promise<void> {
+ const dir = join(ROOT, 'out/face-calibration')
+ await mkdir(dir, { recursive: true })
+ const images = [...(await loadSet('wider-calibration', 60)), ...(await loadSet('composites-calibration', 1e9))]
+ const limits = limitsFromEnv()
+ const index: { file: string; shape: number[] }[] = []
+ 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 file = `face_${n}.bin`
+ await writeFile(join(dir, file), Buffer.from(chw.buffer))
+ index.push({ file, shape: [1, 3, ch, cw] })
+ }
+ await writeFile(join(dir, 'index.json'), JSON.stringify(index))
+ console.log(`${index.length} tensors in ${dir}`)
+}
+
+;(process.argv.includes('--setup')
+ ? setup()
+ : process.argv.includes('--dump-calibration')
+ ? dumpCalibration()
+ : evaluate()
+).catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-bench.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-bench.ts
new file mode 100644
index 000000000000..2645d9c76813
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-bench.ts
@@ -0,0 +1,791 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Text detector comparison: what each candidate costs, and which words its redaction covers, on the
+ * frames the production plan hands the text stage.
+ *
+ * Setup, once:
+ * npm run setup # the production model, which the ppocrv3 entries use
+ * tsx dev/text-det-setup.ts # candidate models + labelled public images
+ * tsx dev/text-det-corpus.ts # synthetic web images with exact boxes
+ * tsx dev/text-det-corpus.ts --calibration # a disjoint synthetic set, for int8 calibration only
+ * dev/text-det-dynamic-hw.py # each docTR model, see its docstring
+ * tsx dev/text-det-bench.ts --dump-calibration "<detector>", then dev/text-det-quantize.py # int8
+ *
+ * Runs:
+ * ORT_THREADS=1 tsx dev/text-det-bench.ts [--detectors a,b] [--sets a,b] [--points a,b] [--limit N] [--label name] [--no-kleidiai]
+ * ORT_THREADS=1 tsx dev/text-det-bench.ts --latency [--reps N]
+ *
+ * ORT_THREADS=1 matches the default in src/cores.ts, which runs one worker per core and gives each
+ * worker one intra-op thread.
+ *
+ * Every candidate runs through the production pre-processing (resize, grey stride padding, the
+ * conditional sharpen), the production post-processing (threshold, horizontal dilation, connected
+ * components, padding) and the production fill margins. Only the channel order, normalization and
+ * thresholds follow each model's own documentation. The baseline entry is checked box for box against
+ * src/dbnet.ts on every image, so the harness cannot drift from what production does.
+ *
+ * A ground-truth word counts as redacted when the fills cover at least 90% of its box. Words are
+ * bucketed by their height at the model input, which is the unit the detection floor in src/floors.ts
+ * is stated in, so the sweep gives each candidate's floor on real images. "Readable" words are the
+ * ones whose ink in the stored image is at least as tall as TEXT_FLOOR.readableAt font px: those are
+ * the only words whose miss leaks anything.
+ *
+ * Operating points:
+ * prod the canvas src/scale-plan.ts gives the text detector
+ * fitted-global the smallest canvas that keeps the plan's rule, where every detector sees its
+ * subject at least the binding ratio (faces) times the safety factor larger than the
+ * stored image keeps it, for the stored size the plan chose; never above prod
+ * fitted the same, with text held only to its own floor ratio (TEXT_FLOOR)
+ * tN the frame scaled by N, for the recall-against-size sweep
+ *
+ * --latency repeats the prod and both fitted points per image and reports medians, once with ORT's
+ * KleidiAI kernels and once without. On an SME-capable Mac those kernels run fp32 convolutions on the
+ * matrix unit, which Graviton does not have, so the numbers without them are the closer proxy.
+ */
+import { existsSync } from 'node:fs'
+import { mkdir, readFile, writeFile } from 'node:fs/promises'
+import { join } from 'node:path'
+import * as ort from 'onnxruntime-node'
+
+import { detectTextDbnet, loadDbnet } from '../src/dbnet.ts'
+import { numFromEnv } from '../src/env.ts'
+import { TEXT_FLOOR, bindingRatio, requiredRatio } from '../src/floors.ts'
+import { type Box } from '../src/geometry.ts'
+import { type Dims, fitToCanvas, limitsFromEnv, planScales } from '../src/scale-plan.ts'
+import { type Src, decodeSrc, probeDims, srcSharp } from '../src/src-image.ts'
+import { type GtImage } from './text-det-setup.ts'
+
+const ROOT = new URL('..', import.meta.url).pathname
+
+interface DetectorSpec {
+ name: string
+ file: string
+ channelOrder: 'rgb' | 'bgr'
+ /** In the model's own channel order. */
+ mean: [number, number, number]
+ std: [number, number, number]
+ output: 'probability' | 'logits'
+ probThreshold: number
+ boxScoreMin: number
+}
+
+const IMAGENET = { mean: [0.485, 0.456, 0.406], std: [0.229, 0.224, 0.225] } as const
+const DOCTR = { mean: [0.798, 0.785, 0.772], std: [0.264, 0.2749, 0.287] } as const
+
+const PROD_PROB_THRESHOLD = numFromEnv('PROB_T', 0.3, 0.05, 0.9)
+const PROD_BOX_SCORE = numFromEnv('BOX_SCORE', 0.5, 0.05, 0.95)
+
+// PaddleOCR decodes with OpenCV, so its detectors were trained on BGR with the ImageNet statistics
+// applied in that order. Production feeds RGB, which the ppocrv3-bgr entry measures.
+const DETECTORS: DetectorSpec[] = [
+ {
+ name: 'ppocrv3 (prod)',
+ file: 'models/dbnet_det.onnx',
+ channelOrder: 'rgb',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: PROD_PROB_THRESHOLD,
+ boxScoreMin: PROD_BOX_SCORE,
+ },
+ {
+ name: 'ppocrv3-bgr',
+ file: 'models/dbnet_det.onnx',
+ channelOrder: 'bgr',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: PROD_PROB_THRESHOLD,
+ boxScoreMin: PROD_BOX_SCORE,
+ },
+ {
+ name: 'ppocrv3-int8',
+ file: 'models/candidates/ppocrv3_det_int8.onnx',
+ channelOrder: 'rgb',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: PROD_PROB_THRESHOLD,
+ boxScoreMin: PROD_BOX_SCORE,
+ },
+ {
+ name: 'ppocrv3-int8-conv',
+ file: 'models/candidates/ppocrv3_det_int8_conv.onnx',
+ channelOrder: 'rgb',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: PROD_PROB_THRESHOLD,
+ boxScoreMin: PROD_BOX_SCORE,
+ },
+ {
+ name: 'ppocrv4-mobile',
+ file: 'models/candidates/ppocrv4_mobile_det.onnx',
+ channelOrder: 'bgr',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: 0.3,
+ boxScoreMin: 0.6,
+ },
+ {
+ name: 'ppocrv5-mobile',
+ file: 'models/candidates/ppocrv5_mobile_det.onnx',
+ channelOrder: 'bgr',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: 0.3,
+ boxScoreMin: 0.6,
+ },
+ {
+ name: 'ppocrv6-tiny',
+ file: 'models/candidates/ppocrv6_tiny_det.onnx',
+ channelOrder: 'bgr',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: 0.2,
+ boxScoreMin: 0.4,
+ },
+ {
+ name: 'ppocrv6-tiny-int8',
+ file: 'models/candidates/ppocrv6_tiny_det_int8.onnx',
+ channelOrder: 'bgr',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: 0.2,
+ boxScoreMin: 0.4,
+ },
+ {
+ name: 'ppocrv6-small',
+ file: 'models/candidates/ppocrv6_small_det.onnx',
+ channelOrder: 'bgr',
+ ...copyStats(IMAGENET),
+ output: 'probability',
+ probThreshold: 0.2,
+ boxScoreMin: 0.45,
+ },
+ {
+ name: 'doctr-db-mbv3',
+ file: 'models/candidates/doctr_db_mobilenet_v3_large_dyn.onnx',
+ channelOrder: 'rgb',
+ ...copyStats(DOCTR),
+ output: 'logits',
+ probThreshold: 0.3,
+ boxScoreMin: 0.1,
+ },
+ {
+ name: 'doctr-db-mbv3-int8',
+ file: 'models/candidates/doctr_db_mobilenet_v3_large_int8_dyn.onnx',
+ channelOrder: 'rgb',
+ ...copyStats(DOCTR),
+ output: 'logits',
+ probThreshold: 0.3,
+ boxScoreMin: 0.1,
+ },
+ {
+ name: 'doctr-fast-tiny',
+ file: 'models/candidates/doctr_fast_tiny_dyn.onnx',
+ channelOrder: 'rgb',
+ ...copyStats(DOCTR),
+ output: 'logits',
+ probThreshold: 0.1,
+ boxScoreMin: 0.1,
+ },
+]
+
+function copyStats(stats: { mean: readonly number[]; std: readonly number[] }): Pick<DetectorSpec, 'mean' | 'std'> {
+ return { mean: [stats.mean[0], stats.mean[1], stats.mean[2]], std: [stats.std[0], stats.std[1], stats.std[2]] }
+}
+
+const MIN_AREA_PX = numFromEnv('MIN_AREA', 16, 1, 1024)
+const DILATE_X = numFromEnv('DILATE_X', 6, 0, 64)
+const PAD_X = numFromEnv('PAD_X', 0.25, 0, 2)
+const PAD_Y = numFromEnv('PAD_Y', 0.3, 0, 2)
+const DET_SHARPEN = numFromEnv('DET_SHARPEN', 1, 0, 10)
+const DET_SHARPEN_BELOW = numFromEnv('DET_SHARPEN_BELOW', 0.6, 0.05, 1)
+const TEXT_MARGIN_FRAC = numFromEnv('TEXT_MARGIN_FRAC', 0.25, 0, 2)
+const TEXT_MARGIN_BOTTOM_FRAC = numFromEnv('TEXT_MARGIN_BOTTOM_FRAC', 0.45, 0, 2)
+const TEXT_MARGIN_MIN = numFromEnv('TEXT_MARGIN_MIN', 4, 0, 64)
+
+const INK_PER_FONT_PX = 0.72
+const READABLE_INK_PX = TEXT_FLOOR.readableAt * INK_PER_FONT_PX
+const COVERED = 0.9
+const HEIGHT_BUCKETS = [0, 2, 3, 4, 5, 6, 7, 8, 10, 12, 16, 24, 48]
+const SWEEP_SCALES = [0.25, 0.35, 0.5, 0.7, 1]
+const SETS = ['synthetic', 'born-digital', 'funsd', 'cord']
+
+interface LoadedDetector {
+ spec: DetectorSpec
+ session: ort.InferenceSession
+ inputName: string
+ outputName: string
+}
+
+interface TextCanvas {
+ content: Dims
+ canvas: Dims
+}
+
+interface Detection {
+ boxes: Box[]
+ preMs: number
+ inferMs: number
+ postMs: number
+}
+
+async function loadDetector(spec: DetectorSpec, kleidiai: boolean): Promise<LoadedDetector> {
+ const session = await ort.InferenceSession.create(join(ROOT, spec.file), {
+ graphOptimizationLevel: 'all',
+ intraOpNumThreads: numFromEnv('ORT_THREADS', 1, 1, 32),
+ interOpNumThreads: 1,
+ executionMode: 'sequential',
+ enableCpuMemArena: false,
+ extra: kleidiai ? {} : { 'mlas.disable_kleidiai': '1' },
+ })
+ return { spec, session, inputName: session.inputNames[0], outputName: session.outputNames[0] }
+}
+
+/** A copy of src/dbnet.ts's preprocess. The baseline check fails when the two drift apart. */
+async function preprocess(
+ spec: DetectorSpec,
+ src: Src,
+ text: TextCanvas
+): Promise<{ data: Float32Array; rw: number; rh: number; sx: number; sy: number }> {
+ const { width: cw, height: ch } = text.content
+ const { width: rw, height: rh } = text.canvas
+ const totalRatio = Math.sqrt((cw * ch) / src.inputPixels)
+ const pipeline = srcSharp(src)
+ .resize(cw, ch, { fit: 'fill' })
+ .extend({ right: rw - cw, bottom: rh - ch, background: '#808080' })
+ const sharpened = DET_SHARPEN > 0 && totalRatio < DET_SHARPEN_BELOW
+ const { data } = await (sharpened ? pipeline.sharpen({ sigma: DET_SHARPEN }) : pipeline)
+ .raw()
+ .toBuffer({ resolveWithObject: true })
+ const chw = new Float32Array(3 * rw * rh)
+ const plane = rw * rh
+ const [m0, m1, m2] = spec.mean
+ const [s0, s1, s2] = spec.std
+ const first = spec.channelOrder === 'rgb' ? 0 : 2
+ const last = 2 - first
+ for (let i = 0, p = 0; i < data.length; i += 3, p++) {
+ chw[p] = (data[i + first] / 255 - m0) / s0
+ chw[plane + p] = (data[i + 1] / 255 - m1) / s1
+ chw[2 * plane + p] = (data[i + last] / 255 - m2) / s2
+ }
+ return { data: chw, rw, rh, sx: src.W / cw, sy: src.H / ch }
+}
+
+/** A copy of src/dbnet.ts's postprocess. The baseline check fails when the two drift apart. */
+function postprocess(
+ spec: DetectorSpec,
+ raw: Float32Array,
+ rw: number,
+ rh: number,
+ sx: number,
+ sy: number,
+ W: number,
+ H: number
+): Box[] {
+ const logits = spec.output === 'logits'
+ const rawThreshold = logits ? Math.log(spec.probThreshold / (1 - spec.probThreshold)) : spec.probThreshold
+ const prob = (v: number): number => (logits ? 1 / (1 + Math.exp(-v)) : v)
+ const bin = new Uint8Array(rw * rh)
+ for (let i = 0; i < raw.length; i++) {
+ bin[i] = raw[i] >= rawThreshold ? 1 : 0
+ }
+ const dil = dilateHoriz(bin, rw, rh, DILATE_X)
+ const seen = new Uint8Array(rw * rh)
+ const stack: number[] = []
+ const boxes: Box[] = []
+ for (let start = 0; start < dil.length; start++) {
+ if (!dil[start] || seen[start]) {
+ continue
+ }
+ let minX = rw
+ let minY = rh
+ let maxX = 0
+ let maxY = 0
+ let coreSum = 0
+ let coreCnt = 0
+ stack.push(start)
+ seen[start] = 1
+ while (stack.length) {
+ const idx = stack.pop()!
+ const x = idx % rw
+ const y = (idx - x) / rw
+ if (bin[idx]) {
+ coreSum += prob(raw[idx])
+ coreCnt++
+ }
+ minX = Math.min(minX, x)
+ maxX = Math.max(maxX, x)
+ minY = Math.min(minY, y)
+ maxY = Math.max(maxY, y)
+ if (x > 0 && dil[idx - 1] && !seen[idx - 1]) {
+ seen[idx - 1] = 1
+ stack.push(idx - 1)
+ }
+ if (x < rw - 1 && dil[idx + 1] && !seen[idx + 1]) {
+ seen[idx + 1] = 1
+ stack.push(idx + 1)
+ }
+ if (y > 0 && dil[idx - rw] && !seen[idx - rw]) {
+ seen[idx - rw] = 1
+ stack.push(idx - rw)
+ }
+ if (y < rh - 1 && dil[idx + rw] && !seen[idx + rw]) {
+ seen[idx + rw] = 1
+ stack.push(idx + rw)
+ }
+ }
+ if (coreCnt < MIN_AREA_PX || coreSum / coreCnt < spec.boxScoreMin) {
+ continue
+ }
+ const ex = (maxX - minX + 1) * PAD_X
+ const ey = (maxY - minY + 1) * PAD_Y
+ const left = Math.max(0, Math.round((minX - ex) * sx))
+ const top = Math.max(0, Math.round((minY - ey) * sy))
+ const right = Math.min(W, Math.round((maxX + 1 + ex) * sx))
+ const bottom = Math.min(H, Math.round((maxY + 1 + ey) * sy))
+ if (right - left >= 2 && bottom - top >= 2) {
+ boxes.push({ left, top, width: right - left, height: bottom - top })
+ }
+ }
+ return boxes
+}
+
+function dilateHoriz(bin: Uint8Array, rw: number, rh: number, k: number): Uint8Array {
+ if (k <= 0) {
+ return bin
+ }
+ const out = new Uint8Array(rw * rh)
+ const prefix = new Int32Array(rw + 1)
+ for (let y = 0; y < rh; y++) {
+ const row = y * rw
+ for (let x = 0; x < rw; x++) {
+ prefix[x + 1] = prefix[x] + bin[row + x]
+ }
+ for (let x = 0; x < rw; x++) {
+ const lo = Math.max(0, x - k)
+ const hi = Math.min(rw - 1, x + k)
+ out[row + x] = prefix[hi + 1] - prefix[lo] > 0 ? 1 : 0
+ }
+ }
+ return out
+}
+
+async function detect(det: LoadedDetector, src: Src, text: TextCanvas): Promise<Detection> {
+ const t0 = performance.now()
+ const { data, rw, rh, sx, sy } = await preprocess(det.spec, src, text)
+ const t1 = performance.now()
+ const out = await det.session.run({ [det.inputName]: new ort.Tensor('float32', data, [1, 3, rh, rw]) })
+ const t2 = performance.now()
+ const output = out[det.outputName]
+ if (output.dims[2] !== rh || output.dims[3] !== rw) {
+ throw new Error(`${det.spec.name}: output ${output.dims.join('x')} for input ${rh}x${rw}`)
+ }
+ const boxes = postprocess(det.spec, output.data as Float32Array, rw, rh, sx, sy, src.W, src.H)
+ return { boxes, preMs: t1 - t0, inferMs: t2 - t1, postMs: performance.now() - t2 }
+}
+
+/** A copy of the text margins in src/scrub.ts, which no check compares against. */
+function fillBox(t: Box, W: number, H: number): Box | null {
+ const mg = Math.round(Math.max(TEXT_MARGIN_MIN, t.height * TEXT_MARGIN_FRAC))
+ const mb = Math.round(Math.max(TEXT_MARGIN_MIN, t.height * TEXT_MARGIN_BOTTOM_FRAC))
+ const left = Math.max(0, Math.min(W - 1, t.left - mg))
+ const top = Math.max(0, Math.min(H - 1, t.top - mg))
+ const width = Math.max(1, Math.min(W - left, t.width + 2 * mg))
+ const height = Math.max(1, Math.min(H - top, t.height + mg + mb))
+ return width < 2 || height < 2 ? null : { left, top, width, height }
+}
+
+function coverageTable(boxes: Box[], W: number, H: number): { table: Int32Array; filled: number } {
+ const mask = new Uint8Array(W * H)
+ for (const b of boxes) {
+ for (let y = b.top; y < b.top + b.height; y++) {
+ mask.fill(1, y * W + b.left, y * W + b.left + b.width)
+ }
+ }
+ const table = new Int32Array((W + 1) * (H + 1))
+ let filled = 0
+ for (let y = 0; y < H; y++) {
+ let rowSum = 0
+ for (let x = 0; x < W; x++) {
+ rowSum += mask[y * W + x]
+ table[(y + 1) * (W + 1) + x + 1] = table[y * (W + 1) + x + 1] + rowSum
+ }
+ filled += rowSum
+ }
+ return { table, filled }
+}
+
+function covered(table: Int32Array, W: number, x0: number, y0: number, x1: number, y1: number): number {
+ const at = (x: number, y: number): number => table[y * (W + 1) + x]
+ return at(x1, y1) - at(x0, y1) - at(x1, y0) + at(x0, y0)
+}
+
+interface WordResult {
+ set: string
+ detector: string
+ point: string
+ heightAtModel: number
+ readable: boolean
+ coverage: number
+}
+
+interface RunResult {
+ set: string
+ image: string
+ detector: string
+ point: string
+ canvasPixels: number
+ preMs: number
+ inferMs: number
+ postMs: number
+ boxes: number
+ fillFraction: number
+}
+
+interface ImagePlan {
+ set: string
+ gt: GtImage
+ src: Src
+ points: Map<string, TextCanvas>
+ storedOverSource: { x: number; y: number }
+ contentOverSource: Map<string, number>
+ prodText: TextCanvas
+}
+
+async function planImage(set: string, gt: GtImage, wanted: string[]): Promise<ImagePlan> {
+ const buf = await readFile(join(ROOT, 'test-data/text-det', set, gt.file))
+ const limits = limitsFromEnv()
+ const source = await probeDims(buf)
+ const plan = planScales(source, limits)
+ const src = await decodeSrc(buf, plan.frame)
+ const frame = plan.frame
+ const framePixels = frame.width * frame.height
+ // The ratio rule is per axis in pixels: text h px tall in the frame is h * content/frame at the model
+ // and h * stored/frame in the artifact, so the content needs ratio * stored on each axis and no more.
+ const fittedTo = (ratio: number): TextCanvas => {
+ const width = Math.min(plan.text.content.width, Math.ceil(ratio * plan.stored.width))
+ const height = Math.min(plan.text.content.height, Math.ceil(ratio * plan.stored.height))
+ return {
+ content: { width, height },
+ canvas: { width: upToStride(width, limits.stride), height: upToStride(height, limits.stride) },
+ }
+ }
+ const points = new Map<string, TextCanvas>()
+ const add = (name: string, text: TextCanvas): void => {
+ if (wanted.includes(name) || wanted.includes(name.replace(/\d.*$/, 'N'))) {
+ points.set(name, text)
+ }
+ }
+ add('prod', plan.text)
+ add('fitted-global', fittedTo(bindingRatio() * limits.safetyFactor))
+ add('fitted', fittedTo(requiredRatio(TEXT_FLOOR) * limits.safetyFactor))
+ for (const s of SWEEP_SCALES) {
+ add(`t${s}`, fitToCanvas(frame, Math.max(1, s ** 2 * framePixels), limits.stride))
+ }
+ const contentOverSource = new Map([...points].map(([name, text]) => [name, text.content.height / source.height]))
+ return {
+ set,
+ gt,
+ src,
+ points,
+ storedOverSource: { x: plan.stored.width / source.width, y: plan.stored.height / source.height },
+ contentOverSource,
+ prodText: plan.text,
+ }
+}
+
+const upToStride = (n: number, stride: number): number => Math.max(stride, Math.ceil(n / stride) * stride)
+
+function scoreWords(
+ image: ImagePlan,
+ detector: string,
+ point: string,
+ fills: Box[]
+): { words: WordResult[]; filled: number } {
+ const { W, H } = image.src
+ const { table, filled } = coverageTable(fills, W, H)
+ const fx = W / image.gt.width
+ const fy = H / image.gt.height
+ const words: WordResult[] = []
+ for (const w of image.gt.words) {
+ const [bx0, by0, bx1, by1] = w.box
+ const shrinkX = Math.min(image.gt.tolerancePx, (bx1 - bx0) / 3)
+ const shrinkY = Math.min(image.gt.tolerancePx, (by1 - by0) / 3)
+ const x0 = Math.max(0, Math.floor((bx0 + shrinkX) * fx))
+ const y0 = Math.max(0, Math.floor((by0 + shrinkY) * fy))
+ const x1 = Math.min(W, Math.ceil((bx1 - shrinkX) * fx))
+ const y1 = Math.min(H, Math.ceil((by1 - shrinkY) * fy))
+ if (x1 <= x0 || y1 <= y0) {
+ continue
+ }
+ const height = by1 - by0
+ words.push({
+ set: image.set,
+ detector,
+ point,
+ heightAtModel: height * image.contentOverSource.get(point)!,
+ readable: height * image.storedOverSource.y >= READABLE_INK_PX,
+ coverage: covered(table, W, x0, y0, x1, y1) / ((x1 - x0) * (y1 - y0)),
+ })
+ }
+ return { words, filled }
+}
+
+async function loadSets(sets: string[], limit: number): Promise<{ set: string; gt: GtImage }[]> {
+ const out: { set: string; gt: GtImage }[] = []
+ for (const set of sets) {
+ const path = join(ROOT, 'test-data/text-det', set, 'gt.json')
+ if (!existsSync(path)) {
+ console.warn(` skipping ${set}: no ${path} (run dev/text-det-setup.ts / dev/text-det-corpus.ts)`)
+ continue
+ }
+ const images = JSON.parse(await readFile(path, 'utf8')) as GtImage[]
+ out.push(...images.slice(0, limit).map((gt) => ({ set, gt })))
+ }
+ if (out.length === 0) {
+ throw new Error(`no images in ${sets.join(', ')}: run the setup commands at the top of this file first`)
+ }
+ return out
+}
+
+function arg(name: string): string | undefined {
+ const i = process.argv.indexOf(`--${name}`)
+ return i >= 0 ? process.argv[i + 1] : undefined
+}
+
+const pct = (n: number, d: number): string => (d ? `${((100 * n) / d).toFixed(1)}%` : '-')
+const mean = (xs: number[]): number => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0)
+const median = (xs: number[]): number => {
+ const s = [...xs].sort((a, b) => a - b)
+ return s.length ? s[Math.floor(s.length / 2)] : 0
+}
+
+function availableDetectors(names: string[] | undefined): DetectorSpec[] {
+ return DETECTORS.filter((d) => (names ? names.includes(d.name) : true)).filter((d) => {
+ const ok = existsSync(join(ROOT, d.file))
+ if (!ok) {
+ console.warn(` skipping ${d.name}: no ${d.file}`)
+ }
+ return ok
+ })
+}
+
+async function quality(): Promise<void> {
+ const specs = availableDetectors(arg('detectors')?.split(','))
+ const sets = arg('sets')?.split(',') ?? SETS
+ const points = arg('points')?.split(',') ?? ['prod', 'fitted-global', 'fitted', 'tN']
+ const limit = Number(arg('limit') ?? 1e9)
+ const images = await loadSets(sets, limit)
+ const detectors = await Promise.all(specs.map((s) => loadDetector(s, !process.argv.includes('--no-kleidiai'))))
+ const baselineDetector = detectors.find((d) => d.spec.name === 'ppocrv3 (prod)')
+ const baseline = baselineDetector
+ ? { detector: baselineDetector, prodModel: await loadDbnet(join(ROOT, baselineDetector.spec.file)) }
+ : null
+ console.log(`${images.length} images, detectors: ${specs.map((s) => s.name).join(', ')}\n`)
+
+ const words: WordResult[] = []
+ const runs: RunResult[] = []
+ let mismatches = 0
+ let warmed = false
+ for (const [n, { set, gt }] of images.entries()) {
+ const image = await planImage(set, gt, points)
+ if (!warmed) {
+ for (const det of detectors) {
+ await detect(det, image.src, image.prodText)
+ }
+ warmed = true
+ }
+ if (baseline) {
+ const ours = await detect(baseline.detector, image.src, image.prodText)
+ const theirs = await detectTextDbnet(baseline.prodModel, image.src, image.prodText)
+ if (JSON.stringify(ours.boxes) !== JSON.stringify(theirs)) {
+ mismatches++
+ }
+ }
+ for (const det of detectors) {
+ for (const [point, text] of image.points) {
+ const d = await detect(det, image.src, text)
+ const fills = d.boxes
+ .map((b) => fillBox(b, image.src.W, image.src.H))
+ .filter((b): b is Box => b !== null)
+ const scored = scoreWords(image, det.spec.name, point, fills)
+ words.push(...scored.words)
+ runs.push({
+ set,
+ image: gt.file,
+ detector: det.spec.name,
+ point,
+ canvasPixels: text.canvas.width * text.canvas.height,
+ preMs: d.preMs,
+ inferMs: d.inferMs,
+ postMs: d.postMs,
+ boxes: d.boxes.length,
+ fillFraction: scored.filled / (image.src.W * image.src.H),
+ })
+ }
+ }
+ if ((n + 1) % 25 === 0) {
+ console.error(` ${n + 1}/${images.length}`)
+ }
+ }
+ if (baseline) {
+ console.log(`baseline check against src/dbnet.ts: ${mismatches} of ${images.length} images differ\n`)
+ if (mismatches) {
+ process.exitCode = 1
+ }
+ }
+
+ const label = arg('label') ?? new Date().toISOString().replace(/[:.]/g, '-')
+ await mkdir(join(ROOT, 'out/text-det-bench'), { recursive: true })
+ await writeFile(join(ROOT, `out/text-det-bench/${label}.json`), JSON.stringify({ words, runs }))
+ report(words, runs, [...new Set(runs.map((r) => r.point))], [...new Set(runs.map((r) => r.set))])
+}
+
+function report(words: WordResult[], runs: RunResult[], points: string[], sets: string[]): void {
+ const detectors = [...new Set(runs.map((r) => r.detector))]
+ for (const point of points.filter((p) => !p.startsWith('t'))) {
+ console.log(`=== ${point}: per image means, single-threaded`)
+ console.log(
+ ` ${'detector'.padEnd(20)}${'canvas MP'.padStart(10)}${'pre ms'.padStart(8)}${'infer ms'.padStart(10)}${'post ms'.padStart(9)}${'total'.padStart(8)}` +
+ `${'readable'.padStart(10)}${'read.99'.padStart(9)}${'all words'.padStart(11)}${'filled'.padStart(8)}`
+ )
+ for (const detector of detectors) {
+ const r = runs.filter((x) => x.detector === detector && x.point === point)
+ const w = words.filter((x) => x.detector === detector && x.point === point)
+ const readable = w.filter((x) => x.readable)
+ console.log(
+ ` ${detector.padEnd(20)}${(mean(r.map((x) => x.canvasPixels)) / 1e6).toFixed(3).padStart(10)}` +
+ `${mean(r.map((x) => x.preMs))
+ .toFixed(1)
+ .padStart(8)}${mean(r.map((x) => x.inferMs))
+ .toFixed(1)
+ .padStart(10)}` +
+ `${mean(r.map((x) => x.postMs))
+ .toFixed(1)
+ .padStart(9)}${mean(r.map((x) => x.preMs + x.inferMs + x.postMs))
+ .toFixed(1)
+ .padStart(8)}` +
+ `${pct(readable.filter((x) => x.coverage >= COVERED).length, readable.length).padStart(10)}` +
+ `${pct(readable.filter((x) => x.coverage >= 0.99).length, readable.length).padStart(9)}` +
+ `${pct(w.filter((x) => x.coverage >= COVERED).length, w.length).padStart(11)}` +
+ `${pct(mean(r.map((x) => x.fillFraction)), 1).padStart(8)}`
+ )
+ }
+ console.log(
+ ` readable words: ${words.filter((x) => x.point === point && x.readable && x.detector === detectors[0]).length}`
+ )
+ for (const set of sets) {
+ const cells = detectors.map((detector) => {
+ const readable = words.filter(
+ (x) => x.detector === detector && x.point === point && x.set === set && x.readable
+ )
+ return pct(readable.filter((x) => x.coverage >= COVERED).length, readable.length).padStart(9)
+ })
+ console.log(` readable recall, ${set.padEnd(14)}${cells.join('')}`)
+ }
+ console.log()
+ }
+
+ console.log(`=== recall (coverage >= ${COVERED}) by word height at the model input, all sweep points pooled`)
+ const sweep = words.filter((x) => x.point.startsWith('t'))
+ const header = HEIGHT_BUCKETS.map((lo, i) => `${lo}-${HEIGHT_BUCKETS[i + 1] ?? ''}`.padStart(8)).join('')
+ for (const set of ['all', ...sets]) {
+ console.log(` ${set}`)
+ console.log(` ${'detector'.padEnd(20)}${header}`)
+ for (const detector of detectors) {
+ const cells = HEIGHT_BUCKETS.map((lo, i) => {
+ const hi = HEIGHT_BUCKETS[i + 1] ?? Infinity
+ const b = sweep.filter(
+ (x) =>
+ x.detector === detector &&
+ (set === 'all' || x.set === set) &&
+ x.heightAtModel >= lo &&
+ x.heightAtModel < hi
+ )
+ return (b.length >= 20 ? pct(b.filter((x) => x.coverage >= COVERED).length, b.length) : '.').padStart(8)
+ })
+ console.log(` ${detector.padEnd(20)}${cells.join('')}`)
+ }
+ }
+ console.log()
+ console.log('=== cost against canvas size, sweep points (ms per image, infer only / total)')
+ for (const detector of detectors) {
+ const cells = SWEEP_SCALES.map((s) => {
+ const r = runs.filter((x) => x.detector === detector && x.point === `t${s}`)
+ return r.length
+ ? `${mean(r.map((x) => x.inferMs)).toFixed(1)}/${mean(r.map((x) => x.preMs + x.inferMs + x.postMs)).toFixed(1)}`.padStart(
+ 13
+ )
+ : ''.padStart(13)
+ })
+ console.log(` ${detector.padEnd(20)}${cells.join('')}`)
+ }
+ console.log(` ${''.padEnd(20)}${SWEEP_SCALES.map((s) => `t${s}`.padStart(13)).join('')}`)
+}
+
+async function latency(): Promise<void> {
+ const specs = availableDetectors(arg('detectors')?.split(','))
+ const reps = Number(arg('reps') ?? 5)
+ const limit = Number(arg('limit') ?? 12)
+ const points = ['prod', 'fitted-global', 'fitted']
+ const images = await loadSets(arg('sets')?.split(',') ?? SETS, limit)
+ const plans = await Promise.all(images.map(({ set, gt }) => planImage(set, gt, points)))
+ console.log(`${plans.length} images x ${reps} reps, medians per image, then mean over images (ms: infer / total)\n`)
+ console.log(` ${'detector'.padEnd(20)}${'kleidiai'.padStart(9)}${points.map((p) => p.padStart(16)).join('')}`)
+ for (const spec of specs) {
+ for (const kleidiai of [true, false]) {
+ const det = await loadDetector(spec, kleidiai)
+ await detect(det, plans[0].src, plans[0].prodText)
+ const cells: string[] = []
+ for (const point of points) {
+ const infer: number[] = []
+ const total: number[] = []
+ for (const p of plans) {
+ const text = p.points.get(point)!
+ const samples: Detection[] = []
+ for (let r = 0; r < reps; r++) {
+ samples.push(await detect(det, p.src, text))
+ }
+ infer.push(median(samples.map((s) => s.inferMs)))
+ total.push(median(samples.map((s) => s.preMs + s.inferMs + s.postMs)))
+ }
+ cells.push(`${mean(infer).toFixed(1)} / ${mean(total).toFixed(1)}`.padStart(16))
+ }
+ console.log(` ${spec.name.padEnd(20)}${(kleidiai ? 'on' : 'off').padStart(9)}${cells.join('')}`)
+ await det.session.release()
+ }
+ }
+}
+
+/** Raw float32 tensors plus index.json, the format dev/text-det-quantize.py reads. */
+async function dumpCalibration(detectorName: string): Promise<void> {
+ const spec = DETECTORS.find((d) => d.name === detectorName)
+ if (!spec) {
+ throw new Error(`unknown detector ${detectorName}`)
+ }
+ const dir = join(ROOT, 'out/text-det-calibration', detectorName.replace(/\W+/g, '_'))
+ await mkdir(dir, { recursive: true })
+ const images = await loadSets(['calibration'], Number(arg('limit') ?? 1e9))
+ const index: { file: string; shape: number[] }[] = []
+ for (const { set, gt } of images) {
+ const image = await planImage(set, gt, ['prod', 'fitted'])
+ for (const [point, text] of image.points) {
+ const { data, rw, rh } = await preprocess(spec, image.src, text)
+ const file = `${gt.file.replace(/\.\w+$/, '')}_${point}.bin`
+ await writeFile(join(dir, file), Buffer.from(data.buffer, data.byteOffset, data.byteLength))
+ index.push({ file, shape: [1, 3, rh, rw] })
+ }
+ }
+ await writeFile(join(dir, 'index.json'), JSON.stringify(index))
+ console.log(`${index.length} tensors in ${dir}`)
+}
+
+const calibrationTarget = arg('dump-calibration')
+;(calibrationTarget
+ ? dumpCalibration(calibrationTarget)
+ : process.argv.includes('--latency')
+ ? latency()
+ : quality()
+).catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-corpus.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-corpus.ts
new file mode 100644
index 000000000000..96349913111a
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-corpus.ts
@@ -0,0 +1,359 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Synthetic web images with an exact ground-truth box for every word, for dev/text-det-bench.ts.
+ *
+ * tsx dev/text-det-corpus.ts [--calibration]
+ *
+ * The labelled public sets cover scans, receipts and banners, but their boxes are hand-drawn and
+ * their text sizes are whatever the set happened to contain. These images control both: every word's
+ * box is its measured ink in the rendered image, and sizes, fonts, contrast and backgrounds are swept on
+ * purpose, including the cases a detector finds hardest (small text, low contrast, light on dark, text
+ * over texture).
+ *
+ * Seeded, so the same command always writes the same images.
+ */
+import { mkdir, writeFile } from 'node:fs/promises'
+import sharp from 'sharp'
+
+import { mulberry32 } from './bench-common.ts'
+import { type GtImage, type GtWord } from './text-det-setup.ts'
+
+// --calibration writes a disjoint seed range to its own set, for int8 calibration that never sees an eval image.
+const CALIBRATION = process.argv.includes('--calibration')
+const OUT = new URL(`../test-data/text-det/${CALIBRATION ? 'calibration' : 'synthetic'}/`, import.meta.url).pathname
+const FIRST_SEED = CALIBRATION ? 100 : 0
+
+const PHRASES = [
+ 'Dashboard',
+ 'Settings',
+ 'Log out',
+ 'Total revenue $48,201.55',
+ '+1 (415) 555-0132',
+ 'Card ending 4242',
+ 'Exp 08/27',
+ 'Order #A1B2C3',
+ 'Ship to 1200 Market St, San Francisco CA 94103',
+ 'Invoice 2026-0042',
+ 'Due 2026-07-15',
+ 'SSN 123-45-6789',
+ 'DOB 1990-04-12',
+ 'Acct 0098761234',
+ 'Search results for "quarterly forecast"',
+ 'Add to cart',
+ 'Free shipping on orders over $50',
+ 'Sale ends Sunday',
+ '50% OFF',
+ 'Sign up for our newsletter',
+ 'Terms and conditions apply',
+ 'Maria Gonzalez',
+ 'Welcome back, Alex',
+ 'Your order has shipped',
+ 'Tracking 1Z999AA10123456784',
+ 'Password reset link sent',
+ 'Last login 2026-09-01 14:22',
+ 'Customer ID 88213',
+ 'Buy now',
+ 'Learn more',
+ 'New arrivals',
+ 'Q3 pipeline: 1,204 deals',
+ 'Conversion rate 3.4%',
+ 'Mon Tue Wed Thu Fri',
+ 'Unsubscribe',
+ 'Privacy policy',
+ 'ACME Corporation',
+ '221B Baker Street, London NW1 6XE',
+ 'IBAN GB29 NWBK 6016 1331 9268 19',
+]
+
+const FONTS = ['Arial', 'Helvetica', 'Georgia', 'Times New Roman', 'Courier New', 'Verdana', 'Trebuchet MS', 'Impact']
+
+interface Palette {
+ background: string
+ text: string[]
+ buttonFills: string[]
+}
+
+const LIGHT: Palette = {
+ background: '<rect width="100%" height="100%" fill="#ffffff"/>',
+ text: ['#111827', '#374151', '#6b7280', '#9ca3af', '#2563eb', '#dc2626'],
+ buttonFills: ['#2563eb', '#16a34a', '#111827', '#f59e0b'],
+}
+const GREY: Palette = { ...LIGHT, background: '<rect width="100%" height="100%" fill="#f3f4f6"/>' }
+const DARK: Palette = {
+ background: '<rect width="100%" height="100%" fill="#111827"/>',
+ text: ['#f9fafb', '#d1d5db', '#9ca3af', '#6b7280', '#60a5fa'],
+ buttonFills: ['#2563eb', '#dc2626', '#f9fafb'],
+}
+
+function texture(random: () => number): Palette {
+ const frequency = (0.004 + random() * 0.02).toFixed(4)
+ const seed = Math.floor(random() * 1000)
+ const tint = ['#7c2d12', '#1e3a8a', '#14532d', '#581c87', '#0f172a'][Math.floor(random() * 5)]
+ return {
+ background:
+ `<defs><filter id="t"><feTurbulence type="fractalNoise" baseFrequency="${frequency}" numOctaves="4" seed="${seed}"/></filter></defs>` +
+ `<rect width="100%" height="100%" fill="${tint}"/>` +
+ `<rect width="100%" height="100%" filter="url(#t)" opacity="0.75"/>`,
+ text: ['#ffffff', '#fde047', '#111827'],
+ buttonFills: ['#dc2626', '#111827', '#ffffff'],
+ }
+}
+
+function gradient(random: () => number): Palette {
+ const pairs = [
+ ['#f97316', '#db2777'],
+ ['#0ea5e9', '#6366f1'],
+ ['#fef3c7', '#fde68a'],
+ ['#e0f2fe', '#ffffff'],
+ ]
+ const [from, to] = pairs[Math.floor(random() * pairs.length)]
+ const light = from.startsWith('#f') || from.startsWith('#e')
+ return {
+ background:
+ `<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="${from}"/><stop offset="1" stop-color="${to}"/></linearGradient></defs>` +
+ `<rect width="100%" height="100%" fill="url(#g)"/>`,
+ text: light ? ['#111827', '#7c2d12', '#374151'] : ['#ffffff', '#111827', '#fef08a'],
+ buttonFills: ['#111827', '#ffffff'],
+ }
+}
+
+interface Layout {
+ name: string
+ width: number
+ height: number
+ devicePixelRatio: number
+ cssFontPxRange: [number, number]
+ palette: (random: () => number) => Palette
+}
+
+const LAYOUTS: Layout[] = [
+ { name: 'desktop', width: 1920, height: 1080, devicePixelRatio: 1, cssFontPxRange: [9, 28], palette: () => LIGHT },
+ {
+ name: 'desktop-grey',
+ width: 1440,
+ height: 900,
+ devicePixelRatio: 1,
+ cssFontPxRange: [9, 24],
+ palette: () => GREY,
+ },
+ { name: 'retina', width: 2880, height: 1800, devicePixelRatio: 2, cssFontPxRange: [9, 28], palette: () => LIGHT },
+ { name: 'dark', width: 1280, height: 720, devicePixelRatio: 1, cssFontPxRange: [9, 32], palette: () => DARK },
+ { name: 'mobile', width: 1170, height: 2532, devicePixelRatio: 3, cssFontPxRange: [10, 30], palette: () => LIGHT },
+ {
+ name: 'mobile-dark',
+ width: 750,
+ height: 1624,
+ devicePixelRatio: 2,
+ cssFontPxRange: [10, 30],
+ palette: () => DARK,
+ },
+ { name: 'og-image', width: 1200, height: 628, devicePixelRatio: 1, cssFontPxRange: [14, 72], palette: gradient },
+ { name: 'hero', width: 1600, height: 900, devicePixelRatio: 1, cssFontPxRange: [12, 96], palette: texture },
+ { name: 'leaderboard', width: 728, height: 90, devicePixelRatio: 1, cssFontPxRange: [9, 32], palette: gradient },
+ { name: 'mpu', width: 300, height: 250, devicePixelRatio: 1, cssFontPxRange: [8, 36], palette: texture },
+ { name: 'product', width: 800, height: 800, devicePixelRatio: 1, cssFontPxRange: [9, 48], palette: () => LIGHT },
+ { name: 'thumbnail', width: 480, height: 270, devicePixelRatio: 1, cssFontPxRange: [8, 40], palette: texture },
+]
+
+const SEEDS_PER_LAYOUT = 4
+
+interface Run {
+ x: number
+ baseline: number
+ fontPx: number
+ font: string
+ weight: 'normal' | 'bold'
+ color: string
+ text: string
+ buttonFill?: string
+}
+
+const escapeXml = (s: string): string =>
+ s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;')
+
+type RunStyle = Omit<Run, 'x' | 'baseline' | 'buttonFill'>
+
+/** Relative to the run's origin (x, baseline). */
+interface Ink {
+ left: number
+ top: number
+ width: number
+ height: number
+}
+
+function textElement(run: RunStyle, x: number, baseline: number): string {
+ return `<text x="${x}" y="${baseline}" font-family="${run.font}" font-size="${run.fontPx}" font-weight="${run.weight}" fill="${run.color}">${escapeXml(run.text)}</text>`
+}
+
+/** A canvas that holds the whole run, with the run's origin at (pad, baseline). */
+function measurementCanvas(run: RunStyle): { pad: number; baseline: number; width: number; height: number } {
+ const pad = Math.ceil(run.fontPx * 2)
+ return {
+ pad,
+ baseline: pad + run.fontPx * 2,
+ width: Math.ceil(run.text.length * run.fontPx * 1.1) + 2 * pad,
+ height: Math.ceil(run.fontPx * 3) + 2 * pad,
+ }
+}
+
+function svgOnCanvas(run: RunStyle, canvas: ReturnType<typeof measurementCanvas>): Buffer {
+ return Buffer.from(
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${canvas.width}" height="${canvas.height}">${textElement(run, canvas.pad, canvas.baseline)}</svg>`
+ )
+}
+
+async function measureInk(run: RunStyle): Promise<Ink> {
+ const canvas = measurementCanvas(run)
+ const { info } = await sharp(svgOnCanvas(run, canvas)).trim({ threshold: 1 }).toBuffer({ resolveWithObject: true })
+ return {
+ left: -(info.trimOffsetLeft ?? 0) - canvas.pad,
+ top: -(info.trimOffsetTop ?? 0) - canvas.baseline,
+ width: info.width,
+ height: info.height,
+ }
+}
+
+// Rasterizing a longer string changes a few alpha values of the glyphs already drawn by a few levels, while a glyph
+// that moves by a fraction of a pixel changes its edge pixels by far more than this.
+const ALPHA_NOISE = 16
+
+// Word k's ink is what the prefix through word k adds to the prefix before it. Appending text never moves the glyphs
+// already laid out, so these are the pixels word k has inside the whole run. Rendering a word alone, or hiding its
+// neighbors in separate spans, loses the kerning at its edges and shifts it.
+async function measureWordInks(run: RunStyle): Promise<{ text: string; ink: Ink }[]> {
+ const canvas = measurementCanvas(run)
+ const words = run.text.split(' ')
+ const inks: { text: string; ink: Ink }[] = []
+ let previousAlpha = new Uint8Array(canvas.width * canvas.height)
+ for (const [k, word] of words.entries()) {
+ const prefix = { ...run, text: words.slice(0, k + 1).join(' ') }
+ const alpha = new Uint8Array(
+ await sharp(svgOnCanvas(prefix, canvas)).ensureAlpha().extractChannel(3).raw().toBuffer()
+ )
+ let [left, top, right, bottom] = [canvas.width, canvas.height, -1, -1]
+ for (let i = 0; i < alpha.length; i++) {
+ const added = alpha[i] - previousAlpha[i]
+ if (added < -ALPHA_NOISE) {
+ throw new Error(`appending "${word}" to "${words.slice(0, k).join(' ')}" moved the prefix`)
+ }
+ if (added > ALPHA_NOISE) {
+ const x = i % canvas.width
+ const y = Math.floor(i / canvas.width)
+ left = Math.min(left, x)
+ top = Math.min(top, y)
+ right = Math.max(right, x + 1)
+ bottom = Math.max(bottom, y + 1)
+ }
+ }
+ if (right < 0) {
+ throw new Error(`"${word}" in "${run.text}" renders no ink`)
+ }
+ inks.push({
+ text: word,
+ ink: { left: left - canvas.pad, top: top - canvas.baseline, width: right - left, height: bottom - top },
+ })
+ previousAlpha = alpha
+ }
+ return inks
+}
+
+async function makeImage(layout: Layout, seed: number): Promise<{ png: Buffer; gt: GtImage }> {
+ const random = mulberry32(seed * 7919 + layout.width)
+ const palette = layout.palette(random)
+ const margin = Math.round(Math.min(layout.width, layout.height) * 0.04)
+ const logMin = Math.log(layout.cssFontPxRange[0] * layout.devicePixelRatio)
+ const logMax = Math.log(layout.cssFontPxRange[1] * layout.devicePixelRatio)
+ const runs: Run[] = []
+ const runBoxes: [number, number, number, number][] = []
+ const words: GtWord[] = []
+
+ let top = margin
+ while (top < layout.height - margin) {
+ const fontPx = Math.round(Math.exp(logMin + random() * (logMax - logMin)))
+ let x = margin + Math.floor(random() * fontPx * 3)
+ const rowBottomLimit = layout.height - margin
+ let rowHeight = 0
+ let placed = 0
+ for (let attempt = 0; attempt < 6 && x < layout.width - margin; attempt++) {
+ const run = {
+ fontPx,
+ font: FONTS[Math.floor(random() * FONTS.length)],
+ weight: random() < 0.3 ? ('bold' as const) : ('normal' as const),
+ color: palette.text[Math.floor(random() * palette.text.length)],
+ text: PHRASES[Math.floor(random() * PHRASES.length)],
+ }
+ const ink = await measureInk(run)
+ const baseline = top - ink.top
+ if (x + ink.left + ink.width > layout.width - margin || top + ink.height > rowBottomLimit) {
+ continue
+ }
+ const button =
+ random() < 0.12 ? palette.buttonFills[Math.floor(random() * palette.buttonFills.length)] : undefined
+ if (button && button === run.color) {
+ continue
+ }
+ runs.push({ ...run, x, baseline, buttonFill: button })
+ runBoxes.push([x + ink.left, baseline + ink.top, x + ink.left + ink.width, baseline + ink.top + ink.height])
+ for (const { text, ink: w } of await measureWordInks(run)) {
+ words.push({
+ box: [x + w.left, baseline + w.top, x + w.left + w.width, baseline + w.top + w.height],
+ text,
+ fontPx,
+ })
+ }
+ rowHeight = Math.max(rowHeight, ink.height)
+ placed++
+ x += ink.left + ink.width + Math.round(fontPx * (2 + random() * 6))
+ }
+ top += Math.max(rowHeight, fontPx) + Math.round(fontPx * (0.8 + random() * 1.4)) + (placed ? 0 : fontPx)
+ }
+
+ const buttons = runs
+ .filter((r) => r.buttonFill)
+ .map((r, i) => {
+ const w = runBoxes[runs.indexOf(r)]
+ const padX = Math.round(r.fontPx * 0.8)
+ const padY = Math.round(r.fontPx * 0.45)
+ return `<rect id="b${i}" x="${w[0] - padX}" y="${w[1] - padY}" width="${w[2] - w[0] + 2 * padX}" height="${w[3] - w[1] + 2 * padY}" rx="${padY}" fill="${r.buttonFill}"/>`
+ })
+ const svg =
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${layout.width}" height="${layout.height}">` +
+ palette.background +
+ buttons.join('') +
+ runs.map((r) => textElement(r, r.x, r.baseline)).join('') +
+ '</svg>'
+ const png = await sharp(Buffer.from(svg)).png().toBuffer()
+ const file = `synthetic_${layout.name}_${seed}.png`
+ return {
+ png,
+ gt: {
+ file,
+ width: layout.width,
+ height: layout.height,
+ words,
+ tolerancePx: 0,
+ },
+ }
+}
+
+async function main(): Promise<void> {
+ await mkdir(OUT, { recursive: true })
+ const images: GtImage[] = []
+ for (const layout of LAYOUTS) {
+ for (let seed = FIRST_SEED; seed < FIRST_SEED + SEEDS_PER_LAYOUT; seed++) {
+ const { png, gt } = await makeImage(layout, seed)
+ await writeFile(OUT + gt.file, png)
+ images.push(gt)
+ }
+ }
+ await writeFile(OUT + 'gt.json', JSON.stringify(images))
+ console.log(
+ `${CALIBRATION ? 'calibration' : 'synthetic'}: ${images.length} images, ${images.reduce((n, im) => n + im.words.length, 0)} words in ${OUT}`
+ )
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-dynamic-hw.py b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-dynamic-hw.py
new file mode 100644
index 000000000000..a37597bc8722
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-dynamic-hw.py
@@ -0,0 +1,45 @@
+"""
+Makes a docTR detector's input height and width dynamic, so dev/text-det-bench.ts can run it on the
+canvas the scale plan chooses instead of the 1024x1024 it was exported with.
+
+ uv run --with onnxruntime --with onnx python dev/text-det-dynamic-hw.py \
+ models/candidates/doctr_fast_tiny.onnx models/candidates/doctr_fast_tiny_dyn.onnx
+
+The networks are fully convolutional and size their upsampling from the input's shape, so only the
+declared shapes pin them. Clearing those is enough, which the check at the end confirms.
+"""
+
+import sys
+
+import onnx
+import numpy as np
+import onnxruntime as ort
+
+
+def main() -> None:
+ source, destination = sys.argv[1:3]
+ model = onnx.load(source)
+ graph = model.graph
+ dims = graph.input[0].type.tensor_type.shape.dim
+ for dim, name in zip(dims, ["batch", None, "height", "width"]):
+ if name:
+ dim.ClearField("dim_value")
+ dim.dim_param = name
+ for output in graph.output:
+ for dim in output.type.tensor_type.shape.dim[2:]:
+ dim.ClearField("dim_value")
+ dim.dim_param = ""
+ del graph.value_info[:]
+ onnx.save(model, destination)
+
+ session = ort.InferenceSession(destination, providers=["CPUExecutionProvider"])
+ for height, width in [(416, 736), (288, 512)]:
+ tensor = np.zeros((1, 3, height, width), dtype=np.float32)
+ shape = session.run(None, {session.get_inputs()[0].name: tensor})[0].shape
+ if shape[2:] != (height, width):
+ raise SystemExit(f"{destination}: {height}x{width} input gave {shape}")
+ sys.stdout.write(f"wrote {destination}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-quantize.py b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-quantize.py
new file mode 100644
index 000000000000..0c91c05141b3
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-quantize.py
@@ -0,0 +1,94 @@
+"""
+Static int8 quantization of a detector, calibrated on inputs dumped by dev/text-det-bench.ts or
+dev/face-bench.ts.
+
+ tsx dev/text-det-bench.ts --dump-calibration "ppocrv3 (prod)"
+ uv run --with onnxruntime --with onnx python dev/text-det-quantize.py \
+ models/dbnet_det.onnx out/text-det-calibration/ppocrv3_prod_ models/candidates/ppocrv3_det_int8.onnx
+
+The PP-OCRv3 export keeps its weights in Constant nodes, which the quantizer does not treat as weights
+and ORT's optimizer does not turn into initializers, so they are moved to initializers first. ORT's
+basic optimizations then fold batch norm into the convolutions, which quant_pre_process leaves in place,
+and an unfused batch norm between a convolution and its output quantizer keeps ORT from running that
+convolution in int8.
+"""
+
+import sys
+import json
+import argparse
+import tempfile
+from pathlib import Path
+
+import onnx
+import numpy as np
+import onnxruntime as ort
+from onnxruntime.quantization import CalibrationDataReader, CalibrationMethod, QuantFormat, QuantType, quantize_static
+
+
+class DumpedInputs(CalibrationDataReader):
+ def __init__(self, directory: Path, input_name: str) -> None:
+ index = json.loads((directory / "index.json").read_text())
+ self.tensors = iter(
+ np.fromfile(directory / entry["file"], dtype=np.float32).reshape(entry["shape"]) for entry in index
+ )
+ self.input_name = input_name
+
+ def get_next(self) -> dict[str, np.ndarray] | None:
+ tensor = next(self.tensors, None)
+ return None if tensor is None else {self.input_name: tensor}
+
+
+def constants_to_initializers(model: onnx.ModelProto) -> onnx.ModelProto:
+ graph = model.graph
+ kept = []
+ for node in graph.node:
+ value = next((a.t for a in node.attribute if a.name == "value" and a.HasField("t")), None)
+ if node.op_type == "Constant" and value is not None:
+ value.name = node.output[0]
+ graph.initializer.append(value)
+ else:
+ kept.append(node)
+ del graph.node[:]
+ graph.node.extend(kept)
+ return model
+
+
+def at_least_opset_13(model: onnx.ModelProto) -> onnx.ModelProto:
+ # Per-channel weights need DequantizeLinear's axis attribute, which only exists from opset 13.
+ default = next((o.version for o in model.opset_import if o.domain in ("", "ai.onnx")), 13)
+ return onnx.version_converter.convert_version(model, 13) if default < 13 else model
+
+
+def main() -> None:
+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
+ parser.add_argument("source", type=Path)
+ parser.add_argument("calibration_dir", type=Path)
+ parser.add_argument("destination", type=Path)
+ parser.add_argument("--conv-only", action="store_true", help="quantize only the Conv nodes")
+ args = parser.parse_args()
+ source, calibration_dir, destination = args.source, args.calibration_dir, args.destination
+ with tempfile.TemporaryDirectory() as scratch:
+ lifted = Path(scratch) / "lifted.onnx"
+ onnx.save(at_least_opset_13(constants_to_initializers(onnx.load(str(source)))), str(lifted))
+ folded = Path(scratch) / "folded.onnx"
+ options = ort.SessionOptions()
+ options.graph_optimization_level = ort.GraphOptimizationLevel.ORT_ENABLE_BASIC
+ options.optimized_model_filepath = str(folded)
+ ort.InferenceSession(str(lifted), options, providers=["CPUExecutionProvider"])
+ input_name = onnx.load(str(folded)).graph.input[0].name
+ quantize_static(
+ str(folded),
+ str(destination),
+ DumpedInputs(calibration_dir, input_name),
+ quant_format=QuantFormat.QDQ,
+ per_channel=True,
+ activation_type=QuantType.QUInt8,
+ weight_type=QuantType.QInt8,
+ calibrate_method=CalibrationMethod.MinMax,
+ op_types_to_quantize=["Conv"] if args.conv_only else None,
+ )
+ sys.stdout.write(f"wrote {destination}\n")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-setup.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-setup.ts
new file mode 100644
index 000000000000..a1435ef2821b
--- /dev/null
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/text-det-setup.ts
@@ -0,0 +1,260 @@
+/* eslint-disable no-console -- CLI output script: console output is the whole point */
+/**
+ * Downloads for dev/text-det-bench.ts: the candidate text detectors, and labelled images with a
+ * ground-truth box per word. Nothing here is committed (models/ and test-data/ are gitignored).
+ *
+ * tsx dev/text-det-setup.ts
+ *
+ * Every model is pinned by URL and sha256. The docTR exports have a fixed 1024x1024 input, so after
+ * download run dev/text-det-dynamic-hw.py on them to make height and width dynamic.
+ *
+ * Ground truth is written as test-data/text-det/<set>/gt.json in one shape for every set, so the bench
+ * never parses a dataset's own format.
+ */
+import { createHash } from 'node:crypto'
+import { existsSync } from 'node:fs'
+import { mkdir, writeFile } from 'node:fs/promises'
+import sharp from 'sharp'
+
+const ROOT = new URL('..', import.meta.url).pathname
+const UA = 'Mozilla/5.0 posthog-replay-image-scrub'
+
+const CANDIDATES: { file: string; url: string; sha256: string }[] = [
+ {
+ file: 'models/candidates/ppocrv4_mobile_det.onnx',
+ url: 'https://huggingface.co/SWHL/RapidOCR/resolve/1cfba2e90fc938db55889873735088de210cc173/PP-OCRv4/ch_PP-OCRv4_det_infer.onnx',
+ sha256: 'd2a7720d45a54257208b1e13e36a8479894cb74155a5efe29462512d42f49da9',
+ },
+ {
+ file: 'models/candidates/ppocrv5_mobile_det.onnx',
+ url: 'https://www.modelscope.cn/models/RapidAI/RapidOCR/resolve/v3.9.2/onnx/PP-OCRv5/det/ch_PP-OCRv5_det_mobile.onnx',
+ sha256: '4d97c44a20d30a81aad087d6a396b08f786c4635742afc391f6621f5c6ae78ae',
+ },
+ {
+ file: 'models/candidates/ppocrv6_tiny_det.onnx',
+ url: 'https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx/resolve/2ba1506c0380b8f0b03dd142459aac66d4421f6c/inference.onnx',
+ sha256: '193bab7a04fca699a6c82e6abb5b81bdb28177f0abd4062552b04908dafb19f8',
+ },
+ {
+ file: 'models/candidates/ppocrv6_small_det.onnx',
+ url: 'https://huggingface.co/PaddlePaddle/PP-OCRv6_small_det_onnx/resolve/28fe5895c24fd108c19eb3e8479f4ab385fbfc62/inference.onnx',
+ sha256: 'd73e0058b7a8086bbd57f3d10b8bcd4ff95363f67e06e2762b5e814fe9c9410e',
+ },
+ {
+ file: 'models/candidates/doctr_db_mobilenet_v3_large.onnx',
+ url: 'https://github.com/felixdittrich92/OnnxTR/releases/download/v0.2.0/db_mobilenet_v3_large-4987e7bd.onnx',
+ sha256: '4987e7bdea372559808bd5add85fda10e179dc639696fb489e59a197a25b4c64',
+ },
+ {
+ file: 'models/candidates/doctr_db_mobilenet_v3_large_int8.onnx',
+ url: 'https://github.com/felixdittrich92/OnnxTR/releases/download/v0.2.0/db_mobilenet_v3_large_static_8_bit-535a6f25.onnx',
+ sha256: '535a6f253365f8ea6c187567463559d4278414519e1fc995e4b87f97600a7938',
+ },
+ {
+ file: 'models/candidates/doctr_fast_tiny.onnx',
+ url: 'https://github.com/felixdittrich92/OnnxTR/releases/download/v0.0.1/rep_fast_tiny-28867779.onnx',
+ sha256: '2886777913e837ea3a5ab79f7fb9fd5db5897fc6560f21d16a4f54c64fc0b357',
+ },
+]
+
+export interface GtWord {
+ /** Axis-aligned, in the saved image's pixels: [left, top, right, bottom). */
+ box: [number, number, number, number]
+ text: string
+ fontPx?: number
+}
+
+export interface GtImage {
+ file: string
+ width: number
+ height: number
+ words: GtWord[]
+ /** How far a box edge can sit from the ink because of how the set stores coordinates. */
+ tolerancePx: number
+}
+
+async function get(url: string): Promise<Response> {
+ return fetch(url, { signal: AbortSignal.timeout(60000), headers: { 'user-agent': UA } })
+}
+
+async function getBuf(url: string, tries = 3): Promise<Buffer> {
+ for (let i = 0; ; i++) {
+ try {
+ const res = await get(url)
+ if (!res.ok) {
+ throw new Error(`HTTP ${res.status}`)
+ }
+ return Buffer.from(await res.arrayBuffer())
+ } catch (e) {
+ if (i + 1 >= tries) {
+ throw e
+ }
+ await new Promise((r) => setTimeout(r, 1000 * (i + 1)))
+ }
+ }
+}
+
+async function getJson(url: string): Promise<any> {
+ return JSON.parse((await getBuf(url)).toString('utf8'))
+}
+
+async function downloadCandidates(): Promise<void> {
+ await mkdir(ROOT + 'models/candidates', { recursive: true })
+ for (const c of CANDIDATES) {
+ if (existsSync(ROOT + c.file)) {
+ continue
+ }
+ const buf = await getBuf(c.url)
+ const digest = createHash('sha256').update(buf).digest('hex')
+ if (digest !== c.sha256) {
+ throw new Error(`${c.file}: sha256 ${digest} does not match the pinned ${c.sha256}`)
+ }
+ await writeFile(ROOT + c.file, buf)
+ console.log(` ${c.file} (${(buf.length / 1e6).toFixed(1)} MB)`)
+ }
+}
+
+/** Rows from the HF datasets-server, 100 per request, which is its page limit. */
+async function hfRows(dataset: string, split: string, count: number): Promise<Record<string, any>[]> {
+ const rows: Record<string, any>[] = []
+ for (let offset = 0; offset < count; offset += 100) {
+ const length = Math.min(100, count - offset)
+ const page = await getJson(
+ `https://datasets-server.huggingface.co/rows?dataset=${encodeURIComponent(dataset)}&config=default&split=${split}&offset=${offset}&length=${length}`
+ )
+ rows.push(...(page.rows ?? []).map((r: { row: Record<string, any> }) => r.row))
+ }
+ return rows
+}
+
+async function saveSet(
+ name: string,
+ rows: Record<string, any>[],
+ toWords: (row: Record<string, any>, width: number, height: number) => GtWord[],
+ tolerancePx: (width: number, height: number) => number
+): Promise<void> {
+ const dir = `${ROOT}test-data/text-det/${name}`
+ await mkdir(dir, { recursive: true })
+ const images: GtImage[] = []
+ for (const [i, row] of rows.entries()) {
+ const bytes = await getBuf(row.image.src)
+ const { width, height, format } = await sharp(bytes).metadata()
+ // Kept in the served encoding when the pipeline accepts it, so photos stay JPEG as they would arrive.
+ const keep = format === 'jpeg' || format === 'png'
+ const file = `${name}_${String(i).padStart(3, '0')}.${keep ? (format === 'jpeg' ? 'jpg' : 'png') : 'png'}`
+ await writeFile(`${dir}/${file}`, keep ? bytes : await sharp(bytes).png().toBuffer())
+ const words = toWords(row, width!, height!).filter((w) => w.box[2] > w.box[0] && w.box[3] > w.box[1])
+ images.push({ file, width: width!, height: height!, words, tolerancePx: tolerancePx(width!, height!) })
+ }
+ await writeFile(`${dir}/gt.json`, JSON.stringify(images))
+ console.log(` ${name}: ${images.length} images, ${images.reduce((n, im) => n + im.words.length, 0)} words`)
+}
+
+/** The born-digital set stores its annotation as a JSON-encoded string inside the row. */
+function parseDumped(value: unknown): string {
+ const text = String(value ?? '')
+ return text.startsWith('"') ? String(JSON.parse(text)) : text
+}
+
+/** Web banners and ads (ICDAR 2013 born-digital). Coordinates are whole percent of each axis. */
+async function bornDigital(count: number): Promise<void> {
+ const rows = await hfRows('Berzerker/born_digital_images_dataset', 'train', count)
+ await saveSet(
+ 'born-digital',
+ rows,
+ (row, width, height) =>
+ parseDumped(row.output_json_dumpsed)
+ .split('\n')
+ .map((line) => line.trim().split(/\s+/))
+ .filter((parts) => parts.length >= 5)
+ .map((parts) => {
+ const [x0, y0, x1, y1] = parts.slice(0, 4).map(Number)
+ return {
+ box: [
+ Math.floor((x0 / 100) * width),
+ Math.floor((y0 / 100) * height),
+ Math.ceil((x1 / 100) * width),
+ Math.ceil((y1 / 100) * height),
+ ] as GtWord['box'],
+ text: parts.slice(4).join(' '),
+ }
+ }),
+ (width, height) => Math.ceil(Math.max(width, height) / 100)
+ )
+}
+
+/** Scanned forms. Boxes are in LayoutLM's 0-1000 range on each axis, not pixels. */
+async function funsd(count: number): Promise<void> {
+ const rows = await hfRows('nielsr/funsd', 'test', count)
+ await saveSet(
+ 'funsd',
+ rows,
+ (row, width, height) =>
+ (row.words as string[]).map((text, i) => {
+ const [x0, y0, x1, y1] = row.bboxes[i] as number[]
+ return {
+ box: [
+ Math.floor((x0 / 1000) * width),
+ Math.floor((y0 / 1000) * height),
+ Math.ceil((x1 / 1000) * width),
+ Math.ceil((y1 / 1000) * height),
+ ] as GtWord['box'],
+ text,
+ }
+ }),
+ (width, height) => Math.ceil(Math.max(width, height) / 1000)
+ )
+}
+
+/** Receipt photos. Word quads are in the original image's pixels, which the server may have resized. */
+async function cord(count: number): Promise<void> {
+ const rows = await hfRows('naver-clova-ix/cord-v2', 'test', count)
+ await saveSet(
+ 'cord',
+ rows,
+ (row, width, height) => {
+ const gt = JSON.parse(row.ground_truth)
+ const size = gt.meta?.image_size ?? { width, height }
+ const sx = width / size.width
+ const sy = height / size.height
+ return (gt.valid_line ?? []).flatMap((line: any) =>
+ (line.words ?? []).map((w: any) => {
+ const q = w.quad
+ const xs = [q.x1, q.x2, q.x3, q.x4]
+ const ys = [q.y1, q.y2, q.y3, q.y4]
+ return {
+ box: [
+ Math.floor(Math.min(...xs) * sx),
+ Math.floor(Math.min(...ys) * sy),
+ Math.ceil(Math.max(...xs) * sx),
+ Math.ceil(Math.max(...ys) * sy),
+ ] as GtWord['box'],
+ text: String(w.text ?? ''),
+ }
+ })
+ )
+ },
+ () => 2
+ )
+}
+
+async function main(): Promise<void> {
+ console.log('candidate models:')
+ await downloadCandidates()
+ console.log('labelled images:')
+ for (const [name, fetchSet] of [
+ ['born-digital', () => bornDigital(100)],
+ ['funsd', () => funsd(50)],
+ ['cord', () => cord(50)],
+ ] as const) {
+ if (existsSync(`${ROOT}test-data/text-det/${name}/gt.json`)) {
+ continue
+ }
+ await fetchSet()
+ }
+}
+
+main().catch((e) => {
+ console.error(e)
+ process.exit(1)
+})