@scoriiu/fenshot 0.1.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/LICENSE +21 -0
- package/README.md +113 -0
- package/dist/compose.d.ts +13 -0
- package/dist/compose.js +38 -0
- package/dist/detect.d.ts +47 -0
- package/dist/detect.js +365 -0
- package/dist/fen.d.ts +36 -0
- package/dist/fen.js +91 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.js +5 -0
- package/dist/recognize.d.ts +61 -0
- package/dist/recognize.js +116 -0
- package/dist/tiles.d.ts +19 -0
- package/dist/tiles.js +73 -0
- package/model/chess-tiles-v2.onnx +0 -0
- package/package.json +58 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 SORTINO LABS S.R.L. (coachess.app)
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
# fenshot
|
|
2
|
+
|
|
3
|
+
Screenshot in. FEN out.
|
|
4
|
+
|
|
5
|
+
[](https://github.com/scoriiu/fenshot/actions/workflows/ci.yml)
|
|
6
|
+
[](https://www.npmjs.com/package/@scoriiu/fenshot)
|
|
7
|
+
[](https://github.com/scoriiu/fenshot/blob/main/LICENSE)
|
|
8
|
+
|
|
9
|
+
Live demo: **[scoriiu.github.io/fenshot](https://scoriiu.github.io/fenshot/)**
|
|
10
|
+
|
|
11
|
+
Chessboard recognition that runs entirely in the browser: finds the board in any screenshot (chess.com, Lichess, book diagrams, reddit lightboxes), reads the position with a CNN tile classifier, and returns a FEN with per-tile confidence. No server, no account, nothing leaves the page.
|
|
12
|
+
|
|
13
|
+
Extracted from the position-import feature of [coachess.app](https://coachess.app), where it runs in production.
|
|
14
|
+
|
|
15
|
+
## Install
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm install @scoriiu/fenshot onnxruntime-web
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
Two static assets must be served by your app:
|
|
22
|
+
|
|
23
|
+
1. **The model** (1.3 MB): copy `node_modules/@scoriiu/fenshot/model/chess-tiles-v2.onnx` to your static dir.
|
|
24
|
+
2. **The onnxruntime wasm pair**: copy `ort-wasm-simd-threaded.mjs` and `ort-wasm-simd-threaded.wasm` from `node_modules/onnxruntime-web/dist/` to a static dir (e.g. `/ort/`).
|
|
25
|
+
|
|
26
|
+
Both are lazy-loaded on first scan, so users who never scan never download them.
|
|
27
|
+
|
|
28
|
+
## Quickstart
|
|
29
|
+
|
|
30
|
+
```ts
|
|
31
|
+
import { createRecognizer, resolveOrientation, placementToFen } from "@scoriiu/fenshot";
|
|
32
|
+
|
|
33
|
+
const recognizer = createRecognizer({
|
|
34
|
+
modelUrl: "/models/chess-tiles-v2.onnx",
|
|
35
|
+
wasmPaths: "/ort/",
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// e.g. from a paste event, drag-drop, or <input type="file">
|
|
39
|
+
const result = await recognizer.recognize(file);
|
|
40
|
+
|
|
41
|
+
if (!result) {
|
|
42
|
+
// no board-like structure found in the image
|
|
43
|
+
} else if (!result.reliable) {
|
|
44
|
+
// board found but the read is untrustworthy (foreign piece set,
|
|
45
|
+
// partial board): show an editor, not a wrong answer
|
|
46
|
+
} else {
|
|
47
|
+
const { placement, orientation } = resolveOrientation(result.placement);
|
|
48
|
+
const fen = placementToFen(placement, "w");
|
|
49
|
+
window.open(`https://lichess.org/analysis/standard/${fen.replaceAll(" ", "_")}`);
|
|
50
|
+
}
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## API
|
|
54
|
+
|
|
55
|
+
### `createRecognizer(options): Recognizer`
|
|
56
|
+
|
|
57
|
+
- `options.modelUrl` — URL of the served ONNX model.
|
|
58
|
+
- `options.wasmPaths` — directory URL of the onnxruntime wasm assets.
|
|
59
|
+
|
|
60
|
+
### `recognizer.recognize(source): Promise<BoardScanResult | null>`
|
|
61
|
+
|
|
62
|
+
`source` is an `HTMLImageElement`, `ImageBitmap`, `File`, or `Blob`. Resolves `null` when no chessboard is detected. Otherwise:
|
|
63
|
+
|
|
64
|
+
```ts
|
|
65
|
+
interface BoardScanResult {
|
|
66
|
+
placement: string; // FEN board field, always read white-at-bottom
|
|
67
|
+
meanConfidence: number; // mean per-tile classifier confidence
|
|
68
|
+
minConfidence: number; // worst tile
|
|
69
|
+
reliable: boolean; // minConfidence >= 0.7; if false, route to an editor
|
|
70
|
+
corners: BoardCorners; // board bounding box in image coordinates
|
|
71
|
+
}
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
### `recognizer.warmUp(): void`
|
|
75
|
+
|
|
76
|
+
Eagerly fetches and compiles the wasm runtime + model so the first scan is near-instant. Call it on scan intent (upload hover, textarea focus). Idempotent.
|
|
77
|
+
|
|
78
|
+
### `resolveOrientation(placement)`
|
|
79
|
+
|
|
80
|
+
The recognizer always reads tiles white-at-bottom. If the screenshot was from Black's point of view, pawn-advance direction gives it away; this returns the corrected placement and detected orientation.
|
|
81
|
+
|
|
82
|
+
### `placementToFen(placement, turn)` / `inferCastling(placement)`
|
|
83
|
+
|
|
84
|
+
Compose a full analyzable FEN from a bare placement. Castling rights are inferred from king/rook home squares (a screenshot carries no history); en passant and move counters get neutral defaults.
|
|
85
|
+
|
|
86
|
+
### Lower-level pieces
|
|
87
|
+
|
|
88
|
+
`findChessboardCorners`, `snapCorners`, `extractTiles`, `rgbaToGray`, `probsToPlacement`, `flipPlacement` are all exported for custom pipelines (e.g. Node with a raster library instead of canvas).
|
|
89
|
+
|
|
90
|
+
## How it works, and why it reads book diagrams
|
|
91
|
+
|
|
92
|
+
1. **Detection** is a TypeScript port of `chessboard_finder.py` from [Elucidation/tensorflow_chessbot](https://github.com/Elucidation/tensorflow_chessbot) (MIT): board edges produce evenly spaced gradient peaks; find the 7-line arithmetic sequence, pick the sub-grid that best matches an ideal checkerboard. One measured deviation: the reference's scale-dependent noise pre-gate is removed, it rejected page-wide screenshots whose board spans a small part of the frame, and against our fixture corpus it rejected nothing the sequence search did not already reject.
|
|
93
|
+
2. **Classification** is a from-scratch CNN (~330k params, 1.3 MB) trained on a fully synthetic corpus: known positions rendered across ~72 piece sets and ~55 board themes, plus procedural flat boards (any site's theme) and hatched book-diagram boards, with screenshot degradations baked in (JPEG artifacts q35-95, blur, dimming overlays, resize round-trips, corner jitter). Every tile's label is true by construction, and training tiles flow through the exact same extraction code that runs in the browser, so there is zero train/serve skew.
|
|
94
|
+
3. **Arbitration**: edge-rich board textures fool the gradient search by a quarter tile, so both the detected corners and a checkerboard grid-snap candidate are classified, and the read with higher mean confidence wins.
|
|
95
|
+
4. **Honesty**: `reliable: false` when any tile's confidence is below 0.7. A scanner that silently returns its best guess on a foreign piece set is worse than one that tells you to check.
|
|
96
|
+
|
|
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
|
+
|
|
99
|
+
## Limitations
|
|
100
|
+
|
|
101
|
+
- 2D screenshots and diagrams only. 3D piece sets with perspective overhang are out of scope for now.
|
|
102
|
+
- Browser-first: `recognize()` uses canvas + `createImageBitmap`. In Node, use the lower-level exports with your own rasterizer.
|
|
103
|
+
- The board must be roughly axis-aligned (screenshots are; photos of physical boards at an angle are not this tool).
|
|
104
|
+
|
|
105
|
+
## Credits
|
|
106
|
+
|
|
107
|
+
- 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) and chess.com (training input only, never redistributed; only trained weights ship).
|
|
109
|
+
- Built and maintained by [coachess.app](https://coachess.app).
|
|
110
|
+
|
|
111
|
+
## License
|
|
112
|
+
|
|
113
|
+
MIT
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FEN composition helpers for scan results. A recognizer returns a
|
|
3
|
+
* bare placement; these build a full analyzable FEN from it without
|
|
4
|
+
* pulling in a chess library.
|
|
5
|
+
*/
|
|
6
|
+
/** Derive castling rights from piece placement (screenshots carry no
|
|
7
|
+
* history). King + rook on their home squares keep the right;
|
|
8
|
+
* anything else drops it. */
|
|
9
|
+
export declare function inferCastling(placement: string): string;
|
|
10
|
+
/** Build a full FEN from a placement and side to move. Castling is
|
|
11
|
+
* inferred from home squares; en passant, halfmove and fullmove get
|
|
12
|
+
* neutral defaults (unknowable from a screenshot). */
|
|
13
|
+
export declare function placementToFen(placement: string, turn: "w" | "b"): string;
|
package/dist/compose.js
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* FEN composition helpers for scan results. A recognizer returns a
|
|
3
|
+
* bare placement; these build a full analyzable FEN from it without
|
|
4
|
+
* pulling in a chess library.
|
|
5
|
+
*/
|
|
6
|
+
function expandRank(rank) {
|
|
7
|
+
return rank.replace(/\d/g, (d) => ".".repeat(Number(d)));
|
|
8
|
+
}
|
|
9
|
+
/** Derive castling rights from piece placement (screenshots carry no
|
|
10
|
+
* history). King + rook on their home squares keep the right;
|
|
11
|
+
* anything else drops it. */
|
|
12
|
+
export function inferCastling(placement) {
|
|
13
|
+
const rows = placement.split("/");
|
|
14
|
+
if (rows.length !== 8)
|
|
15
|
+
return "-";
|
|
16
|
+
const white = expandRank(rows[7]);
|
|
17
|
+
const black = expandRank(rows[0]);
|
|
18
|
+
let rights = "";
|
|
19
|
+
if (white[4] === "K") {
|
|
20
|
+
if (white[7] === "R")
|
|
21
|
+
rights += "K";
|
|
22
|
+
if (white[0] === "R")
|
|
23
|
+
rights += "Q";
|
|
24
|
+
}
|
|
25
|
+
if (black[4] === "k") {
|
|
26
|
+
if (black[7] === "r")
|
|
27
|
+
rights += "k";
|
|
28
|
+
if (black[0] === "r")
|
|
29
|
+
rights += "q";
|
|
30
|
+
}
|
|
31
|
+
return rights || "-";
|
|
32
|
+
}
|
|
33
|
+
/** Build a full FEN from a placement and side to move. Castling is
|
|
34
|
+
* inferred from home squares; en passant, halfmove and fullmove get
|
|
35
|
+
* neutral defaults (unknowable from a screenshot). */
|
|
36
|
+
export function placementToFen(placement, turn) {
|
|
37
|
+
return `${placement} ${turn} ${inferCastling(placement)} - 0 1`;
|
|
38
|
+
}
|
package/dist/detect.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chessboard detection in a screenshot. Pure TypeScript port of
|
|
3
|
+
* chessboard_finder.py from Elucidation/tensorflow_chessbot (MIT).
|
|
4
|
+
*
|
|
5
|
+
* Input: grayscale image as Float32Array (0-255 values, row-major).
|
|
6
|
+
* Output: board bounding box in image coordinates, or null when no
|
|
7
|
+
* board-like gradient structure is found.
|
|
8
|
+
*
|
|
9
|
+
* Algorithm: image gradients split into +/- components, summed into
|
|
10
|
+
* 1D "hough" responses per row and per column. Board edges produce
|
|
11
|
+
* strong evenly spaced peaks; we find length-7+ arithmetic sequences
|
|
12
|
+
* of peaks (the 7 inner lines of an 8x8 board), then pick the 7x7
|
|
13
|
+
* sub-grid whose crop correlates best with an ideal checkerboard
|
|
14
|
+
* kernel. Faithful to the python reference, validated against its
|
|
15
|
+
* outputs in tests/unit/board-scan.test.ts.
|
|
16
|
+
*
|
|
17
|
+
* Deliberate deviation from the reference: its noise pre-gate
|
|
18
|
+
* (std(hough)/length >= 8000 on both axes) is removed. The metric is
|
|
19
|
+
* scale-dependent, so a page screenshot whose board spans only part
|
|
20
|
+
* of a wide frame fails the gate even when the board peaks are
|
|
21
|
+
* pristine (reddit-page-board.png in the test set). Measured against
|
|
22
|
+
* the fixture corpus the gate rejected nothing the arithmetic
|
|
23
|
+
* sequence search did not already reject.
|
|
24
|
+
*/
|
|
25
|
+
export interface BoardCorners {
|
|
26
|
+
x0: number;
|
|
27
|
+
y0: number;
|
|
28
|
+
x1: number;
|
|
29
|
+
y1: number;
|
|
30
|
+
}
|
|
31
|
+
export interface GrayImage {
|
|
32
|
+
data: Float32Array;
|
|
33
|
+
width: number;
|
|
34
|
+
height: number;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Grid-snap refinement candidate: the peak-sequence search can lock
|
|
38
|
+
* onto an offset grid when the board texture itself is edge-rich
|
|
39
|
+
* (hatched book diagrams put more gradient energy inside squares
|
|
40
|
+
* than on the grid lines). Checkerboard correlation peaks at true
|
|
41
|
+
* alignment on such boards, but is too crude to be trusted blindly
|
|
42
|
+
* on photo-textured boards, so callers treat the snapped box as a
|
|
43
|
+
* CANDIDATE alongside the raw one and let the tile classifier pick
|
|
44
|
+
* the alignment with higher mean confidence (recognize.ts).
|
|
45
|
+
*/
|
|
46
|
+
export declare function snapCorners(img: GrayImage, box: BoardCorners): BoardCorners;
|
|
47
|
+
export declare function findChessboardCorners(img: GrayImage): BoardCorners | null;
|
package/dist/detect.js
ADDED
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chessboard detection in a screenshot. Pure TypeScript port of
|
|
3
|
+
* chessboard_finder.py from Elucidation/tensorflow_chessbot (MIT).
|
|
4
|
+
*
|
|
5
|
+
* Input: grayscale image as Float32Array (0-255 values, row-major).
|
|
6
|
+
* Output: board bounding box in image coordinates, or null when no
|
|
7
|
+
* board-like gradient structure is found.
|
|
8
|
+
*
|
|
9
|
+
* Algorithm: image gradients split into +/- components, summed into
|
|
10
|
+
* 1D "hough" responses per row and per column. Board edges produce
|
|
11
|
+
* strong evenly spaced peaks; we find length-7+ arithmetic sequences
|
|
12
|
+
* of peaks (the 7 inner lines of an 8x8 board), then pick the 7x7
|
|
13
|
+
* sub-grid whose crop correlates best with an ideal checkerboard
|
|
14
|
+
* kernel. Faithful to the python reference, validated against its
|
|
15
|
+
* outputs in tests/unit/board-scan.test.ts.
|
|
16
|
+
*
|
|
17
|
+
* Deliberate deviation from the reference: its noise pre-gate
|
|
18
|
+
* (std(hough)/length >= 8000 on both axes) is removed. The metric is
|
|
19
|
+
* scale-dependent, so a page screenshot whose board spans only part
|
|
20
|
+
* of a wide frame fails the gate even when the board peaks are
|
|
21
|
+
* pristine (reddit-page-board.png in the test set). Measured against
|
|
22
|
+
* the fixture corpus the gate rejected nothing the arithmetic
|
|
23
|
+
* sequence search did not already reject.
|
|
24
|
+
*/
|
|
25
|
+
const PEAK_KEEP_RATIO = 0.2;
|
|
26
|
+
const MIN_SEQ_LEN = 7;
|
|
27
|
+
const ERR_PX = 5;
|
|
28
|
+
function max(arr, from, to) {
|
|
29
|
+
let m = -Infinity;
|
|
30
|
+
for (let i = from; i < to; i++)
|
|
31
|
+
if (arr[i] > m)
|
|
32
|
+
m = arr[i];
|
|
33
|
+
return m;
|
|
34
|
+
}
|
|
35
|
+
/** np.gradient semantics: central differences, one-sided at edges. */
|
|
36
|
+
function gradientRows(img) {
|
|
37
|
+
const { data, width, height } = img;
|
|
38
|
+
const out = new Float32Array(width * height);
|
|
39
|
+
for (let x = 0; x < width; x++) {
|
|
40
|
+
out[x] = data[width + x] - data[x];
|
|
41
|
+
const last = (height - 1) * width;
|
|
42
|
+
out[last + x] = data[last + x] - data[last - width + x];
|
|
43
|
+
}
|
|
44
|
+
for (let y = 1; y < height - 1; y++) {
|
|
45
|
+
for (let x = 0; x < width; x++) {
|
|
46
|
+
out[y * width + x] = (data[(y + 1) * width + x] - data[(y - 1) * width + x]) / 2;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
function gradientCols(img) {
|
|
52
|
+
const { data, width, height } = img;
|
|
53
|
+
const out = new Float32Array(width * height);
|
|
54
|
+
for (let y = 0; y < height; y++) {
|
|
55
|
+
const row = y * width;
|
|
56
|
+
out[row] = data[row + 1] - data[row];
|
|
57
|
+
out[row + width - 1] = data[row + width - 1] - data[row + width - 2];
|
|
58
|
+
for (let x = 1; x < width - 1; x++) {
|
|
59
|
+
out[row + x] = (data[row + x + 1] - data[row + x - 1]) / 2;
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return out;
|
|
63
|
+
}
|
|
64
|
+
/** hough[i] = sum(positive part along axis) * sum(negative part along axis). */
|
|
65
|
+
function houghResponse(grad, width, height, axis) {
|
|
66
|
+
const n = axis === "rows" ? height : width;
|
|
67
|
+
const pos = new Float64Array(n);
|
|
68
|
+
const neg = new Float64Array(n);
|
|
69
|
+
for (let y = 0; y < height; y++) {
|
|
70
|
+
for (let x = 0; x < width; x++) {
|
|
71
|
+
const g = grad[y * width + x];
|
|
72
|
+
const i = axis === "rows" ? y : x;
|
|
73
|
+
if (g > 0)
|
|
74
|
+
pos[i] += g;
|
|
75
|
+
else
|
|
76
|
+
neg[i] -= g;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const out = new Float64Array(n);
|
|
80
|
+
for (let i = 0; i < n; i++)
|
|
81
|
+
out[i] = pos[i] * neg[i];
|
|
82
|
+
return out;
|
|
83
|
+
}
|
|
84
|
+
/** Faithful port of nonmax_suppress_1d (including its edge quirks:
|
|
85
|
+
* strict < against the left window, <= against the right window). */
|
|
86
|
+
function nonmaxSuppress(arr, winsize = 5) {
|
|
87
|
+
const out = Float64Array.from(arr);
|
|
88
|
+
const n = arr.length;
|
|
89
|
+
for (let i = 0; i < n; i++) {
|
|
90
|
+
const left = i === 0 ? 0 : max(arr, Math.max(0, i - winsize), i);
|
|
91
|
+
const right = i >= n - 2 ? 0 : max(arr, i + 1, Math.min(n - 1, i + winsize));
|
|
92
|
+
if (arr[i] < left || arr[i] <= right)
|
|
93
|
+
out[i] = 0;
|
|
94
|
+
}
|
|
95
|
+
return out;
|
|
96
|
+
}
|
|
97
|
+
/** All arithmetic sequences (within ERR_PX) of length >= MIN_SEQ_LEN. */
|
|
98
|
+
function getAllSequences(seq) {
|
|
99
|
+
if (seq.length < MIN_SEQ_LEN)
|
|
100
|
+
return [];
|
|
101
|
+
const seqs = [];
|
|
102
|
+
for (let i = 0; i < seq.length - 1; i++) {
|
|
103
|
+
for (let j = i + 1; j < seq.length; j++) {
|
|
104
|
+
let duplicate = false;
|
|
105
|
+
for (const prev of seqs) {
|
|
106
|
+
for (let k = 0; k < prev.length - 1; k++) {
|
|
107
|
+
if (seq[i] === prev[k] && seq[j] === prev[k + 1])
|
|
108
|
+
duplicate = true;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
if (duplicate)
|
|
112
|
+
continue;
|
|
113
|
+
const d = seq[j] - seq[i];
|
|
114
|
+
if (d < ERR_PX)
|
|
115
|
+
continue;
|
|
116
|
+
const s = [seq[i], seq[j]];
|
|
117
|
+
let n = s[s.length - 1] + d;
|
|
118
|
+
for (;;) {
|
|
119
|
+
let bestIdx = 0;
|
|
120
|
+
let bestDist = Infinity;
|
|
121
|
+
for (let k = 0; k < seq.length; k++) {
|
|
122
|
+
const dist = Math.abs(seq[k] - n);
|
|
123
|
+
if (dist < bestDist) {
|
|
124
|
+
bestDist = dist;
|
|
125
|
+
bestIdx = k;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
if (bestDist >= ERR_PX)
|
|
129
|
+
break;
|
|
130
|
+
n = seq[bestIdx];
|
|
131
|
+
s.push(n);
|
|
132
|
+
n = s[s.length - 1] + d;
|
|
133
|
+
}
|
|
134
|
+
if (s.length >= MIN_SEQ_LEN)
|
|
135
|
+
seqs.push(s);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return seqs;
|
|
139
|
+
}
|
|
140
|
+
/** Strip weakest edges until sequence is at most 9 long. */
|
|
141
|
+
function trimSequence(seq, vals) {
|
|
142
|
+
let s = seq.slice();
|
|
143
|
+
let v = vals.slice();
|
|
144
|
+
if (s.length > 9) {
|
|
145
|
+
while (s.length > 7) {
|
|
146
|
+
if (v[0] > v[v.length - 1]) {
|
|
147
|
+
s = s.slice(0, -1);
|
|
148
|
+
v = v.slice(0, -1);
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
s = s.slice(1);
|
|
152
|
+
v = v.slice(1);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
return { seq: s, vals: v };
|
|
157
|
+
}
|
|
158
|
+
function median(arr) {
|
|
159
|
+
const s = arr.slice().sort((a, b) => a - b);
|
|
160
|
+
const mid = Math.floor(s.length / 2);
|
|
161
|
+
return s.length % 2 ? s[mid] : (s[mid - 1] + s[mid]) / 2;
|
|
162
|
+
}
|
|
163
|
+
/** Crop (zero-padded out of bounds) + nearest resize to 64x64,
|
|
164
|
+
* correlate against ideal checkerboard kernel. */
|
|
165
|
+
function checkerboardScore(img, x0, y0, x1, y1) {
|
|
166
|
+
const w = x1 - x0;
|
|
167
|
+
const h = y1 - y0;
|
|
168
|
+
if (w <= 0 || h <= 0)
|
|
169
|
+
return 0;
|
|
170
|
+
let score = 0;
|
|
171
|
+
for (let ty = 0; ty < 64; ty++) {
|
|
172
|
+
const sy = y0 + Math.floor((ty * h) / 64);
|
|
173
|
+
for (let tx = 0; tx < 64; tx++) {
|
|
174
|
+
const sx = x0 + Math.floor((tx * w) / 64);
|
|
175
|
+
let px = 0;
|
|
176
|
+
if (sx >= 0 && sx < img.width && sy >= 0 && sy < img.height) {
|
|
177
|
+
px = img.data[sy * img.width + sx];
|
|
178
|
+
}
|
|
179
|
+
// kernel: +1 on (tile parity even), -1 odd, tiles are 8x8 px;
|
|
180
|
+
// normalized by sqrt(64*64) = 64 like np.linalg.norm of +/-1 grid.
|
|
181
|
+
const parity = (Math.floor(tx / 8) + Math.floor(ty / 8)) % 2 === 0 ? 1 : -1;
|
|
182
|
+
score += (parity * px) / 64;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return Math.abs(score);
|
|
186
|
+
}
|
|
187
|
+
function bestPeakSequence(hough) {
|
|
188
|
+
const suppressed = nonmaxSuppress(hough);
|
|
189
|
+
const peak = max(suppressed, 0, suppressed.length);
|
|
190
|
+
if (peak <= 0)
|
|
191
|
+
return null;
|
|
192
|
+
const positions = [];
|
|
193
|
+
const values = [];
|
|
194
|
+
for (let i = 0; i < suppressed.length; i++) {
|
|
195
|
+
const v = suppressed[i] / peak;
|
|
196
|
+
if (v >= PEAK_KEEP_RATIO) {
|
|
197
|
+
positions.push(i);
|
|
198
|
+
values.push(v);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const seqs = getAllSequences(positions);
|
|
202
|
+
if (seqs.length === 0)
|
|
203
|
+
return null;
|
|
204
|
+
const valueAt = new Map(positions.map((p, i) => [p, values[i]]));
|
|
205
|
+
let best = null;
|
|
206
|
+
let bestScore = -Infinity;
|
|
207
|
+
for (const seq of seqs) {
|
|
208
|
+
const vals = seq.map((p) => valueAt.get(p) ?? 0);
|
|
209
|
+
const trimmed = trimSequence(seq, vals);
|
|
210
|
+
const score = trimmed.vals.reduce((a, b) => a + b, 0) / trimmed.vals.length;
|
|
211
|
+
if (score > bestScore) {
|
|
212
|
+
bestScore = score;
|
|
213
|
+
best = trimmed.seq;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return best;
|
|
217
|
+
}
|
|
218
|
+
/**
|
|
219
|
+
* Grid-snap refinement candidate: the peak-sequence search can lock
|
|
220
|
+
* onto an offset grid when the board texture itself is edge-rich
|
|
221
|
+
* (hatched book diagrams put more gradient energy inside squares
|
|
222
|
+
* than on the grid lines). Checkerboard correlation peaks at true
|
|
223
|
+
* alignment on such boards, but is too crude to be trusted blindly
|
|
224
|
+
* on photo-textured boards, so callers treat the snapped box as a
|
|
225
|
+
* CANDIDATE alongside the raw one and let the tile classifier pick
|
|
226
|
+
* the alignment with higher mean confidence (recognize.ts).
|
|
227
|
+
*/
|
|
228
|
+
export function snapCorners(img, box) {
|
|
229
|
+
const tile = (box.x1 - box.x0) / 8;
|
|
230
|
+
const radius = Math.max(2, Math.round(tile / 3));
|
|
231
|
+
let bestDx = 0;
|
|
232
|
+
let bestDy = 0;
|
|
233
|
+
let bestScore = -Infinity;
|
|
234
|
+
const evalAt = (dx, dy) => {
|
|
235
|
+
const score = checkerboardScore(img, box.x0 + dx, box.y0 + dy, box.x1 + dx, box.y1 + dy);
|
|
236
|
+
if (score > bestScore) {
|
|
237
|
+
bestScore = score;
|
|
238
|
+
bestDx = dx;
|
|
239
|
+
bestDy = dy;
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
for (let dy = -radius; dy <= radius; dy += 2) {
|
|
243
|
+
for (let dx = -radius; dx <= radius; dx += 2) {
|
|
244
|
+
evalAt(dx, dy);
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
const cx = bestDx;
|
|
248
|
+
const cy = bestDy;
|
|
249
|
+
for (let dy = cy - 2; dy <= cy + 2; dy++) {
|
|
250
|
+
for (let dx = cx - 2; dx <= cx + 2; dx++) {
|
|
251
|
+
evalAt(dx, dy);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
return { x0: box.x0 + bestDx, y0: box.y0 + bestDy, x1: box.x1 + bestDx, y1: box.y1 + bestDy };
|
|
255
|
+
}
|
|
256
|
+
/**
|
|
257
|
+
* One-axis fallback: when the grid lines are clean on one axis but the
|
|
258
|
+
* other axis's internal lines are drowned out (low square-contrast
|
|
259
|
+
* boards where black pieces dump more gradient energy than the faint
|
|
260
|
+
* grid, e.g. white/pale-blue themes), reconstruct the missing axis from
|
|
261
|
+
* the good one. A chessboard is square, so the board's extent on the
|
|
262
|
+
* weak axis equals 8 tiles of the good axis's spacing; slide that square
|
|
263
|
+
* window along the weak axis and keep the position whose checkerboard
|
|
264
|
+
* correlation is strongest. Returns null if nothing scores well, so this
|
|
265
|
+
* cannot manufacture a board out of noise — checkerboardScore arbitrates.
|
|
266
|
+
*/
|
|
267
|
+
function reconstructSquareBoard(img, good, axis, weakPeaks) {
|
|
268
|
+
const tile = median(good.slice(1).map((v, i) => v - good[i]));
|
|
269
|
+
if (!(tile > 0))
|
|
270
|
+
return null;
|
|
271
|
+
// The good sequence already runs first-line to last-line. Treat that
|
|
272
|
+
// as the board span directly — do NOT pad a phantom tile on each side,
|
|
273
|
+
// which over-extends the square and pulls the checkerboard-correlation
|
|
274
|
+
// peak onto a false alignment in the surrounding UI.
|
|
275
|
+
const gA = Math.round(good[0]);
|
|
276
|
+
const gB = Math.round(good[good.length - 1]);
|
|
277
|
+
const span = gB - gA;
|
|
278
|
+
if (span <= 0)
|
|
279
|
+
return null;
|
|
280
|
+
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
|
+
let best = null;
|
|
289
|
+
let bestScore = -Infinity;
|
|
290
|
+
for (let start = -span; start <= limit; start += step) {
|
|
291
|
+
const wA = start;
|
|
292
|
+
const wB = start + span;
|
|
293
|
+
const box = axis === "x"
|
|
294
|
+
? { x0: gA, y0: wA, x1: gB, y1: wB }
|
|
295
|
+
: { x0: wA, y0: gA, x1: wB, y1: gB };
|
|
296
|
+
let score = checkerboardScore(img, box.x0, box.y0, box.x1, box.y1);
|
|
297
|
+
if (nearEdge(wA, wB))
|
|
298
|
+
score *= 1.5;
|
|
299
|
+
if (score > bestScore) {
|
|
300
|
+
bestScore = score;
|
|
301
|
+
best = box;
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
return best;
|
|
305
|
+
}
|
|
306
|
+
/** Peaks above the keep ratio on one axis, even when they don't form a
|
|
307
|
+
* full grid sequence — used to recover detected outer board edges for
|
|
308
|
+
* the one-axis reconstruction fallback. */
|
|
309
|
+
function peakPositions(hough) {
|
|
310
|
+
const suppressed = nonmaxSuppress(hough);
|
|
311
|
+
const peak = max(suppressed, 0, suppressed.length);
|
|
312
|
+
if (peak <= 0)
|
|
313
|
+
return [];
|
|
314
|
+
const out = [];
|
|
315
|
+
for (let i = 0; i < suppressed.length; i++) {
|
|
316
|
+
if (suppressed[i] / peak >= PEAK_KEEP_RATIO)
|
|
317
|
+
out.push(i);
|
|
318
|
+
}
|
|
319
|
+
return out;
|
|
320
|
+
}
|
|
321
|
+
export function findChessboardCorners(img) {
|
|
322
|
+
const gradY = gradientRows(img);
|
|
323
|
+
const gradX = gradientCols(img);
|
|
324
|
+
const houghRows = houghResponse(gradY, img.width, img.height, "rows");
|
|
325
|
+
const houghCols = houghResponse(gradX, img.width, img.height, "cols");
|
|
326
|
+
// Rows hough peaks = y coordinates of horizontal lines;
|
|
327
|
+
// cols hough peaks = x coordinates of vertical lines.
|
|
328
|
+
const linesY = bestPeakSequence(houghRows);
|
|
329
|
+
const linesX = bestPeakSequence(houghCols);
|
|
330
|
+
// One axis clean, the other lost to low contrast / piece-edge noise:
|
|
331
|
+
// rebuild the square board from the good axis. snapCorners (called by
|
|
332
|
+
// the recognizer) then refines the alignment a few pixels either way.
|
|
333
|
+
if (linesX && !linesY)
|
|
334
|
+
return reconstructSquareBoard(img, linesX, "x", peakPositions(houghRows));
|
|
335
|
+
if (linesY && !linesX)
|
|
336
|
+
return reconstructSquareBoard(img, linesY, "y", peakPositions(houghCols));
|
|
337
|
+
if (!linesX || !linesY)
|
|
338
|
+
return null;
|
|
339
|
+
const dx = median(linesX.slice(1).map((v, i) => v - linesX[i]));
|
|
340
|
+
const dy = median(linesY.slice(1).map((v, i) => v - linesY[i]));
|
|
341
|
+
// Sequences of 7-9 lines give up to 3x3 candidate 7-line sub-grids;
|
|
342
|
+
// pick the one whose outer box correlates best with a checkerboard.
|
|
343
|
+
const subX = [];
|
|
344
|
+
for (let k = 0; k + 7 <= linesX.length; k++)
|
|
345
|
+
subX.push(linesX.slice(k, k + 7));
|
|
346
|
+
const subY = [];
|
|
347
|
+
for (let k = 0; k + 7 <= linesY.length; k++)
|
|
348
|
+
subY.push(linesY.slice(k, k + 7));
|
|
349
|
+
let best = null;
|
|
350
|
+
let bestScore = -Infinity;
|
|
351
|
+
for (const sx of subX) {
|
|
352
|
+
for (const sy of subY) {
|
|
353
|
+
const x0 = Math.round(sx[0] - dx);
|
|
354
|
+
const x1 = Math.round(sx[6] + dx);
|
|
355
|
+
const y0 = Math.round(sy[0] - dy);
|
|
356
|
+
const y1 = Math.round(sy[6] + dy);
|
|
357
|
+
const score = checkerboardScore(img, x0, y0, x1, y1);
|
|
358
|
+
if (score > bestScore) {
|
|
359
|
+
bestScore = score;
|
|
360
|
+
best = { x0, y0, x1, y1 };
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
return best;
|
|
365
|
+
}
|
package/dist/fen.d.ts
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model output to FEN piece placement. The classifier emits 13-class
|
|
3
|
+
* probabilities per tile in A1..H8 rank order; class labels are
|
|
4
|
+
* '1KQRBNPkqrbnp' (index 0 = empty square).
|
|
5
|
+
*/
|
|
6
|
+
export interface RecognitionResult {
|
|
7
|
+
/** FEN piece-placement field (ranks 8..1), run-length compressed. */
|
|
8
|
+
placement: string;
|
|
9
|
+
/** Per-tile argmax confidence, A1..H8 rank order. */
|
|
10
|
+
confidences: number[];
|
|
11
|
+
/** The weakest tile confidence. Below ~0.7 treat as unreliable. */
|
|
12
|
+
minConfidence: number;
|
|
13
|
+
/** Average tile confidence; used to arbitrate between candidate
|
|
14
|
+
* board alignments (recognize.ts). */
|
|
15
|
+
meanConfidence: number;
|
|
16
|
+
}
|
|
17
|
+
export declare function probsToPlacement(probs: Float32Array): RecognitionResult;
|
|
18
|
+
/** Mirror a placement for a board photographed with Black at the
|
|
19
|
+
* bottom (rotate 180 degrees: reverse ranks and files). */
|
|
20
|
+
export declare function flipPlacement(placement: string): string;
|
|
21
|
+
/** Decide board orientation from pawn-advance direction, the one
|
|
22
|
+
* orientation-fixed fact in chess: white pawns march up the ranks
|
|
23
|
+
* (home 2, promote 8), black pawns march down (home 7, promote 1).
|
|
24
|
+
* In any natural position white pawns sit, on average, on LOWER
|
|
25
|
+
* ranks than black pawns. The recognizer always reads tiles as if
|
|
26
|
+
* white were at the bottom, so a screenshot taken from Black's side
|
|
27
|
+
* comes back with that relationship inverted (white pawns appear
|
|
28
|
+
* high, black low). We compare the read against its 180-rotation and
|
|
29
|
+
* keep whichever has white pawns lower than black. When there are no
|
|
30
|
+
* pawns of one color, or the signal ties, orientation is genuinely
|
|
31
|
+
* undecidable from pixels, so we keep the white-at-bottom read and
|
|
32
|
+
* leave the call to the user's flip toggle. */
|
|
33
|
+
export declare function resolveOrientation(placement: string): {
|
|
34
|
+
placement: string;
|
|
35
|
+
orientation: "white" | "black";
|
|
36
|
+
};
|
package/dist/fen.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model output to FEN piece placement. The classifier emits 13-class
|
|
3
|
+
* probabilities per tile in A1..H8 rank order; class labels are
|
|
4
|
+
* '1KQRBNPkqrbnp' (index 0 = empty square).
|
|
5
|
+
*/
|
|
6
|
+
const LABELS = "1KQRBNPkqrbnp";
|
|
7
|
+
export function probsToPlacement(probs) {
|
|
8
|
+
const names = [];
|
|
9
|
+
const confidences = [];
|
|
10
|
+
for (let i = 0; i < 64; i++) {
|
|
11
|
+
let best = -1;
|
|
12
|
+
let bestIdx = 0;
|
|
13
|
+
for (let c = 0; c < 13; c++) {
|
|
14
|
+
const p = probs[i * 13 + c];
|
|
15
|
+
if (p > best) {
|
|
16
|
+
best = p;
|
|
17
|
+
bestIdx = c;
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
names.push(LABELS[bestIdx]);
|
|
21
|
+
confidences.push(best);
|
|
22
|
+
}
|
|
23
|
+
const ranks = [];
|
|
24
|
+
for (let r = 7; r >= 0; r--) {
|
|
25
|
+
ranks.push(names.slice(r * 8, r * 8 + 8).join(""));
|
|
26
|
+
}
|
|
27
|
+
const placement = ranks
|
|
28
|
+
.join("/")
|
|
29
|
+
.replace(/1{2,}/g, (m) => String(m.length));
|
|
30
|
+
return {
|
|
31
|
+
placement,
|
|
32
|
+
confidences,
|
|
33
|
+
minConfidence: Math.min(...confidences),
|
|
34
|
+
meanConfidence: confidences.reduce((a, b) => a + b, 0) / confidences.length,
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
/** Mirror a placement for a board photographed with Black at the
|
|
38
|
+
* bottom (rotate 180 degrees: reverse ranks and files). */
|
|
39
|
+
export function flipPlacement(placement) {
|
|
40
|
+
return placement
|
|
41
|
+
.split("/")
|
|
42
|
+
.reverse()
|
|
43
|
+
.map((rank) => rank.split("").reverse().join(""))
|
|
44
|
+
.join("/");
|
|
45
|
+
}
|
|
46
|
+
/** Mean rank of each color's pawns, reading `placement` as a
|
|
47
|
+
* white-at-bottom board (rank 8 = first row, rank 1 = last row).
|
|
48
|
+
* Returns null for a color with no pawns. */
|
|
49
|
+
function meanPawnRanks(placement) {
|
|
50
|
+
const ranks = placement.split("/");
|
|
51
|
+
const white = [];
|
|
52
|
+
const black = [];
|
|
53
|
+
ranks.forEach((row, i) => {
|
|
54
|
+
const rank = 8 - i;
|
|
55
|
+
for (const ch of row) {
|
|
56
|
+
if (ch === "P")
|
|
57
|
+
white.push(rank);
|
|
58
|
+
else if (ch === "p")
|
|
59
|
+
black.push(rank);
|
|
60
|
+
}
|
|
61
|
+
});
|
|
62
|
+
const mean = (xs) => xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : null;
|
|
63
|
+
return { white: mean(white), black: mean(black) };
|
|
64
|
+
}
|
|
65
|
+
/** Decide board orientation from pawn-advance direction, the one
|
|
66
|
+
* orientation-fixed fact in chess: white pawns march up the ranks
|
|
67
|
+
* (home 2, promote 8), black pawns march down (home 7, promote 1).
|
|
68
|
+
* In any natural position white pawns sit, on average, on LOWER
|
|
69
|
+
* ranks than black pawns. The recognizer always reads tiles as if
|
|
70
|
+
* white were at the bottom, so a screenshot taken from Black's side
|
|
71
|
+
* comes back with that relationship inverted (white pawns appear
|
|
72
|
+
* high, black low). We compare the read against its 180-rotation and
|
|
73
|
+
* keep whichever has white pawns lower than black. When there are no
|
|
74
|
+
* pawns of one color, or the signal ties, orientation is genuinely
|
|
75
|
+
* undecidable from pixels, so we keep the white-at-bottom read and
|
|
76
|
+
* leave the call to the user's flip toggle. */
|
|
77
|
+
export function resolveOrientation(placement) {
|
|
78
|
+
const naturalness = (p) => {
|
|
79
|
+
const { white, black } = meanPawnRanks(p);
|
|
80
|
+
if (white == null || black == null)
|
|
81
|
+
return null;
|
|
82
|
+
return black - white;
|
|
83
|
+
};
|
|
84
|
+
const asRead = naturalness(placement);
|
|
85
|
+
const rotated = flipPlacement(placement);
|
|
86
|
+
const asRotated = naturalness(rotated);
|
|
87
|
+
if (asRead != null && asRotated != null && asRotated > asRead) {
|
|
88
|
+
return { placement: rotated, orientation: "black" };
|
|
89
|
+
}
|
|
90
|
+
return { placement, orientation: "white" };
|
|
91
|
+
}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createRecognizer, recognizeGray, CONFIDENCE_FLOOR, type Recognizer, type RecognizerOptions, type BoardScanResult, type TileClassifier, } from "./recognize";
|
|
2
|
+
export { findChessboardCorners, snapCorners, type BoardCorners, type GrayImage, } from "./detect";
|
|
3
|
+
export { extractBoardImage, boardToTiles, extractTiles, rgbaToGray } from "./tiles";
|
|
4
|
+
export { probsToPlacement, flipPlacement, resolveOrientation, type RecognitionResult, } from "./fen";
|
|
5
|
+
export { inferCastling, placementToFen } from "./compose";
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
export { createRecognizer, recognizeGray, CONFIDENCE_FLOOR, } from "./recognize";
|
|
2
|
+
export { findChessboardCorners, snapCorners, } from "./detect";
|
|
3
|
+
export { extractBoardImage, boardToTiles, extractTiles, rgbaToGray } from "./tiles";
|
|
4
|
+
export { probsToPlacement, flipPlacement, resolveOrientation, } from "./fen";
|
|
5
|
+
export { inferCastling, placementToFen } from "./compose";
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-side screenshot recognition. Lazy-loads onnxruntime-web
|
|
3
|
+
* (pure-wasm build) and the tile classifier model on first use.
|
|
4
|
+
*
|
|
5
|
+
* The classifier is trained on a synthetic corpus spanning lichess +
|
|
6
|
+
* chess.com piece sets and board themes, procedural flat boards, and
|
|
7
|
+
* book-diagram hatch boards, with screenshot degradations baked in
|
|
8
|
+
* (dimming, JPEG artifacts, blur, corner jitter).
|
|
9
|
+
*
|
|
10
|
+
* Alignment arbitration: detection corners plus a checkerboard
|
|
11
|
+
* grid-snap candidate are both classified, and the read with higher
|
|
12
|
+
* mean confidence wins. Edge-rich board textures (hatched book
|
|
13
|
+
* diagrams) fool the gradient peak search by a quarter tile; the
|
|
14
|
+
* snap fixes those, but is itself unreliable on dim photo-textured
|
|
15
|
+
* boards, so the classifier arbitrates.
|
|
16
|
+
*
|
|
17
|
+
* recognize: HTMLImageElement/ImageBitmap/File/Blob -> placement FEN
|
|
18
|
+
* + per-tile confidence. reliable=false (minConfidence below
|
|
19
|
+
* CONFIDENCE_FLOOR) means the read is untrustworthy (truly foreign
|
|
20
|
+
* piece set, partial board) and the caller should route the user to
|
|
21
|
+
* an editor with a warning rather than trusting the result.
|
|
22
|
+
*/
|
|
23
|
+
import { type BoardCorners, type GrayImage } from "./detect";
|
|
24
|
+
import { type RecognitionResult } from "./fen";
|
|
25
|
+
export declare const CONFIDENCE_FLOOR = 0.7;
|
|
26
|
+
export interface BoardScanResult extends RecognitionResult {
|
|
27
|
+
corners: BoardCorners;
|
|
28
|
+
reliable: boolean;
|
|
29
|
+
}
|
|
30
|
+
export interface RecognizerOptions {
|
|
31
|
+
/** URL of the tile classifier model (`chess-tiles-v2.onnx`, shipped
|
|
32
|
+
* in this package under `model/`). Serve it as a static asset and
|
|
33
|
+
* point here, e.g. "/models/chess-tiles-v2.onnx". */
|
|
34
|
+
modelUrl: string;
|
|
35
|
+
/** Location of the onnxruntime-web wasm assets. Either a directory
|
|
36
|
+
* URL prefix (e.g. "/ort/") or exact per-file URLs, which is what
|
|
37
|
+
* bundlers like Vite need:
|
|
38
|
+
* `{ mjs: mjsUrl, wasm: wasmUrl }` from `?url` imports. */
|
|
39
|
+
wasmPaths: string | {
|
|
40
|
+
mjs: string;
|
|
41
|
+
wasm: string;
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
export interface Recognizer {
|
|
45
|
+
/** Scan an image for a chessboard. Resolves null when no board-like
|
|
46
|
+
* structure is found. */
|
|
47
|
+
recognize(source: HTMLImageElement | ImageBitmap | File | Blob): Promise<BoardScanResult | null>;
|
|
48
|
+
/** Eagerly fetch + compile the wasm runtime and the model so the
|
|
49
|
+
* first scan is near-instant. Idempotent; failures are swallowed
|
|
50
|
+
* (a warmup miss just means the first scan pays the cost). */
|
|
51
|
+
warmUp(): void;
|
|
52
|
+
}
|
|
53
|
+
export type TileClassifier = (corners: BoardCorners) => Promise<RecognitionResult>;
|
|
54
|
+
/**
|
|
55
|
+
* Pure recognition core: detect corners, classify, arbitrate against
|
|
56
|
+
* the grid-snap candidate. Platform-independent (no canvas, no ONNX);
|
|
57
|
+
* the classifier is injected. Exercised directly by the golden test
|
|
58
|
+
* suite and usable from Node with any rasterizer.
|
|
59
|
+
*/
|
|
60
|
+
export declare function recognizeGray(gray: GrayImage, classify: TileClassifier): Promise<BoardScanResult | null>;
|
|
61
|
+
export declare function createRecognizer(options: RecognizerOptions): Recognizer;
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-side screenshot recognition. Lazy-loads onnxruntime-web
|
|
3
|
+
* (pure-wasm build) and the tile classifier model on first use.
|
|
4
|
+
*
|
|
5
|
+
* The classifier is trained on a synthetic corpus spanning lichess +
|
|
6
|
+
* chess.com piece sets and board themes, procedural flat boards, and
|
|
7
|
+
* book-diagram hatch boards, with screenshot degradations baked in
|
|
8
|
+
* (dimming, JPEG artifacts, blur, corner jitter).
|
|
9
|
+
*
|
|
10
|
+
* Alignment arbitration: detection corners plus a checkerboard
|
|
11
|
+
* grid-snap candidate are both classified, and the read with higher
|
|
12
|
+
* mean confidence wins. Edge-rich board textures (hatched book
|
|
13
|
+
* diagrams) fool the gradient peak search by a quarter tile; the
|
|
14
|
+
* snap fixes those, but is itself unreliable on dim photo-textured
|
|
15
|
+
* boards, so the classifier arbitrates.
|
|
16
|
+
*
|
|
17
|
+
* recognize: HTMLImageElement/ImageBitmap/File/Blob -> placement FEN
|
|
18
|
+
* + per-tile confidence. reliable=false (minConfidence below
|
|
19
|
+
* CONFIDENCE_FLOOR) means the read is untrustworthy (truly foreign
|
|
20
|
+
* piece set, partial board) and the caller should route the user to
|
|
21
|
+
* an editor with a warning rather than trusting the result.
|
|
22
|
+
*/
|
|
23
|
+
import { findChessboardCorners, snapCorners } from "./detect";
|
|
24
|
+
import { extractTiles, rgbaToGray } from "./tiles";
|
|
25
|
+
import { probsToPlacement } from "./fen";
|
|
26
|
+
export const CONFIDENCE_FLOOR = 0.7;
|
|
27
|
+
/** Detection works on moderate resolutions; downscale huge retina
|
|
28
|
+
* screenshots for speed (gradients survive downscaling fine). */
|
|
29
|
+
const MAX_DETECT_DIM = 1600;
|
|
30
|
+
function imageToGray(img) {
|
|
31
|
+
const w = "naturalWidth" in img ? img.naturalWidth : img.width;
|
|
32
|
+
const h = "naturalHeight" in img ? img.naturalHeight : img.height;
|
|
33
|
+
const scale = Math.min(1, MAX_DETECT_DIM / Math.max(w, h));
|
|
34
|
+
const cw = Math.round(w * scale);
|
|
35
|
+
const ch = Math.round(h * scale);
|
|
36
|
+
const canvas = document.createElement("canvas");
|
|
37
|
+
canvas.width = cw;
|
|
38
|
+
canvas.height = ch;
|
|
39
|
+
const ctx = canvas.getContext("2d", { willReadFrequently: true });
|
|
40
|
+
if (!ctx)
|
|
41
|
+
throw new Error("Canvas 2d context unavailable");
|
|
42
|
+
ctx.drawImage(img, 0, 0, cw, ch);
|
|
43
|
+
const data = ctx.getImageData(0, 0, cw, ch);
|
|
44
|
+
return rgbaToGray(data.data, cw, ch);
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Pure recognition core: detect corners, classify, arbitrate against
|
|
48
|
+
* the grid-snap candidate. Platform-independent (no canvas, no ONNX);
|
|
49
|
+
* the classifier is injected. Exercised directly by the golden test
|
|
50
|
+
* suite and usable from Node with any rasterizer.
|
|
51
|
+
*/
|
|
52
|
+
export async function recognizeGray(gray, classify) {
|
|
53
|
+
const corners = findChessboardCorners(gray);
|
|
54
|
+
if (!corners)
|
|
55
|
+
return null;
|
|
56
|
+
let bestCorners = corners;
|
|
57
|
+
let best = await classify(corners);
|
|
58
|
+
const snapped = snapCorners(gray, corners);
|
|
59
|
+
if (snapped.x0 !== corners.x0 ||
|
|
60
|
+
snapped.y0 !== corners.y0 ||
|
|
61
|
+
snapped.x1 !== corners.x1 ||
|
|
62
|
+
snapped.y1 !== corners.y1) {
|
|
63
|
+
const snappedRead = await classify(snapped);
|
|
64
|
+
if (snappedRead.meanConfidence > best.meanConfidence) {
|
|
65
|
+
best = snappedRead;
|
|
66
|
+
bestCorners = snapped;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return {
|
|
70
|
+
...best,
|
|
71
|
+
corners: bestCorners,
|
|
72
|
+
reliable: best.minConfidence >= CONFIDENCE_FLOOR,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
export function createRecognizer(options) {
|
|
76
|
+
let ortPromise = null;
|
|
77
|
+
let sessionPromise = null;
|
|
78
|
+
function loadOrt() {
|
|
79
|
+
if (!ortPromise) {
|
|
80
|
+
// The pure-wasm build: the default package entry is the JSEP
|
|
81
|
+
// (webgpu) bundle which requests ort-wasm-*.jsep.mjs at runtime;
|
|
82
|
+
// only the plain wasm pair is required here.
|
|
83
|
+
ortPromise = import("onnxruntime-web/wasm").then((ort) => {
|
|
84
|
+
ort.env.wasm.wasmPaths = options.wasmPaths;
|
|
85
|
+
return ort;
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
return ortPromise;
|
|
89
|
+
}
|
|
90
|
+
function getSession() {
|
|
91
|
+
if (!sessionPromise) {
|
|
92
|
+
sessionPromise = (async () => {
|
|
93
|
+
const ort = await loadOrt();
|
|
94
|
+
return ort.InferenceSession.create(options.modelUrl, {
|
|
95
|
+
executionProviders: ["wasm"],
|
|
96
|
+
});
|
|
97
|
+
})();
|
|
98
|
+
}
|
|
99
|
+
return sessionPromise;
|
|
100
|
+
}
|
|
101
|
+
return {
|
|
102
|
+
warmUp() {
|
|
103
|
+
void getSession().catch(() => undefined);
|
|
104
|
+
},
|
|
105
|
+
async recognize(source) {
|
|
106
|
+
const img = source instanceof File || source instanceof Blob ? await createImageBitmap(source) : source;
|
|
107
|
+
const gray = imageToGray(img);
|
|
108
|
+
const [ort, session] = await Promise.all([loadOrt(), getSession()]);
|
|
109
|
+
return recognizeGray(gray, async (c) => {
|
|
110
|
+
const tiles = extractTiles(gray, c);
|
|
111
|
+
const out = await session.run({ tiles: new ort.Tensor("float32", tiles, [64, 1024]) });
|
|
112
|
+
return probsToPlacement(out["probs"].data);
|
|
113
|
+
});
|
|
114
|
+
},
|
|
115
|
+
};
|
|
116
|
+
}
|
package/dist/tiles.d.ts
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tile extraction for the chess-tiles CNN. Port of getChessTilesGray
|
|
3
|
+
* from Elucidation/tensorflow_chessbot (MIT).
|
|
4
|
+
*
|
|
5
|
+
* Crops the board (edge-padding out-of-bounds corners), bilinear
|
|
6
|
+
* resizes to 256x256, normalizes to [0,1], and emits the 64 tiles in
|
|
7
|
+
* the model's input order: tile k = rank*8 + file with A1 at the
|
|
8
|
+
* image's bottom-left, each tile a row-major 32x32 block. Output is
|
|
9
|
+
* a Float32Array of shape [64, 1024].
|
|
10
|
+
*/
|
|
11
|
+
import type { BoardCorners, GrayImage } from "./detect";
|
|
12
|
+
export declare const TILE_INPUT_SIZE: number;
|
|
13
|
+
/** Bilinear resize of the corners crop to 256x256, values in [0,1]. */
|
|
14
|
+
export declare function extractBoardImage(img: GrayImage, corners: BoardCorners): Float32Array;
|
|
15
|
+
/** Slice the 256x256 board into the [64, 1024] model input. */
|
|
16
|
+
export declare function boardToTiles(board: Float32Array): Float32Array;
|
|
17
|
+
export declare function extractTiles(img: GrayImage, corners: BoardCorners): Float32Array;
|
|
18
|
+
/** RGBA ImageData bytes to 0-255 grayscale (ITU-R 601 luma). */
|
|
19
|
+
export declare function rgbaToGray(rgba: Uint8ClampedArray, width: number, height: number): GrayImage;
|
package/dist/tiles.js
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Tile extraction for the chess-tiles CNN. Port of getChessTilesGray
|
|
3
|
+
* from Elucidation/tensorflow_chessbot (MIT).
|
|
4
|
+
*
|
|
5
|
+
* Crops the board (edge-padding out-of-bounds corners), bilinear
|
|
6
|
+
* resizes to 256x256, normalizes to [0,1], and emits the 64 tiles in
|
|
7
|
+
* the model's input order: tile k = rank*8 + file with A1 at the
|
|
8
|
+
* image's bottom-left, each tile a row-major 32x32 block. Output is
|
|
9
|
+
* a Float32Array of shape [64, 1024].
|
|
10
|
+
*/
|
|
11
|
+
const BOARD_PX = 256;
|
|
12
|
+
const TILE_PX = 32;
|
|
13
|
+
export const TILE_INPUT_SIZE = TILE_PX * TILE_PX;
|
|
14
|
+
/** Sample with edge clamping (np.pad mode="edge" equivalent). */
|
|
15
|
+
function sampleClamped(img, x, y) {
|
|
16
|
+
const cx = Math.min(img.width - 1, Math.max(0, x));
|
|
17
|
+
const cy = Math.min(img.height - 1, Math.max(0, y));
|
|
18
|
+
return img.data[cy * img.width + cx];
|
|
19
|
+
}
|
|
20
|
+
/** Bilinear resize of the corners crop to 256x256, values in [0,1]. */
|
|
21
|
+
export function extractBoardImage(img, corners) {
|
|
22
|
+
const { x0, y0, x1, y1 } = corners;
|
|
23
|
+
const cw = x1 - x0;
|
|
24
|
+
const ch = y1 - y0;
|
|
25
|
+
const out = new Float32Array(BOARD_PX * BOARD_PX);
|
|
26
|
+
for (let ty = 0; ty < BOARD_PX; ty++) {
|
|
27
|
+
const sy = y0 + ((ty + 0.5) * ch) / BOARD_PX - 0.5;
|
|
28
|
+
const fy = Math.floor(sy);
|
|
29
|
+
const wy = sy - fy;
|
|
30
|
+
for (let tx = 0; tx < BOARD_PX; tx++) {
|
|
31
|
+
const sx = x0 + ((tx + 0.5) * cw) / BOARD_PX - 0.5;
|
|
32
|
+
const fx = Math.floor(sx);
|
|
33
|
+
const wx = sx - fx;
|
|
34
|
+
const v = sampleClamped(img, fx, fy) * (1 - wx) * (1 - wy) +
|
|
35
|
+
sampleClamped(img, fx + 1, fy) * wx * (1 - wy) +
|
|
36
|
+
sampleClamped(img, fx, fy + 1) * (1 - wx) * wy +
|
|
37
|
+
sampleClamped(img, fx + 1, fy + 1) * wx * wy;
|
|
38
|
+
out[ty * BOARD_PX + tx] = v / 255;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
/** Slice the 256x256 board into the [64, 1024] model input. */
|
|
44
|
+
export function boardToTiles(board) {
|
|
45
|
+
const out = new Float32Array(64 * TILE_INPUT_SIZE);
|
|
46
|
+
for (let rank = 0; rank < 8; rank++) {
|
|
47
|
+
for (let file = 0; file < 8; file++) {
|
|
48
|
+
const tile = rank * 8 + file;
|
|
49
|
+
const srcY0 = (7 - rank) * TILE_PX;
|
|
50
|
+
const srcX0 = file * TILE_PX;
|
|
51
|
+
for (let y = 0; y < TILE_PX; y++) {
|
|
52
|
+
const srcRow = (srcY0 + y) * BOARD_PX + srcX0;
|
|
53
|
+
const dstRow = tile * TILE_INPUT_SIZE + y * TILE_PX;
|
|
54
|
+
for (let x = 0; x < TILE_PX; x++) {
|
|
55
|
+
out[dstRow + x] = board[srcRow + x];
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
return out;
|
|
61
|
+
}
|
|
62
|
+
export function extractTiles(img, corners) {
|
|
63
|
+
return boardToTiles(extractBoardImage(img, corners));
|
|
64
|
+
}
|
|
65
|
+
/** RGBA ImageData bytes to 0-255 grayscale (ITU-R 601 luma). */
|
|
66
|
+
export function rgbaToGray(rgba, width, height) {
|
|
67
|
+
const data = new Float32Array(width * height);
|
|
68
|
+
for (let i = 0; i < width * height; i++) {
|
|
69
|
+
const off = i * 4;
|
|
70
|
+
data[i] = 0.299 * rgba[off] + 0.587 * rgba[off + 1] + 0.114 * rgba[off + 2];
|
|
71
|
+
}
|
|
72
|
+
return { data, width, height };
|
|
73
|
+
}
|
|
Binary file
|
package/package.json
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@scoriiu/fenshot",
|
|
3
|
+
"version": "0.1.0",
|
|
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
|
+
"type": "module",
|
|
6
|
+
"main": "./dist/index.js",
|
|
7
|
+
"types": "./dist/index.d.ts",
|
|
8
|
+
"exports": {
|
|
9
|
+
".": {
|
|
10
|
+
"types": "./dist/index.d.ts",
|
|
11
|
+
"import": "./dist/index.js"
|
|
12
|
+
},
|
|
13
|
+
"./model/chess-tiles-v2.onnx": "./model/chess-tiles-v2.onnx"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"model"
|
|
18
|
+
],
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"scripts": {
|
|
21
|
+
"build": "tsc -p tsconfig.build.json",
|
|
22
|
+
"test": "vitest run",
|
|
23
|
+
"prepublishOnly": "npm run build && npm run test"
|
|
24
|
+
},
|
|
25
|
+
"publishConfig": {
|
|
26
|
+
"access": "public"
|
|
27
|
+
},
|
|
28
|
+
"peerDependencies": {
|
|
29
|
+
"onnxruntime-web": ">=1.17.0"
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/pngjs": "^6.0.5",
|
|
33
|
+
"onnxruntime-web": "1.26.0",
|
|
34
|
+
"pngjs": "^7.0.0",
|
|
35
|
+
"typescript": "^5.6.0",
|
|
36
|
+
"vitest": "^3.0.0"
|
|
37
|
+
},
|
|
38
|
+
"keywords": [
|
|
39
|
+
"chess",
|
|
40
|
+
"fen",
|
|
41
|
+
"screenshot",
|
|
42
|
+
"ocr",
|
|
43
|
+
"chessboard",
|
|
44
|
+
"recognition",
|
|
45
|
+
"onnx",
|
|
46
|
+
"lichess"
|
|
47
|
+
],
|
|
48
|
+
"author": "Coachess (https://coachess.app)",
|
|
49
|
+
"license": "MIT",
|
|
50
|
+
"repository": {
|
|
51
|
+
"type": "git",
|
|
52
|
+
"url": "git+https://github.com/scoriiu/fenshot.git"
|
|
53
|
+
},
|
|
54
|
+
"homepage": "https://github.com/scoriiu/fenshot#readme",
|
|
55
|
+
"bugs": {
|
|
56
|
+
"url": "https://github.com/scoriiu/fenshot/issues"
|
|
57
|
+
}
|
|
58
|
+
}
|