@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,246 @@
1
+ /**
2
+ * Heatmap region clustering.
3
+ *
4
+ * `detectBandShifts` (see `heatmap.ts`) reports per-band Y-shifts —
5
+ * useful for global translations but loses horizontal localization.
6
+ * Subagent F wished for "heatmap region clustering": group connected
7
+ * hot pixels in `*_heatmap.png` into clusters with rectangular
8
+ * bounding boxes, so "a text run at y=420 shifted up 4px" becomes
9
+ * one row instead of being smeared across a tall band.
10
+ *
11
+ * Reuses the connected-component algorithm from `component-bbox.ts`
12
+ * — the input is just a different mask (foreground = "hot pixel").
13
+ *
14
+ * Pixelmatch heatmaps use a fixed palette: bright red for "diff
15
+ * pixel", original (resized) baseline tinted for context. We treat
16
+ * any pixel whose red channel is strongly elevated relative to the
17
+ * other two channels as a hot pixel.
18
+ */
19
+ import { PNG } from "pngjs";
20
+ import { readFile } from "node:fs/promises";
21
+ import { classifyRegion } from "./region-classify.ts";
22
+
23
+ export interface HeatmapRegion {
24
+ top: number;
25
+ left: number;
26
+ width: number;
27
+ height: number;
28
+ /** Hot-pixel count inside the bbox. */
29
+ area: number;
30
+ /**
31
+ * Dominant color of the region as sampled from a *source* image
32
+ * (the baseline / target PNG that the heatmap was generated against).
33
+ * Only populated when `findHeatmapRegionsFromFile` was called with a
34
+ * `sourceImagePath`. Lets the agent close the loop between
35
+ * "this region differs" and "fill it with this color".
36
+ */
37
+ dominantColor?: { r: number; g: number; b: number; hex: string };
38
+ /**
39
+ * Content classification of the region inside the source image —
40
+ * `text` / `filled-rect` / `icon` / `image` / `unknown`. Helps the
41
+ * agent decide whether to paint a flat background, write a text
42
+ * run, or place an icon. Only populated when `sourceImagePath` is
43
+ * provided.
44
+ */
45
+ kind?: "text" | "filled-rect" | "icon" | "image" | "unknown";
46
+ /** Classifier confidence ∈ [0, 1]. */
47
+ kindConfidence?: number;
48
+ }
49
+
50
+ export interface FindHeatmapRegionsOptions {
51
+ /** Minimum hot-pixel count for a region to be kept. Default 80. */
52
+ minArea?: number;
53
+ /** Cap on returned regions, sorted by area desc. Default 8. */
54
+ topN?: number;
55
+ /** Hot-pixel threshold: red − max(green, blue) >= this. Default 60. */
56
+ redOverGreenBlue?: number;
57
+ /**
58
+ * Skip regions whose bbox covers ≥ this fraction of the image. When
59
+ * baseline and variant are almost entirely different (e.g. blank
60
+ * page vs full target), the CC pass produces one giant region
61
+ * spanning 0,0 → W,H. That region is uninformative ("the whole
62
+ * page differs" is already obvious from diff %) and wastes
63
+ * iteration. Default 0.8 — drop regions covering ≥80% of the image.
64
+ * From subagent dogfood eval.
65
+ */
66
+ maxRegionFraction?: number;
67
+ }
68
+
69
+ const DEFAULT_MIN_AREA = 80;
70
+ const DEFAULT_TOP_N = 8;
71
+ const DEFAULT_RED_OVER = 60;
72
+ const DEFAULT_MAX_REGION_FRACTION = 0.8;
73
+
74
+ function buildHotMask(
75
+ data: Uint8Array,
76
+ width: number,
77
+ height: number,
78
+ redOver: number,
79
+ ): Uint8Array {
80
+ const mask = new Uint8Array(width * height);
81
+ for (let y = 0; y < height; y++) {
82
+ for (let x = 0; x < width; x++) {
83
+ const idx = (y * width + x) * 4;
84
+ const r = data[idx]!, g = data[idx + 1]!, b = data[idx + 2]!;
85
+ if (r - Math.max(g, b) >= redOver) {
86
+ mask[y * width + x] = 1;
87
+ }
88
+ }
89
+ }
90
+ return mask;
91
+ }
92
+
93
+ function labelComponents(mask: Uint8Array, width: number, height: number): HeatmapRegion[] {
94
+ const labels = new Int32Array(width * height);
95
+ const parent: number[] = [0];
96
+ const find = (x: number): number => {
97
+ while (parent[x] !== x) {
98
+ parent[x] = parent[parent[x]!]!;
99
+ x = parent[x]!;
100
+ }
101
+ return x;
102
+ };
103
+ const union = (a: number, b: number): void => {
104
+ const ra = find(a), rb = find(b);
105
+ if (ra !== rb) parent[Math.max(ra, rb)] = Math.min(ra, rb);
106
+ };
107
+ let next = 1;
108
+ for (let y = 0; y < height; y++) {
109
+ for (let x = 0; x < width; x++) {
110
+ const idx = y * width + x;
111
+ if (!mask[idx]) continue;
112
+ const up = y > 0 ? labels[idx - width]! : 0;
113
+ const left = x > 0 ? labels[idx - 1]! : 0;
114
+ if (up && left) {
115
+ const a = Math.min(up, left);
116
+ labels[idx] = a;
117
+ if (up !== left) union(up, left);
118
+ } else if (up) {
119
+ labels[idx] = up;
120
+ } else if (left) {
121
+ labels[idx] = left;
122
+ } else {
123
+ labels[idx] = next;
124
+ parent[next] = next;
125
+ next++;
126
+ }
127
+ }
128
+ }
129
+ type Stat = { minX: number; minY: number; maxX: number; maxY: number; area: number };
130
+ const byRoot = new Map<number, Stat>();
131
+ for (let y = 0; y < height; y++) {
132
+ for (let x = 0; x < width; x++) {
133
+ const l = labels[y * width + x];
134
+ if (!l) continue;
135
+ const root = find(l);
136
+ let s = byRoot.get(root);
137
+ if (!s) {
138
+ s = { minX: x, minY: y, maxX: x, maxY: y, area: 0 };
139
+ byRoot.set(root, s);
140
+ }
141
+ if (x < s.minX) s.minX = x;
142
+ if (x > s.maxX) s.maxX = x;
143
+ if (y < s.minY) s.minY = y;
144
+ if (y > s.maxY) s.maxY = y;
145
+ s.area++;
146
+ }
147
+ }
148
+ const out: HeatmapRegion[] = [];
149
+ for (const s of byRoot.values()) {
150
+ out.push({
151
+ top: s.minY,
152
+ left: s.minX,
153
+ width: s.maxX - s.minX + 1,
154
+ height: s.maxY - s.minY + 1,
155
+ area: s.area,
156
+ });
157
+ }
158
+ return out;
159
+ }
160
+
161
+ export function findHeatmapRegionsFromRgba(
162
+ data: Uint8Array,
163
+ width: number,
164
+ height: number,
165
+ options: FindHeatmapRegionsOptions = {},
166
+ ): HeatmapRegion[] {
167
+ const minArea = options.minArea ?? DEFAULT_MIN_AREA;
168
+ const topN = options.topN ?? DEFAULT_TOP_N;
169
+ const redOver = options.redOverGreenBlue ?? DEFAULT_RED_OVER;
170
+ const maxFraction = options.maxRegionFraction ?? DEFAULT_MAX_REGION_FRACTION;
171
+
172
+ if (width <= 0 || height <= 0) return [];
173
+ const mask = buildHotMask(data, width, height, redOver);
174
+ const imageArea = width * height;
175
+ return labelComponents(mask, width, height)
176
+ .filter((r) => r.area >= minArea)
177
+ .filter((r) => (r.width * r.height) / imageArea < maxFraction)
178
+ .sort((a, b) => b.area - a.area)
179
+ .slice(0, topN);
180
+ }
181
+
182
+ function toHex(r: number, g: number, b: number): string {
183
+ const c = (n: number) => n.toString(16).padStart(2, "0");
184
+ return `#${c(r)}${c(g)}${c(b)}`;
185
+ }
186
+
187
+ /** Sample the dominant color inside `region` from the source image data. */
188
+ function sampleRegionColor(
189
+ sourceData: Uint8Array,
190
+ sourceWidth: number,
191
+ sourceHeight: number,
192
+ region: HeatmapRegion,
193
+ ): { r: number; g: number; b: number; hex: string } | undefined {
194
+ // Sample on a 5×5 grid inside the region. Skip transparent pixels.
195
+ // Use the median per-channel rather than mean — robust against
196
+ // boundary pixels that might pick up surrounding bg color.
197
+ const inset = 2;
198
+ const x0 = Math.max(0, region.left + inset);
199
+ const x1 = Math.min(sourceWidth, region.left + region.width - inset);
200
+ const y0 = Math.max(0, region.top + inset);
201
+ const y1 = Math.min(sourceHeight, region.top + region.height - inset);
202
+ if (x1 <= x0 || y1 <= y0) return undefined;
203
+ const stepX = Math.max(1, Math.floor((x1 - x0) / 5));
204
+ const stepY = Math.max(1, Math.floor((y1 - y0) / 5));
205
+ const rs: number[] = [], gs: number[] = [], bs: number[] = [];
206
+ for (let y = y0; y < y1; y += stepY) {
207
+ for (let x = x0; x < x1; x += stepX) {
208
+ const i = (y * sourceWidth + x) * 4;
209
+ if (sourceData[i + 3]! === 0) continue;
210
+ rs.push(sourceData[i]!);
211
+ gs.push(sourceData[i + 1]!);
212
+ bs.push(sourceData[i + 2]!);
213
+ }
214
+ }
215
+ if (rs.length === 0) return undefined;
216
+ rs.sort((a, b) => a - b); gs.sort((a, b) => a - b); bs.sort((a, b) => a - b);
217
+ const mid = rs.length >> 1;
218
+ const r = rs[mid]!, g = gs[mid]!, b = bs[mid]!;
219
+ return { r, g, b, hex: toHex(r, g, b) };
220
+ }
221
+
222
+ export async function findHeatmapRegionsFromFile(
223
+ path: string,
224
+ options: FindHeatmapRegionsOptions = {},
225
+ sourceImagePath?: string,
226
+ ): Promise<HeatmapRegion[]> {
227
+ const buf = await readFile(path);
228
+ const png = PNG.sync.read(buf);
229
+ const regions = findHeatmapRegionsFromRgba(png.data, png.width, png.height, options);
230
+ if (sourceImagePath) {
231
+ try {
232
+ const sourceBuf = await readFile(sourceImagePath);
233
+ const sourcePng = PNG.sync.read(sourceBuf);
234
+ for (const region of regions) {
235
+ const color = sampleRegionColor(sourcePng.data, sourcePng.width, sourcePng.height, region);
236
+ if (color) region.dominantColor = color;
237
+ const cls = classifyRegion(sourcePng.data, sourcePng.width, sourcePng.height, region);
238
+ region.kind = cls.kind;
239
+ region.kindConfidence = Number(cls.confidence.toFixed(2));
240
+ }
241
+ } catch {
242
+ // Source image unavailable — leave regions without annotations.
243
+ }
244
+ }
245
+ return regions;
246
+ }