@mizchi/vlmkit-core 0.6.0 → 0.7.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.
- package/README.md +9 -6
- package/package.json +3 -3
- package/src/authored-style-capture.ts +185 -0
- package/src/authored-style-diff.ts +32 -0
- package/src/computed-style-capture.ts +143 -22
- package/src/element-compare.ts +25 -10
- package/src/heatmap-regions.ts +5 -6
- package/src/heatmap.ts +155 -1
- package/src/image-resize.ts +1 -1
- package/src/index.ts +5 -8
- package/src/png-utils.ts +30 -0
- package/src/region-shift.ts +173 -0
- package/src/text-rows.ts +2 -0
- package/src/types.ts +65 -0
- package/src/a11y-contrast.ts +0 -387
- package/src/a11y-focus-order.ts +0 -397
- package/src/a11y-touch.ts +0 -340
- package/src/grid-ratio.ts +0 -251
- package/src/png-diff.ts +0 -165
- package/src/quality.ts +0 -209
- package/src/region-classify.ts +0 -189
- package/src/shift-origin.ts +0 -204
- package/src/visual-semantic.ts +0 -185
package/src/png-diff.ts
DELETED
|
@@ -1,165 +0,0 @@
|
|
|
1
|
-
import { mkdir } from "node:fs/promises";
|
|
2
|
-
import { basename, join } from "node:path";
|
|
3
|
-
import { compareScreenshots } from "./heatmap.ts";
|
|
4
|
-
import { classifyVisualDiff } from "./visual-semantic.ts";
|
|
5
|
-
import type { VrtSnapshot } from "./types.ts";
|
|
6
|
-
|
|
7
|
-
export interface PngDiffCliOptions {
|
|
8
|
-
baselinePath: string;
|
|
9
|
-
currentPath: string;
|
|
10
|
-
outputDir: string;
|
|
11
|
-
threshold: number;
|
|
12
|
-
skipHeatmap: boolean;
|
|
13
|
-
json: boolean;
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
class PngDiffCliError extends Error {
|
|
17
|
-
readonly exitCode: number;
|
|
18
|
-
|
|
19
|
-
constructor(message: string, exitCode: number) {
|
|
20
|
-
super(message);
|
|
21
|
-
this.exitCode = exitCode;
|
|
22
|
-
}
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
export function formatPngDiffUsage(): string {
|
|
26
|
-
return `vrt png-diff <baseline.png> <current.png>
|
|
27
|
-
|
|
28
|
-
Compare two existing PNG screenshots without launching Playwright.
|
|
29
|
-
|
|
30
|
-
Options:
|
|
31
|
-
--output-dir <path> Directory for generated heatmaps (default: test-results/png-diff)
|
|
32
|
-
--threshold <0-1> pixelmatch threshold (default: 0.1)
|
|
33
|
-
--no-heatmap Skip heatmap generation
|
|
34
|
-
--json Print JSON instead of a human-readable summary`;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
export function parsePngDiffArgs(args: string[]): PngDiffCliOptions {
|
|
38
|
-
const positional: string[] = [];
|
|
39
|
-
let outputDir = join(process.cwd(), "test-results", "png-diff");
|
|
40
|
-
let threshold = 0.1;
|
|
41
|
-
let skipHeatmap = false;
|
|
42
|
-
let json = false;
|
|
43
|
-
|
|
44
|
-
for (let i = 0; i < args.length; i++) {
|
|
45
|
-
const arg = args[i]!;
|
|
46
|
-
switch (arg) {
|
|
47
|
-
case "--help":
|
|
48
|
-
case "-h":
|
|
49
|
-
throw new PngDiffCliError(formatPngDiffUsage(), 0);
|
|
50
|
-
case "--output":
|
|
51
|
-
case "--output-dir": {
|
|
52
|
-
const value = args[++i];
|
|
53
|
-
if (!value) throw new PngDiffCliError(`Missing value for ${arg}\n\n${formatPngDiffUsage()}`, 1);
|
|
54
|
-
outputDir = value;
|
|
55
|
-
break;
|
|
56
|
-
}
|
|
57
|
-
case "--threshold": {
|
|
58
|
-
const value = args[++i];
|
|
59
|
-
const parsed = value ? Number(value) : Number.NaN;
|
|
60
|
-
if (!value || !Number.isFinite(parsed) || parsed < 0 || parsed > 1) {
|
|
61
|
-
throw new PngDiffCliError(`Invalid --threshold value: ${value ?? ""}\n\n${formatPngDiffUsage()}`, 1);
|
|
62
|
-
}
|
|
63
|
-
threshold = parsed;
|
|
64
|
-
break;
|
|
65
|
-
}
|
|
66
|
-
case "--no-heatmap":
|
|
67
|
-
skipHeatmap = true;
|
|
68
|
-
break;
|
|
69
|
-
case "--json":
|
|
70
|
-
json = true;
|
|
71
|
-
break;
|
|
72
|
-
default:
|
|
73
|
-
if (arg.startsWith("--")) {
|
|
74
|
-
throw new PngDiffCliError(`Unknown option: ${arg}\n\n${formatPngDiffUsage()}`, 1);
|
|
75
|
-
}
|
|
76
|
-
positional.push(arg);
|
|
77
|
-
break;
|
|
78
|
-
}
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
if (positional.length !== 2) {
|
|
82
|
-
throw new PngDiffCliError(formatPngDiffUsage(), 1);
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
const [baselinePath, currentPath] = positional;
|
|
86
|
-
return { baselinePath, currentPath, outputDir, threshold, skipHeatmap, json };
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export async function runPngDiff(options: PngDiffCliOptions) {
|
|
90
|
-
if (!options.skipHeatmap) {
|
|
91
|
-
await mkdir(options.outputDir, { recursive: true });
|
|
92
|
-
}
|
|
93
|
-
|
|
94
|
-
const snapshot: VrtSnapshot = {
|
|
95
|
-
testId: basename(options.currentPath, ".png") || "png-diff",
|
|
96
|
-
testTitle: basename(options.currentPath),
|
|
97
|
-
projectName: "vrt",
|
|
98
|
-
screenshotPath: options.currentPath,
|
|
99
|
-
baselinePath: options.baselinePath,
|
|
100
|
-
status: "changed",
|
|
101
|
-
};
|
|
102
|
-
|
|
103
|
-
const diff = await compareScreenshots(snapshot, {
|
|
104
|
-
outputDir: options.skipHeatmap ? undefined : options.outputDir,
|
|
105
|
-
skipHeatmap: options.skipHeatmap,
|
|
106
|
-
threshold: options.threshold,
|
|
107
|
-
});
|
|
108
|
-
if (!diff) {
|
|
109
|
-
throw new Error("PNG diff requires both baseline and current screenshot paths");
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
const semantic = classifyVisualDiff(diff);
|
|
113
|
-
return { diff, semantic };
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
export async function runPngDiffCli(cliArgs = process.argv.slice(2)) {
|
|
117
|
-
try {
|
|
118
|
-
const options = parsePngDiffArgs(cliArgs);
|
|
119
|
-
const result = await runPngDiff(options);
|
|
120
|
-
const output = {
|
|
121
|
-
status: result.diff.diffPixels === 0 ? "pass" : "changed",
|
|
122
|
-
baselinePath: options.baselinePath,
|
|
123
|
-
currentPath: options.currentPath,
|
|
124
|
-
diffPixels: result.diff.diffPixels,
|
|
125
|
-
totalPixels: result.diff.totalPixels,
|
|
126
|
-
diffRatio: result.diff.diffRatio,
|
|
127
|
-
regions: result.diff.regions,
|
|
128
|
-
heatmapPath: result.diff.heatmapPath,
|
|
129
|
-
summary: result.semantic.summary,
|
|
130
|
-
changes: result.semantic.changes,
|
|
131
|
-
};
|
|
132
|
-
|
|
133
|
-
if (options.json) {
|
|
134
|
-
console.log(JSON.stringify(output, null, 2));
|
|
135
|
-
return;
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
console.log("PNG Diff");
|
|
139
|
-
console.log(` baseline: ${output.baselinePath}`);
|
|
140
|
-
console.log(` current: ${output.currentPath}`);
|
|
141
|
-
console.log(` diff: ${(output.diffRatio * 100).toFixed(2)}% (${output.diffPixels} / ${output.totalPixels} px)`);
|
|
142
|
-
console.log(` regions: ${output.regions.length}`);
|
|
143
|
-
console.log(` summary: ${output.summary}`);
|
|
144
|
-
if (output.heatmapPath) {
|
|
145
|
-
console.log(` heatmap: ${output.heatmapPath}`);
|
|
146
|
-
}
|
|
147
|
-
} catch (error) {
|
|
148
|
-
if (error instanceof PngDiffCliError) {
|
|
149
|
-
if (error.exitCode === 0) {
|
|
150
|
-
console.log(error.message);
|
|
151
|
-
} else {
|
|
152
|
-
console.error(error.message);
|
|
153
|
-
}
|
|
154
|
-
process.exit(error.exitCode);
|
|
155
|
-
}
|
|
156
|
-
throw error;
|
|
157
|
-
}
|
|
158
|
-
}
|
|
159
|
-
|
|
160
|
-
if (process.env.__VRT_DISPATCHER_LEAF__ === "png-diff" || process.argv[1]?.endsWith("png-diff.ts")) {
|
|
161
|
-
runPngDiffCli().catch((error) => {
|
|
162
|
-
console.error(error);
|
|
163
|
-
process.exit(1);
|
|
164
|
-
});
|
|
165
|
-
}
|
package/src/quality.ts
DELETED
|
@@ -1,209 +0,0 @@
|
|
|
1
|
-
import type {
|
|
2
|
-
QualityCheckResult,
|
|
3
|
-
VrtSnapshot,
|
|
4
|
-
VrtDiff,
|
|
5
|
-
DepGraph,
|
|
6
|
-
AffectedComponent,
|
|
7
|
-
} from "./types.ts";
|
|
8
|
-
import { detectWhiteout, detectEmptyContent } from "./heatmap.ts";
|
|
9
|
-
import { decodePng } from "./png-utils.ts";
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Run all quality checks.
|
|
13
|
-
*/
|
|
14
|
-
export async function runQualityChecks(
|
|
15
|
-
snapshots: VrtSnapshot[],
|
|
16
|
-
diffs: VrtDiff[],
|
|
17
|
-
graph?: DepGraph,
|
|
18
|
-
affected?: AffectedComponent[]
|
|
19
|
-
): Promise<QualityCheckResult[]> {
|
|
20
|
-
const results: QualityCheckResult[] = [];
|
|
21
|
-
|
|
22
|
-
// Per-snapshot checks
|
|
23
|
-
for (const snapshot of snapshots) {
|
|
24
|
-
const snapshotChecks = await checkSnapshot(snapshot);
|
|
25
|
-
results.push(...snapshotChecks);
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
// Coverage check
|
|
29
|
-
if (graph && affected) {
|
|
30
|
-
results.push(checkCoverage(snapshots, affected));
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// Error state check (when diff exists)
|
|
34
|
-
for (const diff of diffs) {
|
|
35
|
-
if (diff.diffRatio > 0.5) {
|
|
36
|
-
results.push({
|
|
37
|
-
check: "layout-shift",
|
|
38
|
-
passed: false,
|
|
39
|
-
details: `Large visual change detected in "${diff.snapshot.testTitle}": ${(diff.diffRatio * 100).toFixed(1)}% of pixels changed. ${diff.regions.length} region(s) affected.`,
|
|
40
|
-
severity: "warning",
|
|
41
|
-
});
|
|
42
|
-
}
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
return results;
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/**
|
|
49
|
-
* Per-snapshot quality checks.
|
|
50
|
-
*/
|
|
51
|
-
async function checkSnapshot(
|
|
52
|
-
snapshot: VrtSnapshot
|
|
53
|
-
): Promise<QualityCheckResult[]> {
|
|
54
|
-
const results: QualityCheckResult[] = [];
|
|
55
|
-
|
|
56
|
-
try {
|
|
57
|
-
const png = await decodePng(snapshot.screenshotPath);
|
|
58
|
-
|
|
59
|
-
// Whiteout detection
|
|
60
|
-
const whiteout = detectWhiteout(png);
|
|
61
|
-
results.push({
|
|
62
|
-
check: "whiteout",
|
|
63
|
-
passed: !whiteout.isWhiteout,
|
|
64
|
-
details: whiteout.isWhiteout
|
|
65
|
-
? `Whiteout detected in "${snapshot.testTitle}": ${(whiteout.whiteRatio * 100).toFixed(1)}% white pixels`
|
|
66
|
-
: `OK: ${(whiteout.whiteRatio * 100).toFixed(1)}% white pixels`,
|
|
67
|
-
severity: whiteout.isWhiteout ? "error" : "info",
|
|
68
|
-
});
|
|
69
|
-
|
|
70
|
-
// Empty content detection
|
|
71
|
-
const empty = detectEmptyContent(png);
|
|
72
|
-
results.push({
|
|
73
|
-
check: "empty-content",
|
|
74
|
-
passed: !empty.isEmpty,
|
|
75
|
-
details: empty.isEmpty
|
|
76
|
-
? `Empty content detected in "${snapshot.testTitle}": only ${empty.uniqueColors} unique colors`
|
|
77
|
-
: `OK: ${empty.uniqueColors} unique colors`,
|
|
78
|
-
severity: empty.isEmpty ? "error" : "info",
|
|
79
|
-
});
|
|
80
|
-
|
|
81
|
-
// Error state detection (red pixel ratio)
|
|
82
|
-
const errorState = detectErrorIndicators(png);
|
|
83
|
-
results.push({
|
|
84
|
-
check: "error-state",
|
|
85
|
-
passed: !errorState.hasError,
|
|
86
|
-
details: errorState.hasError
|
|
87
|
-
? `Possible error state in "${snapshot.testTitle}": ${errorState.reason}`
|
|
88
|
-
: "OK: no error indicators detected",
|
|
89
|
-
severity: errorState.hasError ? "warning" : "info",
|
|
90
|
-
});
|
|
91
|
-
} catch (err) {
|
|
92
|
-
results.push({
|
|
93
|
-
check: "whiteout",
|
|
94
|
-
passed: false,
|
|
95
|
-
details: `Failed to analyze screenshot "${snapshot.testTitle}": ${err}`,
|
|
96
|
-
severity: "error",
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
return results;
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/**
|
|
104
|
-
* Detect visual indicators of error states.
|
|
105
|
-
* - High red pixel ratio (error messages, validation errors)
|
|
106
|
-
* - Yellow/orange warning colors
|
|
107
|
-
*/
|
|
108
|
-
function detectErrorIndicators(data: {
|
|
109
|
-
width: number;
|
|
110
|
-
height: number;
|
|
111
|
-
data: Uint8Array;
|
|
112
|
-
}): { hasError: boolean; reason: string } {
|
|
113
|
-
const { width, height, data: pixels } = data;
|
|
114
|
-
const total = width * height;
|
|
115
|
-
let redCount = 0;
|
|
116
|
-
let yellowCount = 0;
|
|
117
|
-
|
|
118
|
-
const stride = Math.max(1, Math.floor(total / 20000));
|
|
119
|
-
let sampled = 0;
|
|
120
|
-
|
|
121
|
-
for (let i = 0; i < total; i += stride) {
|
|
122
|
-
const offset = i * 4;
|
|
123
|
-
const r = pixels[offset];
|
|
124
|
-
const g = pixels[offset + 1];
|
|
125
|
-
const b = pixels[offset + 2];
|
|
126
|
-
sampled++;
|
|
127
|
-
|
|
128
|
-
// Red (error): high R, low G, low B
|
|
129
|
-
if (r > 180 && g < 80 && b < 80) {
|
|
130
|
-
redCount++;
|
|
131
|
-
}
|
|
132
|
-
// Yellow/orange (warning): high R, mid-high G, low B
|
|
133
|
-
if (r > 200 && g > 120 && g < 220 && b < 60) {
|
|
134
|
-
yellowCount++;
|
|
135
|
-
}
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
const redRatio = redCount / sampled;
|
|
139
|
-
const yellowRatio = yellowCount / sampled;
|
|
140
|
-
|
|
141
|
-
if (redRatio > 0.05) {
|
|
142
|
-
return {
|
|
143
|
-
hasError: true,
|
|
144
|
-
reason: `${(redRatio * 100).toFixed(1)}% red pixels (possible error state)`,
|
|
145
|
-
};
|
|
146
|
-
}
|
|
147
|
-
if (yellowRatio > 0.1) {
|
|
148
|
-
return {
|
|
149
|
-
hasError: true,
|
|
150
|
-
reason: `${(yellowRatio * 100).toFixed(1)}% yellow/orange pixels (possible warning state)`,
|
|
151
|
-
};
|
|
152
|
-
}
|
|
153
|
-
|
|
154
|
-
return { hasError: false, reason: "" };
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
/**
|
|
158
|
-
* VRT coverage: ratio of affected components that have VRT snapshots.
|
|
159
|
-
*/
|
|
160
|
-
function checkCoverage(
|
|
161
|
-
snapshots: VrtSnapshot[],
|
|
162
|
-
affected: AffectedComponent[]
|
|
163
|
-
): QualityCheckResult {
|
|
164
|
-
if (affected.length === 0) {
|
|
165
|
-
return {
|
|
166
|
-
check: "coverage",
|
|
167
|
-
passed: true,
|
|
168
|
-
details: "No affected components to cover",
|
|
169
|
-
severity: "info",
|
|
170
|
-
};
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
// Check if snapshot testTitle/testId contains the component name
|
|
174
|
-
const snapshotNames = new Set(
|
|
175
|
-
snapshots.flatMap((s) => [s.testTitle.toLowerCase(), s.testId.toLowerCase()])
|
|
176
|
-
);
|
|
177
|
-
|
|
178
|
-
const covered: string[] = [];
|
|
179
|
-
const uncovered: string[] = [];
|
|
180
|
-
|
|
181
|
-
for (const comp of affected) {
|
|
182
|
-
// Match by component filename (without extension)
|
|
183
|
-
const name = comp.node.id
|
|
184
|
-
.replace(/\.[^.]+$/, "")
|
|
185
|
-
.split("/")
|
|
186
|
-
.pop()!
|
|
187
|
-
.toLowerCase();
|
|
188
|
-
|
|
189
|
-
const isCovered = [...snapshotNames].some(
|
|
190
|
-
(sn) => sn.includes(name) || name.includes(sn)
|
|
191
|
-
);
|
|
192
|
-
|
|
193
|
-
if (isCovered) {
|
|
194
|
-
covered.push(comp.node.id);
|
|
195
|
-
} else {
|
|
196
|
-
uncovered.push(comp.node.id);
|
|
197
|
-
}
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
const ratio = covered.length / affected.length;
|
|
201
|
-
const passed = ratio >= 0.8; // 80% coverage threshold
|
|
202
|
-
|
|
203
|
-
return {
|
|
204
|
-
check: "coverage",
|
|
205
|
-
passed,
|
|
206
|
-
details: `VRT coverage: ${covered.length}/${affected.length} (${(ratio * 100).toFixed(0)}%) affected components covered.${uncovered.length > 0 ? ` Uncovered: ${uncovered.join(", ")}` : ""}`,
|
|
207
|
-
severity: passed ? "info" : "warning",
|
|
208
|
-
};
|
|
209
|
-
}
|
package/src/region-classify.ts
DELETED
|
@@ -1,189 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Region content-type classifier.
|
|
3
|
-
*
|
|
4
|
-
* Given a rectangular region of an image (e.g. a heatmap cluster or
|
|
5
|
-
* a component bbox), classify what it most likely represents:
|
|
6
|
-
* - `text` — horizontal text rows (high horizontal entropy,
|
|
7
|
-
* consistent row stripe pattern)
|
|
8
|
-
* - `filled-rect` — solid color block (button, badge, banner)
|
|
9
|
-
* - `icon` — small compact graphic (2-4 colors, square-ish)
|
|
10
|
-
* - `image` — high color variance, no stripe pattern
|
|
11
|
-
* - `unknown` — region too small or empty
|
|
12
|
-
*
|
|
13
|
-
* Pure pixel heuristic — no DOM access. Closes the "is this region
|
|
14
|
-
* text or a filled rectangle?" question called out by subagent G v2
|
|
15
|
-
* dogfood: "the heatmap gives (x, y, W×H) but no clue what the
|
|
16
|
-
* region is."
|
|
17
|
-
*/
|
|
18
|
-
export type RegionKind = "text" | "filled-rect" | "icon" | "image" | "unknown";
|
|
19
|
-
|
|
20
|
-
export interface RegionClassification {
|
|
21
|
-
kind: RegionKind;
|
|
22
|
-
/** Confidence ∈ [0, 1]. */
|
|
23
|
-
confidence: number;
|
|
24
|
-
/** Diagnostics used to make the decision. */
|
|
25
|
-
features: {
|
|
26
|
-
colorCount: number;
|
|
27
|
-
/** Standard deviation of luminance across the region. Low = uniform fill. */
|
|
28
|
-
lumaStd: number;
|
|
29
|
-
/** Number of distinct horizontal "stripes" — dark-row clusters. */
|
|
30
|
-
stripeRows: number;
|
|
31
|
-
/** Aspect ratio width/height. */
|
|
32
|
-
aspect: number;
|
|
33
|
-
/** Width × height. */
|
|
34
|
-
area: number;
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
export interface ClassifyOptions {
|
|
39
|
-
/** Quantization bits per channel for color counting. Default 4. */
|
|
40
|
-
bitsPerChannel?: number;
|
|
41
|
-
/** Stride for stripe-row scanning. Default 1. */
|
|
42
|
-
stripeStride?: number;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Classify a region of an RGBA image. The region is given by
|
|
47
|
-
* `top, left, width, height` (clamped to image bounds).
|
|
48
|
-
*/
|
|
49
|
-
export function classifyRegion(
|
|
50
|
-
data: Uint8Array,
|
|
51
|
-
imageWidth: number,
|
|
52
|
-
imageHeight: number,
|
|
53
|
-
region: { top: number; left: number; width: number; height: number },
|
|
54
|
-
options: ClassifyOptions = {},
|
|
55
|
-
): RegionClassification {
|
|
56
|
-
const bits = options.bitsPerChannel ?? 4;
|
|
57
|
-
const stripeStride = options.stripeStride ?? 1;
|
|
58
|
-
const shift = 8 - bits;
|
|
59
|
-
const bucketCount = 1 << bits;
|
|
60
|
-
|
|
61
|
-
const x0 = Math.max(0, region.left);
|
|
62
|
-
const y0 = Math.max(0, region.top);
|
|
63
|
-
const x1 = Math.min(imageWidth, region.left + region.width);
|
|
64
|
-
const y1 = Math.min(imageHeight, region.top + region.height);
|
|
65
|
-
const W = x1 - x0;
|
|
66
|
-
const H = y1 - y0;
|
|
67
|
-
if (W <= 1 || H <= 1) {
|
|
68
|
-
return {
|
|
69
|
-
kind: "unknown",
|
|
70
|
-
confidence: 1,
|
|
71
|
-
features: { colorCount: 0, lumaStd: 0, stripeRows: 0, aspect: 0, area: 0 },
|
|
72
|
-
};
|
|
73
|
-
}
|
|
74
|
-
|
|
75
|
-
// Single-pass aggregation:
|
|
76
|
-
// - color histogram (quantized) for colorCount
|
|
77
|
-
// - per-pixel luma → row-mean & total mean/std
|
|
78
|
-
// - per-row luma → stripe detection
|
|
79
|
-
const histogram = new Set<number>();
|
|
80
|
-
const rowMeanLuma = new Float32Array(H);
|
|
81
|
-
let totalSum = 0, totalSumSq = 0;
|
|
82
|
-
let n = 0;
|
|
83
|
-
for (let yy = 0; yy < H; yy++) {
|
|
84
|
-
const y = y0 + yy;
|
|
85
|
-
let rowSum = 0;
|
|
86
|
-
for (let xx = 0; xx < W; xx++) {
|
|
87
|
-
const x = x0 + xx;
|
|
88
|
-
const i = (y * imageWidth + x) * 4;
|
|
89
|
-
if (data[i + 3]! === 0) continue;
|
|
90
|
-
const r = data[i]!, g = data[i + 1]!, b = data[i + 2]!;
|
|
91
|
-
const key = ((r >> shift) << (2 * bits)) | ((g >> shift) << bits) | (b >> shift);
|
|
92
|
-
histogram.add(key);
|
|
93
|
-
const L = 0.299 * r + 0.587 * g + 0.114 * b;
|
|
94
|
-
rowSum += L;
|
|
95
|
-
totalSum += L;
|
|
96
|
-
totalSumSq += L * L;
|
|
97
|
-
n++;
|
|
98
|
-
}
|
|
99
|
-
rowMeanLuma[yy] = W > 0 ? rowSum / W : 0;
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
if (n === 0) {
|
|
103
|
-
return {
|
|
104
|
-
kind: "unknown",
|
|
105
|
-
confidence: 1,
|
|
106
|
-
features: { colorCount: 0, lumaStd: 0, stripeRows: 0, aspect: W / H, area: W * H },
|
|
107
|
-
};
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
const colorCount = histogram.size;
|
|
111
|
-
const mean = totalSum / n;
|
|
112
|
-
const variance = totalSumSq / n - mean * mean;
|
|
113
|
-
const lumaStd = Math.sqrt(Math.max(0, variance));
|
|
114
|
-
|
|
115
|
-
// Stripe detection: count alternating dark/light row transitions.
|
|
116
|
-
// A row is "dark" if rowMeanLuma is meaningfully below the region's
|
|
117
|
-
// mean luma. Multiple distinct dark stripes → likely text.
|
|
118
|
-
const stripeDip = 12;
|
|
119
|
-
let stripeRows = 0;
|
|
120
|
-
let inDarkRun = false;
|
|
121
|
-
for (let yy = 0; yy < H; yy += stripeStride) {
|
|
122
|
-
const isDark = mean - rowMeanLuma[yy]! >= stripeDip;
|
|
123
|
-
if (isDark && !inDarkRun) {
|
|
124
|
-
stripeRows++;
|
|
125
|
-
inDarkRun = true;
|
|
126
|
-
} else if (!isDark && inDarkRun) {
|
|
127
|
-
inDarkRun = false;
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
const aspect = W / H;
|
|
132
|
-
const area = W * H;
|
|
133
|
-
|
|
134
|
-
// Heuristic classification:
|
|
135
|
-
// text — multiple stripes (≥ 2 alternating dark-row runs)
|
|
136
|
-
// AND aspect ratio not tiny (text bands tend to be
|
|
137
|
-
// wider than tall, but a single short word can be
|
|
138
|
-
// ~square)
|
|
139
|
-
// filled-rect — colorCount ≤ 4 AND lumaStd < 20 (essentially
|
|
140
|
-
// uniform fill)
|
|
141
|
-
// icon — small region (area < 4000), colorCount ≤ 16,
|
|
142
|
-
// aspect 0.5-2 (square-ish)
|
|
143
|
-
// image — colorCount > 16 AND not striped → textured
|
|
144
|
-
// unknown — none of the above hold confidently
|
|
145
|
-
let kind: RegionKind = "unknown";
|
|
146
|
-
let confidence = 0.5;
|
|
147
|
-
// Thresholds tuned against real anti-aliased rendering — a "uniform"
|
|
148
|
-
// button has ~30-80 quantized colors from AA on text + corners, not
|
|
149
|
-
// the ~4 a naive view would suggest. Buckets calibrated against
|
|
150
|
-
// system-ui at 14-40 px on light bg.
|
|
151
|
-
|
|
152
|
-
// Tiny region — likely icon or single character.
|
|
153
|
-
if (area < 2000 && aspect > 0.4 && aspect < 2.5) {
|
|
154
|
-
kind = "icon";
|
|
155
|
-
confidence = 0.65;
|
|
156
|
-
}
|
|
157
|
-
// Multiple distinct dark stripes → text.
|
|
158
|
-
else if (stripeRows >= 2) {
|
|
159
|
-
kind = "text";
|
|
160
|
-
confidence = Math.min(1, 0.55 + stripeRows * 0.08);
|
|
161
|
-
}
|
|
162
|
-
// Truly uniform fill (single color block, no text overlay).
|
|
163
|
-
else if (colorCount <= 8 && lumaStd < 12) {
|
|
164
|
-
kind = "filled-rect";
|
|
165
|
-
confidence = 0.9;
|
|
166
|
-
}
|
|
167
|
-
// Button-/badge-like: bounded color count, narrow luma std (AA on
|
|
168
|
-
// text inside a solid fill is the main source of variation).
|
|
169
|
-
else if (colorCount <= 120 && lumaStd < 45) {
|
|
170
|
-
kind = "filled-rect";
|
|
171
|
-
confidence = 0.65;
|
|
172
|
-
}
|
|
173
|
-
// Single-stripe text band — common short labels / single-line text.
|
|
174
|
-
else if (stripeRows === 1) {
|
|
175
|
-
kind = "text";
|
|
176
|
-
confidence = 0.55;
|
|
177
|
-
}
|
|
178
|
-
// Many colors + no stripe structure → textured / image content.
|
|
179
|
-
else if (colorCount > 200) {
|
|
180
|
-
kind = "image";
|
|
181
|
-
confidence = 0.6;
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
return {
|
|
185
|
-
kind,
|
|
186
|
-
confidence,
|
|
187
|
-
features: { colorCount, lumaStd: Number(lumaStd.toFixed(1)), stripeRows, aspect: Number(aspect.toFixed(2)), area },
|
|
188
|
-
};
|
|
189
|
-
}
|