@scoriiu/fenshot 0.1.0 → 0.1.2
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 +3 -1
- package/dist/detect.js +75 -55
- package/dist/recognize.d.ts +7 -0
- package/dist/recognize.js +47 -7
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -96,6 +96,8 @@ Compose a full analyzable FEN from a bare placement. Castling rights are inferre
|
|
|
96
96
|
|
|
97
97
|
Versus the legacy tensorflow_chessbot model on our real-screenshot eval set: the legacy model misread 34 tiles on one fixture and 5 tiles on a dimmed reddit screenshot; this model ships at zero wrong tiles on all positive cases with negatives still rejected.
|
|
98
98
|
|
|
99
|
+
The model is reproducible, not just downloadable: the full training pipeline (asset fetcher, corpus generator, training script, and an eval gate that runs the real recognition pipeline against the golden fixtures) lives in [`tools/tile-classifier`](https://github.com/scoriiu/fenshot/tree/main/tools/tile-classifier).
|
|
100
|
+
|
|
99
101
|
## Limitations
|
|
100
102
|
|
|
101
103
|
- 2D screenshots and diagrams only. 3D piece sets with perspective overhang are out of scope for now.
|
|
@@ -105,7 +107,7 @@ Versus the legacy tensorflow_chessbot model on our real-screenshot eval set: the
|
|
|
105
107
|
## Credits
|
|
106
108
|
|
|
107
109
|
- Board detection algorithm: [Elucidation/tensorflow_chessbot](https://github.com/Elucidation/tensorflow_chessbot) (MIT).
|
|
108
|
-
- Piece set and board theme assets used as training input: lichess ([lila](https://github.com/lichess-org/lila), free licenses)
|
|
110
|
+
- Piece set and board theme assets used as training input: lichess ([lila](https://github.com/lichess-org/lila), free licenses). The corpus also includes other sites' themes (including chess.com) so the recognizer reads their screenshots too; those assets are training input only and are never redistributed, only trained weights ship.
|
|
109
111
|
- Built and maintained by [coachess.app](https://coachess.app).
|
|
110
112
|
|
|
111
113
|
## License
|
package/dist/detect.js
CHANGED
|
@@ -184,11 +184,17 @@ function checkerboardScore(img, x0, y0, x1, y1) {
|
|
|
184
184
|
}
|
|
185
185
|
return Math.abs(score);
|
|
186
186
|
}
|
|
187
|
-
|
|
187
|
+
/** How many candidate line sequences the one-axis reconstruction
|
|
188
|
+
* arbitrates between. Piece edges and adjacent UI lines can form a
|
|
189
|
+
* shifted arithmetic sequence whose peak values narrowly beat the true
|
|
190
|
+
* grid's; checkerboard correlation separates them reliably, so several
|
|
191
|
+
* candidates are kept instead of trusting peak strength alone. */
|
|
192
|
+
const MAX_CANDIDATE_SEQS = 5;
|
|
193
|
+
function rankedPeakSequences(hough) {
|
|
188
194
|
const suppressed = nonmaxSuppress(hough);
|
|
189
195
|
const peak = max(suppressed, 0, suppressed.length);
|
|
190
196
|
if (peak <= 0)
|
|
191
|
-
return
|
|
197
|
+
return [];
|
|
192
198
|
const positions = [];
|
|
193
199
|
const values = [];
|
|
194
200
|
for (let i = 0; i < suppressed.length; i++) {
|
|
@@ -200,20 +206,26 @@ function bestPeakSequence(hough) {
|
|
|
200
206
|
}
|
|
201
207
|
const seqs = getAllSequences(positions);
|
|
202
208
|
if (seqs.length === 0)
|
|
203
|
-
return
|
|
209
|
+
return [];
|
|
204
210
|
const valueAt = new Map(positions.map((p, i) => [p, values[i]]));
|
|
205
|
-
|
|
206
|
-
let bestScore = -Infinity;
|
|
207
|
-
for (const seq of seqs) {
|
|
211
|
+
const scored = seqs.map((seq) => {
|
|
208
212
|
const vals = seq.map((p) => valueAt.get(p) ?? 0);
|
|
209
213
|
const trimmed = trimSequence(seq, vals);
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
+
return {
|
|
215
|
+
candidate: { trimmed: trimmed.seq, full: seq },
|
|
216
|
+
score: trimmed.vals.reduce((a, b) => a + b, 0) / trimmed.vals.length,
|
|
217
|
+
};
|
|
218
|
+
});
|
|
219
|
+
scored.sort((a, b) => b.score - a.score);
|
|
220
|
+
const unique = [];
|
|
221
|
+
for (const { candidate } of scored) {
|
|
222
|
+
if (!unique.some((u) => u.full.length === candidate.full.length && u.full.every((v, i) => v === candidate.full[i]))) {
|
|
223
|
+
unique.push(candidate);
|
|
214
224
|
}
|
|
225
|
+
if (unique.length >= MAX_CANDIDATE_SEQS)
|
|
226
|
+
break;
|
|
215
227
|
}
|
|
216
|
-
return
|
|
228
|
+
return unique;
|
|
217
229
|
}
|
|
218
230
|
/**
|
|
219
231
|
* Grid-snap refinement candidate: the peak-sequence search can lock
|
|
@@ -264,59 +276,65 @@ export function snapCorners(img, box) {
|
|
|
264
276
|
* correlation is strongest. Returns null if nothing scores well, so this
|
|
265
277
|
* cannot manufacture a board out of noise — checkerboardScore arbitrates.
|
|
266
278
|
*/
|
|
267
|
-
function reconstructSquareBoard(img, good, axis
|
|
279
|
+
function reconstructSquareBoard(img, good, axis) {
|
|
268
280
|
const tile = median(good.slice(1).map((v, i) => v - good[i]));
|
|
269
281
|
if (!(tile > 0))
|
|
270
282
|
return null;
|
|
271
|
-
// The good sequence
|
|
272
|
-
//
|
|
273
|
-
//
|
|
274
|
-
//
|
|
283
|
+
// The good-axis sequence is ambiguous: its lines can be the 7 INNER
|
|
284
|
+
// grid lines (extent = one tile beyond each end), can include one or
|
|
285
|
+
// both OUTER edges, or can include phantom lines from adjacent UI.
|
|
286
|
+
// Enumerate the same candidates the two-axis path considers: every
|
|
287
|
+
// 7-line sub-grid padded by one tile, plus the whole span read as
|
|
288
|
+
// outer-edge-to-outer-edge. Checkerboard correlation arbitrates.
|
|
275
289
|
const gA = Math.round(good[0]);
|
|
276
290
|
const gB = Math.round(good[good.length - 1]);
|
|
277
|
-
|
|
278
|
-
if (span <= 0)
|
|
291
|
+
if (gB - gA <= 0)
|
|
279
292
|
return null;
|
|
293
|
+
const pad = Math.round(tile);
|
|
294
|
+
const extents = [[gA, gB]];
|
|
295
|
+
for (let k = 0; k + 7 <= good.length; k++) {
|
|
296
|
+
const e = [Math.round(good[k]) - pad, Math.round(good[k + 6]) + pad];
|
|
297
|
+
if (!extents.some(([a, b]) => Math.abs(a - e[0]) <= 2 && Math.abs(b - e[1]) <= 2)) {
|
|
298
|
+
extents.push(e);
|
|
299
|
+
}
|
|
300
|
+
}
|
|
280
301
|
const limit = axis === "x" ? img.height : img.width;
|
|
281
|
-
const step = Math.max(2, Math.round(tile / 8));
|
|
282
|
-
// If the weak axis detected outer edges (even though its internal lines
|
|
283
|
-
// were lost), bias the search to start positions whose span endpoints
|
|
284
|
-
// land near a detected edge — these are the true board boundaries.
|
|
285
|
-
const nearEdge = (a, b) => weakPeaks.length > 0 &&
|
|
286
|
-
weakPeaks.some((p) => Math.abs(p - a) <= tile) &&
|
|
287
|
-
weakPeaks.some((p) => Math.abs(p - b) <= tile);
|
|
288
302
|
let best = null;
|
|
289
303
|
let bestScore = -Infinity;
|
|
290
|
-
for (
|
|
291
|
-
const
|
|
292
|
-
const
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
bestScore
|
|
301
|
-
|
|
304
|
+
for (const [eA, eB] of extents) {
|
|
305
|
+
const span = eB - eA;
|
|
306
|
+
const step = Math.max(2, Math.round(tile / 8));
|
|
307
|
+
for (let start = -span; start <= limit; start += step) {
|
|
308
|
+
const wA = start;
|
|
309
|
+
const wB = start + span;
|
|
310
|
+
const box = axis === "x"
|
|
311
|
+
? { x0: eA, y0: wA, x1: eB, y1: wB }
|
|
312
|
+
: { x0: wA, y0: eA, x1: wB, y1: eB };
|
|
313
|
+
const score = checkerboardScore(img, box.x0, box.y0, box.x1, box.y1);
|
|
314
|
+
if (score > bestScore) {
|
|
315
|
+
bestScore = score;
|
|
316
|
+
best = box;
|
|
317
|
+
}
|
|
302
318
|
}
|
|
303
319
|
}
|
|
304
|
-
return best;
|
|
320
|
+
return best ? { box: best, score: bestScore } : null;
|
|
305
321
|
}
|
|
306
|
-
/**
|
|
307
|
-
*
|
|
308
|
-
*
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
const
|
|
315
|
-
|
|
316
|
-
if (
|
|
317
|
-
|
|
322
|
+
/** One-axis fallback across ALL candidate line sequences of the good
|
|
323
|
+
* axis: a shifted sequence can out-score the true grid on raw peak
|
|
324
|
+
* strength, so every candidate is reconstructed (from its FULL
|
|
325
|
+
* untrimmed line list) and the checkerboard correlation picks the
|
|
326
|
+
* winner. */
|
|
327
|
+
function reconstructFromCandidates(img, candidates, axis) {
|
|
328
|
+
let best = null;
|
|
329
|
+
let bestScore = -Infinity;
|
|
330
|
+
for (const { full } of candidates) {
|
|
331
|
+
const r = reconstructSquareBoard(img, full, axis);
|
|
332
|
+
if (r && r.score > bestScore) {
|
|
333
|
+
bestScore = r.score;
|
|
334
|
+
best = r.box;
|
|
335
|
+
}
|
|
318
336
|
}
|
|
319
|
-
return
|
|
337
|
+
return best;
|
|
320
338
|
}
|
|
321
339
|
export function findChessboardCorners(img) {
|
|
322
340
|
const gradY = gradientRows(img);
|
|
@@ -325,15 +343,17 @@ export function findChessboardCorners(img) {
|
|
|
325
343
|
const houghCols = houghResponse(gradX, img.width, img.height, "cols");
|
|
326
344
|
// Rows hough peaks = y coordinates of horizontal lines;
|
|
327
345
|
// cols hough peaks = x coordinates of vertical lines.
|
|
328
|
-
const
|
|
329
|
-
const
|
|
346
|
+
const candidatesY = rankedPeakSequences(houghRows);
|
|
347
|
+
const candidatesX = rankedPeakSequences(houghCols);
|
|
348
|
+
const linesY = candidatesY[0]?.trimmed ?? null;
|
|
349
|
+
const linesX = candidatesX[0]?.trimmed ?? null;
|
|
330
350
|
// One axis clean, the other lost to low contrast / piece-edge noise:
|
|
331
351
|
// rebuild the square board from the good axis. snapCorners (called by
|
|
332
352
|
// the recognizer) then refines the alignment a few pixels either way.
|
|
333
353
|
if (linesX && !linesY)
|
|
334
|
-
return
|
|
354
|
+
return reconstructFromCandidates(img, candidatesX, "x");
|
|
335
355
|
if (linesY && !linesX)
|
|
336
|
-
return
|
|
356
|
+
return reconstructFromCandidates(img, candidatesY, "y");
|
|
337
357
|
if (!linesX || !linesY)
|
|
338
358
|
return null;
|
|
339
359
|
const dx = median(linesX.slice(1).map((v, i) => v - linesX[i]));
|
package/dist/recognize.d.ts
CHANGED
|
@@ -56,6 +56,13 @@ export type TileClassifier = (corners: BoardCorners) => Promise<RecognitionResul
|
|
|
56
56
|
* the grid-snap candidate. Platform-independent (no canvas, no ONNX);
|
|
57
57
|
* the classifier is injected. Exercised directly by the golden test
|
|
58
58
|
* suite and usable from Node with any rasterizer.
|
|
59
|
+
*
|
|
60
|
+
* An all-empty read is never the board the user means (an empty board
|
|
61
|
+
* has no position to analyze, and whole-screen captures can include
|
|
62
|
+
* decorative or placeholder boards). When a pass reads empty, the
|
|
63
|
+
* region is masked and the scan repeats, preferring a piece-bearing
|
|
64
|
+
* board found later. The empty read is still returned when nothing
|
|
65
|
+
* better exists.
|
|
59
66
|
*/
|
|
60
67
|
export declare function recognizeGray(gray: GrayImage, classify: TileClassifier): Promise<BoardScanResult | null>;
|
|
61
68
|
export declare function createRecognizer(options: RecognizerOptions): Recognizer;
|
package/dist/recognize.js
CHANGED
|
@@ -43,13 +43,13 @@ function imageToGray(img) {
|
|
|
43
43
|
const data = ctx.getImageData(0, 0, cw, ch);
|
|
44
44
|
return rgbaToGray(data.data, cw, ch);
|
|
45
45
|
}
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
|
|
52
|
-
|
|
46
|
+
const EMPTY_PLACEMENT = "8/8/8/8/8/8/8/8";
|
|
47
|
+
/** Detection passes per image: the first board found can be an empty
|
|
48
|
+
* decorative board (a page can contain several board-like regions,
|
|
49
|
+
* including this library's own UI); masking it and rescanning finds
|
|
50
|
+
* the board the user actually means. */
|
|
51
|
+
const MAX_SCAN_PASSES = 3;
|
|
52
|
+
async function scanOnce(gray, classify) {
|
|
53
53
|
const corners = findChessboardCorners(gray);
|
|
54
54
|
if (!corners)
|
|
55
55
|
return null;
|
|
@@ -72,6 +72,46 @@ export async function recognizeGray(gray, classify) {
|
|
|
72
72
|
reliable: best.minConfidence >= CONFIDENCE_FLOOR,
|
|
73
73
|
};
|
|
74
74
|
}
|
|
75
|
+
/** Flatten a region so its gradients vanish and the detector cannot
|
|
76
|
+
* lock onto it again on the next pass. */
|
|
77
|
+
function maskRegion(gray, box) {
|
|
78
|
+
const data = Float32Array.from(gray.data);
|
|
79
|
+
const x0 = Math.max(0, Math.floor(box.x0));
|
|
80
|
+
const y0 = Math.max(0, Math.floor(box.y0));
|
|
81
|
+
const x1 = Math.min(gray.width, Math.ceil(box.x1));
|
|
82
|
+
const y1 = Math.min(gray.height, Math.ceil(box.y1));
|
|
83
|
+
for (let y = y0; y < y1; y++) {
|
|
84
|
+
data.fill(128, y * gray.width + x0, y * gray.width + x1);
|
|
85
|
+
}
|
|
86
|
+
return { data, width: gray.width, height: gray.height };
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* Pure recognition core: detect corners, classify, arbitrate against
|
|
90
|
+
* the grid-snap candidate. Platform-independent (no canvas, no ONNX);
|
|
91
|
+
* the classifier is injected. Exercised directly by the golden test
|
|
92
|
+
* suite and usable from Node with any rasterizer.
|
|
93
|
+
*
|
|
94
|
+
* An all-empty read is never the board the user means (an empty board
|
|
95
|
+
* has no position to analyze, and whole-screen captures can include
|
|
96
|
+
* decorative or placeholder boards). When a pass reads empty, the
|
|
97
|
+
* region is masked and the scan repeats, preferring a piece-bearing
|
|
98
|
+
* board found later. The empty read is still returned when nothing
|
|
99
|
+
* better exists.
|
|
100
|
+
*/
|
|
101
|
+
export async function recognizeGray(gray, classify) {
|
|
102
|
+
let working = gray;
|
|
103
|
+
let emptyFallback = null;
|
|
104
|
+
for (let pass = 0; pass < MAX_SCAN_PASSES; pass++) {
|
|
105
|
+
const result = await scanOnce(working, classify);
|
|
106
|
+
if (!result)
|
|
107
|
+
break;
|
|
108
|
+
if (result.placement !== EMPTY_PLACEMENT)
|
|
109
|
+
return result;
|
|
110
|
+
emptyFallback = emptyFallback ?? result;
|
|
111
|
+
working = maskRegion(working, result.corners);
|
|
112
|
+
}
|
|
113
|
+
return emptyFallback;
|
|
114
|
+
}
|
|
75
115
|
export function createRecognizer(options) {
|
|
76
116
|
let ortPromise = null;
|
|
77
117
|
let sessionPromise = null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@scoriiu/fenshot",
|
|
3
|
-
"version": "0.1.
|
|
3
|
+
"version": "0.1.2",
|
|
4
4
|
"description": "Screenshot in, FEN out. Chessboard recognition in the browser: detects the board in any screenshot or book diagram and reads the position with a CNN tile classifier.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|