: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(ai-research): detect text with PP-OCRv6 tiny in image scrub (#106797)
Robbie9c11779600e7
diff --git a/Dockerfile.ml-mirror-image-scrub b/Dockerfile.ml-mirror-image-scrubindex 6031b2dc3b5a..48810f132b93 100644--- a/Dockerfile.ml-mirror-image-scrub+++ b/Dockerfile.ml-mirror-image-scrub@@ -43,8 +43,8 @@ RUN rm -f src/*.test.ts# The ONNX models (safety gate, face, text), pinned to immutable upstream refs and checksum-verified# by BuildKit; loadModels() reads them from WORKDIR-relative models/. Keep URLs + digests in sync# with dev/setup.ts (the dev-machine download path).-ADD --checksum=sha256:f139598bc2af4e4b6fe98dec11574e30edfdd91fc94ac1425c18ace3bd5a866b \- https://huggingface.co/SWHL/RapidOCR/resolve/1cfba2e90fc938db55889873735088de210cc173/PP-OCRv4/en_PP-OCRv3_det_infer.onnx \+ADD --checksum=sha256:193bab7a04fca699a6c82e6abb5b81bdb28177f0abd4062552b04908dafb19f8 \+ https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx/resolve/2ba1506c0380b8f0b03dd142459aac66d4421f6c/inference.onnx \models/dbnet_det.onnxADD --checksum=sha256:8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4 \https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/face_detection_yunet_2023mar.onnx \diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.md b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/README.mdindex 1c5da1effdba..772653268d8d 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@@ -118,13 +118,13 @@ The fill's edges are feathered by blurring the fill's _colour_ only, never the mAll model inference and image processing run in optimized native libraries.The TypeScript is orchestration plus lightweight output decoding (over small downscaled maps, not full images):-| Stage | Library | Native engine |-| ---------------------------------- | ------------------ | -------------------- |-| NSFW/gore classify (SwiftFormer) | `onnxruntime-node` | ONNX Runtime (C++) |-| Face detection (YuNet) | `onnxruntime-node` | ONNX Runtime (C++) |-| Text detection (DBNet / PP-OCRv3) | `onnxruntime-node` | ONNX Runtime (C++) |-| QR/barcode detection | `zxing-wasm` | zxing-cpp (C++/wasm) |-| resize / blur / composite / encode | `sharp` | libvips (C++) |+| Stage | Library | Native engine |+| -------------------------------------- | ------------------ | -------------------- |+| NSFW/gore classify (SwiftFormer) | `onnxruntime-node` | ONNX Runtime (C++) |+| Face detection (YuNet) | `onnxruntime-node` | ONNX Runtime (C++) |+| Text detection (DBNet / PP-OCRv6 tiny) | `onnxruntime-node` | ONNX Runtime (C++) |+| QR/barcode detection | `zxing-wasm` | zxing-cpp (C++/wasm) |+| resize / blur / composite / encode | `sharp` | libvips (C++) |We do not train anything and run no neural nets in JS.The only hand-written JS is model-output decoding (DBNet threshold + dilation + connected components, YuNet anchor decode + NMS, tensor packing, mask fill), which runs over the small detection maps and is not the bottleneck.@@ -201,7 +201,7 @@ The suite **gates** on session replay's representative domain (crisp rendered-UI```textUI TEXT (gated): 31/31 clean, 0.0% leak [PASS] # rendered screenshots-DOCUMENT TEXT (report): 19/20 clean, 2.7% worst [report] # faint fax/scan print, out of domain+DOCUMENT TEXT (report): 20/20 clean, 0.0% worst [report] # faint fax/scan print, out of domainFACE: 89/89 faces redacted (100%)```@@ -222,7 +222,7 @@ One rule sets every size: **each detector must see a subject at least `ratio` tiAnything still readable in the artifact was therefore large enough to have been found and filled.`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 7/3 ≈ 2.33.+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.`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.diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.tsindex c069bc3fd24a..0a6f44cc2f68 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/dev/setup.ts@@ -10,7 +10,7 @@ import { existsSync } from 'node:fs'* /splits discovers a valid config+split, /rows returns rows whose image cells carry a `src` URL.* The dataset list below is just defaults — swap in whatever faces/text sources you want.*/-import { mkdir, writeFile } from 'node:fs/promises'+import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'import sharp from 'sharp'const ROOT = new URL('..', import.meta.url).pathname@@ -21,9 +21,9 @@ const ROOT = new URL('..', import.meta.url).pathname// same files at build time).const MODELS: { url: string; file: string; sha256: string }[] = [{- url: 'https://huggingface.co/SWHL/RapidOCR/resolve/1cfba2e90fc938db55889873735088de210cc173/PP-OCRv4/en_PP-OCRv3_det_infer.onnx',+ url: 'https://huggingface.co/PaddlePaddle/PP-OCRv6_tiny_det_onnx/resolve/2ba1506c0380b8f0b03dd142459aac66d4421f6c/inference.onnx',file: 'models/dbnet_det.onnx',- sha256: 'f139598bc2af4e4b6fe98dec11574e30edfdd91fc94ac1425c18ace3bd5a866b',+ sha256: '193bab7a04fca699a6c82e6abb5b81bdb28177f0abd4062552b04908dafb19f8',},{url: 'https://github.com/opencv/opencv_zoo/raw/47534e27c9851bb1128ccc0102f1145e27f23f98/models/face_detection_yunet/face_detection_yunet_2023mar.onnx',@@ -88,19 +88,30 @@ async function getBuf(url: string, tries = 3): Promise<Buffer> {throw new Error('unreachable')}+const sha256Hex = (bytes: Uint8Array): string => createHash('sha256').update(bytes).digest('hex')+async function downloadModels(): Promise<void> {for (const m of MODELS) {const dest = ROOT + m.fileif (existsSync(dest)) {- continue+ if (sha256Hex(await readFile(dest)) === m.sha256) {+ continue+ }+ console.warn(` ${m.file} does not match its pinned sha256, replacing it`)}const buf = await getBuf(m.url)- const digest = createHash('sha256').update(buf).digest('hex')+ const digest = sha256Hex(buf)if (digest !== m.sha256) {throw new Error(`${m.file}: sha256 mismatch (got ${digest}, want ${m.sha256}) — refusing to write`)}await mkdir(ROOT + 'models', { recursive: true })- await writeFile(dest, buf)+ const partial = `${dest}.${process.pid}.partial`+ try {+ await writeFile(partial, buf)+ await rename(partial, dest)+ } finally {+ await rm(partial, { force: true })+ }}}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.tsindex 2645d9c76813..bb5d0c8b296b 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@@ -4,7 +4,7 @@* frames the production plan hands the text stage.** Setup, once:- * npm run setup # the production model, which the ppocrv3 entries use+ * npm run setup # the production model, which the prod entry uses* 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@@ -72,29 +72,39 @@ interface DetectorSpec {const IMAGENET = { mean: [0.485, 0.456, 0.406], std: [0.229, 0.224, 0.225] } as constconst 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)+const PROD_PROB_THRESHOLD = numFromEnv('PROB_T', 0.2, 0.05, 0.9)+const PROD_BOX_SCORE = numFromEnv('BOX_SCORE', 0.4, 0.05, 0.95)+const PPOCRV3_THRESHOLDS = { probThreshold: 0.3, boxScoreMin: 0.5 } as const+const PROD_DETECTOR = 'ppocrv6-tiny (prod)'// 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.+// applied in that order. The ppocrv3 entry feeds RGB and ppocrv3-bgr feeds BGR, so together they+// measure what the channel order costs that model.const DETECTORS: DetectorSpec[] = [{- name: 'ppocrv3 (prod)',+ name: PROD_DETECTOR,file: 'models/dbnet_det.onnx',- channelOrder: 'rgb',+ channelOrder: 'bgr',...copyStats(IMAGENET),output: 'probability',probThreshold: PROD_PROB_THRESHOLD,boxScoreMin: PROD_BOX_SCORE,},+ {+ name: 'ppocrv3',+ file: 'models/candidates/ppocrv3_det.onnx',+ channelOrder: 'rgb',+ ...copyStats(IMAGENET),+ output: 'probability',+ ...PPOCRV3_THRESHOLDS,+ },{name: 'ppocrv3-bgr',- file: 'models/dbnet_det.onnx',+ file: 'models/candidates/ppocrv3_det.onnx',channelOrder: 'bgr',...copyStats(IMAGENET),output: 'probability',- probThreshold: PROD_PROB_THRESHOLD,- boxScoreMin: PROD_BOX_SCORE,+ ...PPOCRV3_THRESHOLDS,},{name: 'ppocrv3-int8',@@ -102,8 +112,7 @@ const DETECTORS: DetectorSpec[] = [channelOrder: 'rgb',...copyStats(IMAGENET),output: 'probability',- probThreshold: PROD_PROB_THRESHOLD,- boxScoreMin: PROD_BOX_SCORE,+ ...PPOCRV3_THRESHOLDS,},{name: 'ppocrv3-int8-conv',@@ -111,8 +120,7 @@ const DETECTORS: DetectorSpec[] = [channelOrder: 'rgb',...copyStats(IMAGENET),output: 'probability',- probThreshold: PROD_PROB_THRESHOLD,- boxScoreMin: PROD_BOX_SCORE,+ ...PPOCRV3_THRESHOLDS,},{name: 'ppocrv4-mobile',@@ -132,15 +140,6 @@ const DETECTORS: DetectorSpec[] = [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',@@ -576,7 +575,7 @@ async function quality(): Promise<void> {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 baselineDetector = detectors.find((d) => d.spec.name === PROD_DETECTOR)const baseline = baselineDetector? { detector: baselineDetector, prodModel: await loadDbnet(join(ROOT, baselineDetector.spec.file)) }: nulldiff --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.pyindex 0c91c05141b3..fae99757e8a7 100644--- 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@@ -2,9 +2,9 @@Static int8 quantization of a detector, calibrated on inputs dumped by dev/text-det-bench.ts ordev/face-bench.ts.- tsx dev/text-det-bench.ts --dump-calibration "ppocrv3 (prod)"+ tsx dev/text-det-bench.ts --dump-calibration "ppocrv3"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+ models/candidates/ppocrv3_det.onnx out/text-det-calibration/ppocrv3 models/candidates/ppocrv3_det_int8.onnxThe PP-OCRv3 export keeps its weights in Constant nodes, which the quantizer does not treat as weightsand ORT's optimizer does not turn into initializers, so they are moved to initializers first. ORT'sdiff --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.tsindex a1435ef2821b..349950411ef4 100644--- 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@@ -20,6 +20,11 @@ const ROOT = new URL('..', import.meta.url).pathnameconst UA = 'Mozilla/5.0 posthog-replay-image-scrub'const CANDIDATES: { file: string; url: string; sha256: string }[] = [+ {+ file: 'models/candidates/ppocrv3_det.onnx',+ url: 'https://huggingface.co/SWHL/RapidOCR/resolve/1cfba2e90fc938db55889873735088de210cc173/PP-OCRv4/en_PP-OCRv3_det_infer.onnx',+ sha256: 'f139598bc2af4e4b6fe98dec11574e30edfdd91fc94ac1425c18ace3bd5a866b',+ },{file: 'models/candidates/ppocrv4_mobile_det.onnx',url: 'https://huggingface.co/SWHL/RapidOCR/resolve/1cfba2e90fc938db55889873735088de210cc173/PP-OCRv4/ch_PP-OCRv4_det_infer.onnx',@@ -30,11 +35,6 @@ const CANDIDATES: { file: string; url: string; sha256: string }[] = [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',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.tsindex 93e9f9abf00a..d763de240496 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/dbnet.ts@@ -1,6 +1,6 @@/**- * DBNet text-region detection via onnxruntime-node (native). Model: PP-OCRv3 detection (a DB head),- * ~2.4MB ONNX. Outputs a per-pixel text-probability map; we threshold it, horizontally dilate it+ * DBNet text-region detection via onnxruntime-node (native). Model: PP-OCRv6 tiny detection (a DB+ * head), ~1.8MB ONNX. Outputs a per-pixel text-probability map; we threshold it, horizontally dilate it* (so words on a line bridge into one box that reaches the line end), find connected components,* and return their expanded axis-aligned boxes. Axis-aligned is enough since we only blur.*@@ -24,9 +24,10 @@ export interface DetectOpts {padY?: number}+// The two thresholds are the model's own `thresh` and `box_thresh`, from the inference.yml it ships with.const DEFAULTS: Required<DetectOpts> = {- probThreshold: numFromEnv('PROB_T', 0.3, 0.05, 0.9),- boxScoreMin: numFromEnv('BOX_SCORE', 0.5, 0.05, 0.95),+ probThreshold: numFromEnv('PROB_T', 0.2, 0.05, 0.9),+ boxScoreMin: numFromEnv('BOX_SCORE', 0.4, 0.05, 0.95),minAreaPx: numFromEnv('MIN_AREA', 16, 1, 1024),dilateX: numFromEnv('DILATE_X', 6, 0, 64),padX: numFromEnv('PAD_X', 0.25, 0, 2),@@ -90,10 +91,11 @@ async function preprocess(.toBuffer({ resolveWithObject: true })const chw = new Float32Array(3 * rw * rh)const plane = rw * rh+ // PaddleOCR decodes with OpenCV, so the model takes BGR planes, with the statistics applied in that order.for (let i = 0, p = 0; i < data.length; i += 3, p++) {- chw[p] = (data[i] / 255 - MEAN[0]) / STD[0]+ chw[p] = (data[i + 2] / 255 - MEAN[0]) / STD[0]chw[plane + p] = (data[i + 1] / 255 - MEAN[1]) / STD[1]- chw[2 * plane + p] = (data[i + 2] / 255 - MEAN[2]) / STD[2]+ chw[2 * plane + p] = (data[i] / 255 - MEAN[2]) / STD[2]}return { data: chw, rw, rh, sx: src.W / cw, sy: src.H / ch }}diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.tsindex f375230a8836..175bc4bfec60 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/floors.ts@@ -21,17 +21,18 @@ export interface Floor {}/**- * Text is the binding subject and the best measured.+ * Text is the best measured subject.*- * Detection: `tsx dev/glyph-floor.ts` sweeps rendered size against a fixed frame. DBNet starts finding- * text at about 4.9px and has every line by 7px, at the model input.+ * Detection: `tsx dev/glyph-floor.ts` sweeps rendered size against a fixed frame. PP-OCRv6 tiny starts+ * finding text at about 2.9px and has every line by 4.3px, at the model input. On the labelled sets of+ * `dev/text-det-bench.ts` it covers every word from 5 to 7px there, and those sets hold few words below 5px.** Readability: rendered samples at a range of sizes, judged by eye. 4px is readable and 3px is not,* so 3px is the largest size that carries nothing, which is the conservative end of that boundary. Tesseract gives up at 8-9px and is not the bar: a person reads* well past where OCR does, and using OCR as the proxy hid a live leak once already.*/export const TEXT_FLOOR: Floor = {- detectedAt: 7,+ detectedAt: 4.3,readableAt: 3,unit: 'font-size px (ink is about 0.72x this)',measuredBy: 'dev/glyph-floor.ts, plus a human judgement on rendered samples',diff --git a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.tsindex 2ad09fb59631..5525000815dd 100644--- a/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts+++ b/nodejs/src/ingestion/pipelines/sessionreplay/ml-mirror-image-scrub-sidecar/src/scale-plan.test.ts@@ -87,7 +87,7 @@ describe('scale-plan', () => {it('is the tightest subject that sets the ratio', () => {// Whichever subject has least room decides, so adding a detector can only tighten it.expect(bindingRatio()).toBe(Math.max(...Object.values(FLOORS).map(requiredRatio)))- expect(requiredRatio(FLOORS.text)).toBeCloseTo(7 / 3, 5)+ expect(requiredRatio(FLOORS.text)).toBeCloseTo(4.3 / 3, 5)})it('respects the stored budget when that is the tighter bound', () => {