@mizchi/vlmkit-core 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,410 @@
1
+ /**
2
+ * Text-row y-position extraction.
3
+ *
4
+ * Subagent F's wish-list item: "I need 'the `$24` text row is at y=420
5
+ * in the reference but y=380 in mine' as a first-class signal — without
6
+ * needing DOM correspondence."
7
+ *
8
+ * Compute the per-row mean luminance of an RGBA image. Text rows are
9
+ * darker than the surrounding whitespace (assuming light background;
10
+ * the dark-bg case is handled by symmetry: we just look for *dips*
11
+ * relative to the local average, regardless of polarity). Group
12
+ * consecutive dark rows into "text bands" and report each band's
13
+ * y-center.
14
+ *
15
+ * Pair baseline rows with variant rows by order (band #N in baseline ↔
16
+ * band #N in variant) and emit Δy. When the agent's rendering has the
17
+ * right *number* of text rows but wrong y-positions, this surfaces the
18
+ * shift directly.
19
+ */
20
+ import { PNG } from "pngjs";
21
+ import { readFile } from "node:fs/promises";
22
+
23
+ export interface TextRow {
24
+ /** Y-coordinate of the row's vertical center. */
25
+ yCenter: number;
26
+ /** Top y of the run of dark rows (inclusive). */
27
+ yStart: number;
28
+ /** Bottom y of the run of dark rows (inclusive). */
29
+ yEnd: number;
30
+ /** Mean luminance across the band (0-255). */
31
+ meanLuma: number;
32
+ /** Approximate height in pixels. */
33
+ height: number;
34
+ /**
35
+ * Estimated font-size in px, derived from band height. Typical UI
36
+ * fonts have a band height ≈ 0.75 × fontSize (the band spans
37
+ * baseline to ascender; descenders push it a bit further). Rounded
38
+ * to the nearest common UI size (12, 14, 16, 18, 20, 24, …, 72).
39
+ */
40
+ estimatedFontSize?: number;
41
+ /**
42
+ * Ink density inside the text's horizontal bounding box. Computed
43
+ * as (dark pixels with luma < 100) / (pixels in text-bbox). Larger
44
+ * values = thicker strokes = bolder weight. Empirical buckets:
45
+ * - < 0.10 → regular / light
46
+ * - 0.10-0.16 → medium / semibold
47
+ * - > 0.16 → bold / heavy
48
+ * Noisy on short text — compare same-content baseline vs variant
49
+ * for high-confidence weight-mismatch detection.
50
+ */
51
+ inkDensity?: number;
52
+ /** Bucketed weight class — heuristic, see `inkDensity` doc. */
53
+ weightBucket?: "light" | "regular" | "medium" | "bold";
54
+ /** Horizontal extent of ink within the band (px from left edge of image). */
55
+ inkLeft?: number;
56
+ inkRight?: number;
57
+ }
58
+
59
+ export interface MatchedTextRow {
60
+ /** Position in the ordered list of detected rows (0 = topmost). */
61
+ rank: number;
62
+ baseline: TextRow;
63
+ variant: TextRow;
64
+ /** variant.yCenter − baseline.yCenter (px). */
65
+ deltaY: number;
66
+ }
67
+
68
+ export interface RowGapDelta {
69
+ /** Rank of the row above the gap. */
70
+ aboveRank: number;
71
+ /** Rank of the row below the gap. */
72
+ belowRank: number;
73
+ /** Baseline gap (yCenter[below] − yCenter[above]). */
74
+ baselineGap: number;
75
+ /** Variant gap. */
76
+ variantGap: number;
77
+ /** variantGap − baselineGap; positive means the gap grew. */
78
+ delta: number;
79
+ }
80
+
81
+ export interface ExtractTextRowsOptions {
82
+ /**
83
+ * Minimum dip in mean luminance (vs. the median row luminance) for a
84
+ * row to be considered "text". Default 12 — picks up body text but
85
+ * ignores subpixel-rendering noise.
86
+ */
87
+ minLumaDip?: number;
88
+ /** Minimum band height in px. Default 4. */
89
+ minBandHeight?: number;
90
+ /** Maximum bands to return (top-N by yCenter, i.e. all of them). */
91
+ maxBands?: number;
92
+ }
93
+
94
+ const DEFAULT_MIN_LUMA_DIP = 12;
95
+ const DEFAULT_MIN_BAND_HEIGHT = 4;
96
+ const DEFAULT_MAX_BANDS = 64;
97
+
98
+ interface RowStats {
99
+ mean: Float32Array;
100
+ range: Float32Array; // max − min per row; high for text rows (dark on light bg).
101
+ }
102
+
103
+ function rowStats(data: Uint8Array, width: number, height: number): RowStats {
104
+ const mean = new Float32Array(height);
105
+ const range = new Float32Array(height);
106
+ for (let y = 0; y < height; y++) {
107
+ let sum = 0, mn = 255, mx = 0;
108
+ const rowStart = y * width * 4;
109
+ for (let x = 0; x < width; x++) {
110
+ const idx = rowStart + x * 4;
111
+ // Rec.601 luma.
112
+ const L = 0.299 * data[idx]! + 0.587 * data[idx + 1]! + 0.114 * data[idx + 2]!;
113
+ sum += L;
114
+ if (L < mn) mn = L;
115
+ if (L > mx) mx = L;
116
+ }
117
+ mean[y] = sum / width;
118
+ range[y] = mx - mn;
119
+ }
120
+ return { mean, range };
121
+ }
122
+
123
+ function median(values: Float32Array): number {
124
+ if (values.length === 0) return 0;
125
+ const sorted = Float32Array.from(values).sort();
126
+ const mid = sorted.length >> 1;
127
+ return sorted.length % 2 ? sorted[mid]! : (sorted[mid - 1]! + sorted[mid]!) / 2;
128
+ }
129
+
130
+ /** Snap a raw px height to the nearest common UI font-size bucket. */
131
+ function snapFontSize(rawPx: number): number {
132
+ const buckets = [10, 11, 12, 13, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 48, 56, 64, 72];
133
+ let best = buckets[0]!;
134
+ let bestDist = Math.abs(rawPx - best);
135
+ for (const b of buckets) {
136
+ const d = Math.abs(rawPx - b);
137
+ if (d < bestDist) { best = b; bestDist = d; }
138
+ }
139
+ return best;
140
+ }
141
+
142
+ function bucketWeight(density: number): TextRow["weightBucket"] {
143
+ // Empirical calibration against system-ui at 12-48 px:
144
+ // regular text: density 0.15-0.25
145
+ // medium (500-600): 0.25-0.35
146
+ // bold (700+): > 0.35
147
+ // Small text has slightly elevated density due to proportional AA
148
+ // blur — the buckets accept that noise.
149
+ if (density < 0.15) return "light";
150
+ if (density < 0.27) return "regular";
151
+ if (density < 0.36) return "medium";
152
+ return "bold";
153
+ }
154
+
155
+ /**
156
+ * Compute typography hints (font-size estimate, ink density, weight
157
+ * bucket) for a band by sampling its pixels. Mutates the band in
158
+ * place. From subagent G v3 dogfood: "next blocker is sub-pixel
159
+ * vertical spacing tuning — and a font-size / weight estimate per
160
+ * heatmap region would push this to < 1% in one more round."
161
+ */
162
+ function annotateTypography(
163
+ band: TextRow,
164
+ data: Uint8Array,
165
+ width: number,
166
+ height: number,
167
+ ): void {
168
+ // 1. Find the horizontal extent of ink within the band. Use an
169
+ // *adaptive* threshold so muted-gray text (e.g. #9ca3af on white,
170
+ // luma ≈ 165) is still detected. A pixel is "ink" if its luma is
171
+ // at least 50 below the band's background luma — `meanLuma` is a
172
+ // good proxy for the band's background since text occupies a
173
+ // small fraction of the band's area.
174
+ const inkThreshold = Math.max(40, band.meanLuma - 50);
175
+ let inkLeft = width, inkRight = -1;
176
+ let inkPixels = 0;
177
+ for (let y = band.yStart; y <= band.yEnd && y < height; y++) {
178
+ for (let x = 0; x < width; x++) {
179
+ const i = (y * width + x) * 4;
180
+ const L = 0.299 * data[i]! + 0.587 * data[i + 1]! + 0.114 * data[i + 2]!;
181
+ if (L < inkThreshold) {
182
+ if (x < inkLeft) inkLeft = x;
183
+ if (x > inkRight) inkRight = x;
184
+ inkPixels++;
185
+ }
186
+ }
187
+ }
188
+ if (inkRight < inkLeft) return;
189
+
190
+ // 2. Ink density = ink pixels / area of the text bbox.
191
+ const inkWidth = inkRight - inkLeft + 1;
192
+ const inkArea = inkWidth * (band.yEnd - band.yStart + 1);
193
+ const density = inkArea > 0 ? inkPixels / inkArea : 0;
194
+
195
+ // 3. Estimate font-size from band height. Calibrated empirically
196
+ // against system-ui at 12-48px: band height ≈ 0.92× fontSize
197
+ // (includes ascender + descender + AA blur). Divide to recover.
198
+ const bandH = band.height;
199
+ const rawFontSize = bandH / 0.92;
200
+ band.estimatedFontSize = snapFontSize(rawFontSize);
201
+ band.inkDensity = density;
202
+ band.weightBucket = bucketWeight(density);
203
+ band.inkLeft = inkLeft;
204
+ band.inkRight = inkRight;
205
+ }
206
+
207
+ export function extractTextRowsFromRgba(
208
+ data: Uint8Array,
209
+ width: number,
210
+ height: number,
211
+ options: ExtractTextRowsOptions = {},
212
+ ): TextRow[] {
213
+ if (width <= 0 || height <= 0) return [];
214
+
215
+ const minDip = options.minLumaDip ?? DEFAULT_MIN_LUMA_DIP;
216
+ const minBandH = options.minBandHeight ?? DEFAULT_MIN_BAND_HEIGHT;
217
+ const maxBands = options.maxBands ?? DEFAULT_MAX_BANDS;
218
+ // Minimum max-min range for a row to count as "ink-bearing". Text on
219
+ // a light bg has a row range of ≥ ~150 even when the text covers a
220
+ // small horizontal slice (the row contains both bg-luma ≈ 245 pixels
221
+ // and text-luma ≈ 30 pixels). Solid backgrounds have near-zero range.
222
+ // Set conservatively to skip subpixel AA noise (range < 30 happens
223
+ // on bands with thin horizontal lines).
224
+ const MIN_INK_RANGE = 80;
225
+
226
+ const { mean: rowMeans, range: rowRanges } = rowStats(data, width, height);
227
+ const med = median(rowMeans);
228
+ // A row is content if EITHER:
229
+ // (a) the row mean drops at least `minDip` below the median row
230
+ // mean — catches solid-fill bands (buttons, banners) that span
231
+ // the full width and pull the average down.
232
+ // (b) the row's max-min range exceeds `MIN_INK_RANGE` — catches
233
+ // thin text-on-bg bands where bg luma dominates the mean but
234
+ // a few dark text pixels pull the row min way down.
235
+ // Subagent G dogfood: prior version used (a) only and missed
236
+ // heading / price / feature rows on pricing-card targets because
237
+ // they don't pull the full-width mean below threshold.
238
+ const bands: TextRow[] = [];
239
+ let runStart = -1;
240
+ let runSum = 0;
241
+ for (let y = 0; y < height; y++) {
242
+ const meanDip = med - rowMeans[y]! >= minDip;
243
+ const hasInk = rowRanges[y]! >= MIN_INK_RANGE;
244
+ const isContent = meanDip || hasInk;
245
+ if (isContent) {
246
+ if (runStart < 0) {
247
+ runStart = y;
248
+ runSum = 0;
249
+ }
250
+ runSum += rowMeans[y]!;
251
+ } else if (runStart >= 0) {
252
+ const bandH = y - runStart;
253
+ if (bandH >= minBandH) {
254
+ bands.push({
255
+ yStart: runStart,
256
+ yEnd: y - 1,
257
+ yCenter: Math.round((runStart + y - 1) / 2),
258
+ height: bandH,
259
+ meanLuma: runSum / bandH,
260
+ });
261
+ }
262
+ runStart = -1;
263
+ }
264
+ }
265
+ if (runStart >= 0) {
266
+ const bandH = height - runStart;
267
+ if (bandH >= minBandH) {
268
+ bands.push({
269
+ yStart: runStart,
270
+ yEnd: height - 1,
271
+ yCenter: Math.round((runStart + height - 1) / 2),
272
+ height: bandH,
273
+ meanLuma: runSum / bandH,
274
+ });
275
+ }
276
+ }
277
+ const capped = bands.slice(0, maxBands);
278
+ for (const band of capped) annotateTypography(band, data, width, height);
279
+ return capped;
280
+ }
281
+
282
+ export async function extractTextRowsFromFile(
283
+ path: string,
284
+ options: ExtractTextRowsOptions = {},
285
+ ): Promise<TextRow[]> {
286
+ const buf = await readFile(path);
287
+ const png = PNG.sync.read(buf);
288
+ return extractTextRowsFromRgba(png.data, png.width, png.height, options);
289
+ }
290
+
291
+ /**
292
+ * Pair text rows by ordered index. When baseline has 6 rows and variant
293
+ * has 6 rows, this maps row #0 → row #0, #1 → #1, etc. When the counts
294
+ * differ, only the prefix common to both is matched.
295
+ *
296
+ * Reports rows with |Δy| above `minDeltaY` to keep the table focused on
297
+ * actionable shifts (small subpixel deltas are excluded by default).
298
+ */
299
+ export function matchTextRows(
300
+ baseline: TextRow[],
301
+ variant: TextRow[],
302
+ minDeltaY = 2,
303
+ ): MatchedTextRow[] {
304
+ const out: MatchedTextRow[] = [];
305
+ const n = Math.min(baseline.length, variant.length);
306
+ for (let i = 0; i < n; i++) {
307
+ const dy = variant[i]!.yCenter - baseline[i]!.yCenter;
308
+ if (Math.abs(dy) >= minDeltaY) {
309
+ out.push({
310
+ rank: i,
311
+ baseline: baseline[i]!,
312
+ variant: variant[i]!,
313
+ deltaY: dy,
314
+ });
315
+ }
316
+ }
317
+ return out;
318
+ }
319
+
320
+ /**
321
+ * Compute per-pair gap deltas from baseline ↔ variant row matches.
322
+ * The gap above row N+1 = `row[N+1].yCenter − row[N].yCenter` — the
323
+ * vertical distance between consecutive text bands. If the gap
324
+ * differs between baseline and variant, the spacing between those
325
+ * two pieces of content is wrong, and the fix is on the preceding
326
+ * element's `margin-bottom` / `padding-bottom`.
327
+ *
328
+ * Subagent G v3 dogfood: "once IoU > 0.98, the remaining ~1.7%
329
+ * diff is text baseline Δy in the 2-19px range, and the report
330
+ * doesn't yet suggest which CSS knob to turn." Gap deltas tell
331
+ * the agent exactly which margin to adjust.
332
+ */
333
+ export interface TypographyMismatch {
334
+ rank: number;
335
+ baselineFontSize?: number;
336
+ variantFontSize?: number;
337
+ baselineWeight?: TextRow["weightBucket"];
338
+ variantWeight?: TextRow["weightBucket"];
339
+ baselineDensity?: number;
340
+ variantDensity?: number;
341
+ /** "size" | "weight" | "both" */
342
+ kind: "size" | "weight" | "both";
343
+ }
344
+
345
+ /**
346
+ * Compare typography hints across ordered baseline ↔ variant pairs.
347
+ * Reports rows where:
348
+ * - estimated font-size buckets differ (different snapped px), OR
349
+ * - weight buckets differ ("regular" vs "bold").
350
+ *
351
+ * Same-content assumption: when baseline and variant render the same
352
+ * text content, ink density is directly comparable. When content
353
+ * differs, density can vary by character makeup ("iii" vs "WWW")
354
+ * and the comparison is noisier — only large bucket jumps are
355
+ * surfaced.
356
+ */
357
+ export function compareRowTypography(
358
+ baseline: TextRow[],
359
+ variant: TextRow[],
360
+ minDensityDelta = 0.04,
361
+ ): TypographyMismatch[] {
362
+ const n = Math.min(baseline.length, variant.length);
363
+ const out: TypographyMismatch[] = [];
364
+ for (let i = 0; i < n; i++) {
365
+ const b = baseline[i]!, v = variant[i]!;
366
+ if (b.estimatedFontSize === undefined || v.estimatedFontSize === undefined) continue;
367
+ const sizeDiffers = b.estimatedFontSize !== v.estimatedFontSize;
368
+ // Weight differs if buckets differ AND the underlying density
369
+ // delta is larger than the threshold (avoids flagging
370
+ // "regular vs medium" on a marginal-density pair).
371
+ const densityDelta = Math.abs((b.inkDensity ?? 0) - (v.inkDensity ?? 0));
372
+ const weightDiffers = b.weightBucket !== v.weightBucket && densityDelta >= minDensityDelta;
373
+ if (!sizeDiffers && !weightDiffers) continue;
374
+ out.push({
375
+ rank: i,
376
+ baselineFontSize: b.estimatedFontSize,
377
+ variantFontSize: v.estimatedFontSize,
378
+ baselineWeight: b.weightBucket,
379
+ variantWeight: v.weightBucket,
380
+ baselineDensity: b.inkDensity,
381
+ variantDensity: v.inkDensity,
382
+ kind: sizeDiffers && weightDiffers ? "both" : sizeDiffers ? "size" : "weight",
383
+ });
384
+ }
385
+ return out;
386
+ }
387
+
388
+ export function computeRowGapDeltas(
389
+ baseline: TextRow[],
390
+ variant: TextRow[],
391
+ minAbsoluteDelta = 2,
392
+ ): RowGapDelta[] {
393
+ const n = Math.min(baseline.length, variant.length);
394
+ const out: RowGapDelta[] = [];
395
+ for (let i = 0; i < n - 1; i++) {
396
+ const baseGap = baseline[i + 1]!.yCenter - baseline[i]!.yCenter;
397
+ const varGap = variant[i + 1]!.yCenter - variant[i]!.yCenter;
398
+ const delta = varGap - baseGap;
399
+ if (Math.abs(delta) >= minAbsoluteDelta) {
400
+ out.push({
401
+ aboveRank: i,
402
+ belowRank: i + 1,
403
+ baselineGap: baseGap,
404
+ variantGap: varGap,
405
+ delta,
406
+ });
407
+ }
408
+ }
409
+ return out;
410
+ }