Skip to content

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

feat(ai-research): size the text input from the stored image (#106816)

Robbie2b7029a66ca8
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 772653268d8d..20fd49408d34 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
@@ -224,6 +224,7 @@ Anything still readable in the artifact was therefore large enough to have been
`ratio` is derived rather than chosen, from measured floors in `src/floors.ts` — what each detector reliably finds, against what a person can still read out of the stored image.
Faces bind at 64/21 ≈ 3.05; codes need 3, and text 4.3/3 ≈ 1.43.
zxing reads the frame at exactly `ratio` times the stored scale, because its cost grows with the pixels it reads and no model fixes its input size.
+DBNet reads exactly `ratio` times the stored size too, cut down from its canvas budget whenever that makes its padded canvas smaller.
`SCRUB_SAFETY_FACTOR` (default 1.3) is margin on top, because both floors came from one font at near-black on white and low-contrast text moves the detection floor the wrong way.
**`SCRUB_OUT_MAX_PIXELS` (default 50,000) is the only knob most people should touch.**
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
index bb5d0c8b296b..b2a4ecbc8143 100644
--- 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
@@ -31,14 +31,12 @@
* 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
+ * prod the canvas src/scale-plan.ts gives the text detector: the binding ratio times the
+ * safety factor over the stored image, within the canvas budget
* 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
+ * --latency repeats the prod and 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.
*/
@@ -49,9 +47,9 @@ 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 { TEXT_FLOOR, 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 Dims, fitTextToStored, 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'
@@ -458,16 +456,6 @@ async function planImage(set: string, gt: GtImage, wanted: string[]): Promise<Im
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'))) {
@@ -475,8 +463,10 @@ async function planImage(set: string, gt: GtImage, wanted: string[]): Promise<Im
}
}
add('prod', plan.text)
- add('fitted-global', fittedTo(bindingRatio() * limits.safetyFactor))
- add('fitted', fittedTo(requiredRatio(TEXT_FLOOR) * limits.safetyFactor))
+ add(
+ 'fitted',
+ fitTextToStored(plan.text, plan.stored, requiredRatio(TEXT_FLOOR) * limits.safetyFactor, limits.stride)
+ )
for (const s of SWEEP_SCALES) {
add(`t${s}`, fitToCanvas(frame, Math.max(1, s ** 2 * framePixels), limits.stride))
}
@@ -492,8 +482,6 @@ async function planImage(set: string, gt: GtImage, wanted: string[]): Promise<Im
}
}
-const upToStride = (n: number, stride: number): number => Math.max(stride, Math.ceil(n / stride) * stride)
-
function scoreWords(
image: ImagePlan,
detector: string,
@@ -571,13 +559,18 @@ function availableDetectors(names: string[] | undefined): DetectorSpec[] {
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 points = arg('points')?.split(',') ?? ['prod', '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 === PROD_DETECTOR)
- const baseline = baselineDetector
- ? { detector: baselineDetector, prodModel: await loadDbnet(join(ROOT, baselineDetector.spec.file)) }
+ const baselineSpec = specs.find((s) => s.name === PROD_DETECTOR)
+ // The check compares logic, so its session keeps production's kernels when --no-kleidiai times the rest without
+ // them. Otherwise the kernels' rounding flips a borderline box and reports a drift that is not there.
+ const baseline = baselineSpec
+ ? {
+ detector: await loadDetector(baselineSpec, true),
+ prodModel: await loadDbnet(join(ROOT, baselineSpec.file)),
+ }
: null
console.log(`${images.length} images, detectors: ${specs.map((s) => s.name).join(', ')}\n`)
@@ -725,7 +718,7 @@ 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 points = ['prod', '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`)
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snap b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snap
index 856f9a17b4a6..fba33ba6c647 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snap
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/__snapshots__/scale-plan.characterisation.test.ts.snap
@@ -5,8 +5,8 @@ exports[`scale geometry, as it currently behaves a 4K desktop frame 1`] = `
"codeScale": "0.540",
"frame": "1181x664",
"stored": "161x90",
- "textCanvas": "928x576",
- "textContent": "928x551",
+ "textCanvas": "640x384",
+ "textContent": "638x357",
}
`;
@@ -15,8 +15,8 @@ exports[`scale geometry, as it currently behaves a 1080p desktop frame 1`] = `
"codeScale": "0.540",
"frame": "1181x664",
"stored": "161x90",
- "textCanvas": "928x576",
- "textContent": "928x551",
+ "textCanvas": "640x384",
+ "textContent": "638x357",
}
`;
@@ -25,8 +25,8 @@ exports[`scale geometry, as it currently behaves a banner past the tiling thresh
"codeScale": "1.000",
"frame": "8000x60",
"stored": "1789x13",
- "textCanvas": "8000x64",
- "textContent": "8000x60",
+ "textCanvas": "7104x64",
+ "textContent": "7088x52",
}
`;
@@ -35,8 +35,8 @@ exports[`scale geometry, as it currently behaves a degenerate column 1`] = `
"codeScale": "0.495",
"frame": "8x88590",
"stored": "1x1936",
- "textCanvas": "32x16928",
- "textContent": "6x16928",
+ "textCanvas": "32x7680",
+ "textContent": "4x7671",
}
`;
@@ -45,8 +45,8 @@ exports[`scale geometry, as it currently behaves a degenerate strip 1`] = `
"codeScale": "0.495",
"frame": "88590x8",
"stored": "1936x1",
- "textCanvas": "16928x32",
- "textContent": "16928x6",
+ "textCanvas": "7680x32",
+ "textContent": "7671x4",
}
`;
@@ -55,8 +55,8 @@ exports[`scale geometry, as it currently behaves a mobile portrait frame 1`] = `
"codeScale": "0.756",
"frame": "390x844",
"stored": "74x161",
- "textCanvas": "416x864",
- "textContent": "390x844",
+ "textCanvas": "320x640",
+ "textContent": "294x638",
}
`;
@@ -65,8 +65,8 @@ exports[`scale geometry, as it currently behaves a retina laptop frame 1`] = `
"codeScale": "0.570",
"frame": "1120x700",
"stored": "161x100",
- "textCanvas": "864x608",
- "textContent": "864x581",
+ "textCanvas": "640x416",
+ "textContent": "638x397",
}
`;
@@ -85,8 +85,8 @@ exports[`scale geometry, as it currently behaves a square at the cap 1`] = `
"codeScale": "1.000",
"frame": "671x671",
"stored": "161x161",
- "textCanvas": "672x672",
- "textContent": "671x671",
+ "textCanvas": "640x640",
+ "textContent": "638x638",
}
`;
@@ -105,7 +105,7 @@ exports[`scale geometry, as it currently behaves a wide banner 1`] = `
"codeScale": "0.486",
"frame": "2048x219",
"stored": "251x26",
- "textCanvas": "2048x224",
- "textContent": "2048x219",
+ "textCanvas": "1024x128",
+ "textContent": "995x104",
}
`;
diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts
index 9e1979d8d2fc..07f2cbadf21d 100644
--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts
+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.ts
@@ -175,6 +175,28 @@ export function faceInputScale(dims: Dims, side: number, tileAbove: number, tile
return Math.min(1, side / faceWindowLong(long, short, tileAbove, tileAspect))
}
+/**
+ * The text detector's input, cut down to the ratio over the stored image.
+ *
+ * The canvas budget sizes text for the frame alone. Once faces or the stored-size cap make the stored image
+ * smaller than that budget allows, text reads more pixels than any readable word needs. The rule is per axis:
+ * text h px tall in the frame is h * content / frame at the model and h * stored / frame in the artifact.
+ */
+export function fitTextToStored(
+ text: { content: Dims; canvas: Dims },
+ stored: Dims,
+ ratio: number,
+ stride: number
+): { content: Dims; canvas: Dims } {
+ const content = {
+ width: Math.min(text.content.width, Math.ceil(ratio * stored.width)),
+ height: Math.min(text.content.height, Math.ceil(ratio * stored.height)),
+ }
+ const canvas = { width: upToStride(content.width, stride), height: upToStride(content.height, stride) }
+ // A cut that leaves the padded canvas as large as before saves no inference and only adds a resample.
+ return canvas.width * canvas.height < text.canvas.width * text.canvas.height ? { content, canvas } : text
+}
+
// A resize has a fixed cost that a small reduction does not win back in zxing time, so zxing reads the frame as it
// is unless the plan takes it below this. Reading more than the ratio asks for cannot break rule 4.
const CODE_RESIZE_BELOW = 0.85
@@ -185,15 +207,16 @@ const CODE_RESIZE_BELOW = 0.85
* The stored size is derived from the WEAKEST detector rather than any single one: a guarantee that
* holds for the text detector and not the face detector is not a guarantee. Every reduction between
* the source and each detector is already folded into its scale, so the ratio is enforced against
- * what each model really saw rather than against the budgets that were asked for.
+ * what each model really saw rather than against the budgets that were asked for. The text detector is
+ * then cut down to the ratio over the stored size, because its budget alone can ask for more.
*/
export function planScales(source: Dims, limits: PlanLimits): ScalePlan {
const frame = fitToArea(source, limits.framePixels)
- const text = fitToCanvas(frame, limits.textCanvasPixels, limits.stride)
+ const textBudget = fitToCanvas(frame, limits.textCanvasPixels, limits.stride)
const faceScale = faceInputScale(frame, limits.faceInputSide, limits.faceTileAbove, limits.faceTileAspect)
// Each detector's scale relative to the frame, so they are comparable.
- const textScale = Math.min(text.content.width / frame.width, text.content.height / frame.height)
+ const textScale = Math.min(textBudget.content.width / frame.width, textBudget.content.height / frame.height)
const weakest = Math.min(textScale, faceScale, 1)
const ratio = bindingRatio() * limits.safetyFactor
@@ -204,7 +227,7 @@ export function planScales(source: Dims, limits: PlanLimits): ScalePlan {
const codeScale = Math.min(1, ratio * keptScale)
return {
frame,
- text,
+ text: fitTextToStored(textBudget, stored, ratio, limits.stride),
face: { scale: faceScale },
code: { scale: codeScale < CODE_RESIZE_BELOW ? codeScale : 1 },
stored,