@scoriiu/fenshot 0.1.5 → 0.1.6

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/dist/detect.d.ts CHANGED
@@ -44,4 +44,28 @@ export interface GrayImage {
44
44
  * the alignment with higher mean confidence (recognize.ts).
45
45
  */
46
46
  export declare function snapCorners(img: GrayImage, box: BoardCorners): BoardCorners;
47
+ /**
48
+ * How much a box looks like a chessboard, whatever stands on it: the
49
+ * Pearson correlation (-1..1) between the 64 tile backgrounds and the
50
+ * chessboard colouring. A box on a real board scores high in any theme;
51
+ * a box that hangs off the board, or sits at the wrong scale, mixes page
52
+ * background into the tiles and scores low. Patches average over a few
53
+ * pixels, so hatched dark squares read as their mean grey.
54
+ */
55
+ export declare function boardness(img: GrayImage, box: BoardCorners): number;
56
+ /**
57
+ * Second look: boards the plain search misses or misplaces because the
58
+ * board itself is full of edges. Hatched dark squares (printed diagrams,
59
+ * chess.com's newspaper board) put more gradient energy inside the
60
+ * squares than on the grid lines, and marbled or low-contrast boards can
61
+ * slide the grid one tile diagonally, which keeps the colouring and so
62
+ * slips past repairParity. On a blurred copy the hatching melts to grey
63
+ * and the grid lines dominate again.
64
+ *
65
+ * Returns the boxes found on blurred copies, each with its grid-snapped
66
+ * variant, that are square and look like a board, without duplicates and
67
+ * without anything in `known`. They are CANDIDATES: the caller lets the
68
+ * tile classifier choose (recognize.ts).
69
+ */
70
+ export declare function findBlurredBoardCandidates(img: GrayImage, known?: BoardCorners[]): BoardCorners[];
47
71
  export declare function findChessboardCorners(img: GrayImage): BoardCorners | null;
package/dist/detect.js CHANGED
@@ -376,6 +376,173 @@ function repairParity(img, box) {
376
376
  }
377
377
  return best;
378
378
  }
379
+ /** Box blur (edges clamped), two separable passes. */
380
+ function boxBlur(img, radius) {
381
+ const { width: w, height: h, data } = img;
382
+ const span = 2 * radius + 1;
383
+ const tmp = new Float32Array(w * h);
384
+ const out = new Float32Array(w * h);
385
+ for (let y = 0; y < h; y++) {
386
+ const row = y * w;
387
+ let acc = 0;
388
+ for (let x = -radius; x <= radius; x++)
389
+ acc += data[row + Math.min(w - 1, Math.max(0, x))];
390
+ for (let x = 0; x < w; x++) {
391
+ tmp[row + x] = acc / span;
392
+ acc += data[row + Math.min(w - 1, x + radius + 1)] - data[row + Math.max(0, x - radius)];
393
+ }
394
+ }
395
+ for (let x = 0; x < w; x++) {
396
+ let acc = 0;
397
+ for (let y = -radius; y <= radius; y++)
398
+ acc += tmp[Math.min(h - 1, Math.max(0, y)) * w + x];
399
+ for (let y = 0; y < h; y++) {
400
+ out[y * w + x] = acc / span;
401
+ acc += tmp[Math.min(h - 1, y + radius + 1) * w + x] - tmp[Math.max(0, y - radius) * w + x];
402
+ }
403
+ }
404
+ return { data: out, width: w, height: h };
405
+ }
406
+ /** Where in a tile its background shows: near the four corners, which
407
+ * pieces (drawn centered) do not reach. */
408
+ const BACKGROUND_SAMPLES = [
409
+ [0.16, 0.16],
410
+ [0.84, 0.16],
411
+ [0.16, 0.84],
412
+ [0.84, 0.84],
413
+ ];
414
+ /** Background brightness of one tile: the median of small patches at its
415
+ * corners. Null when the tile lies mostly outside the image. */
416
+ function tileBackground(img, x, y, tw, th, patch) {
417
+ const vals = [];
418
+ for (const [fx, fy] of BACKGROUND_SAMPLES) {
419
+ const cx = Math.round(x + fx * tw);
420
+ const cy = Math.round(y + fy * th);
421
+ let sum = 0;
422
+ let n = 0;
423
+ for (let py = Math.max(0, cy - patch); py <= Math.min(img.height - 1, cy + patch); py++) {
424
+ for (let px = Math.max(0, cx - patch); px <= Math.min(img.width - 1, cx + patch); px++) {
425
+ sum += img.data[py * img.width + px];
426
+ n++;
427
+ }
428
+ }
429
+ if (n)
430
+ vals.push(sum / n);
431
+ }
432
+ return vals.length < 2 ? null : median(vals);
433
+ }
434
+ /**
435
+ * How much a box looks like a chessboard, whatever stands on it: the
436
+ * Pearson correlation (-1..1) between the 64 tile backgrounds and the
437
+ * chessboard colouring. A box on a real board scores high in any theme;
438
+ * a box that hangs off the board, or sits at the wrong scale, mixes page
439
+ * background into the tiles and scores low. Patches average over a few
440
+ * pixels, so hatched dark squares read as their mean grey.
441
+ */
442
+ export function boardness(img, box) {
443
+ const tw = (box.x1 - box.x0) / 8;
444
+ const th = (box.y1 - box.y0) / 8;
445
+ if (tw < 6 || th < 6)
446
+ return -1;
447
+ const patch = Math.max(1, Math.round(tw / 10));
448
+ const backgrounds = [];
449
+ const colours = [];
450
+ for (let r = 0; r < 8; r++) {
451
+ for (let c = 0; c < 8; c++) {
452
+ const bg = tileBackground(img, box.x0 + c * tw, box.y0 + r * th, tw, th, patch);
453
+ if (bg === null)
454
+ continue;
455
+ backgrounds.push(bg);
456
+ colours.push((r + c) % 2 === 0 ? 1 : -1);
457
+ }
458
+ }
459
+ if (backgrounds.length < 48)
460
+ return -1;
461
+ const meanBg = backgrounds.reduce((a, b) => a + b, 0) / backgrounds.length;
462
+ const meanCol = colours.reduce((a, b) => a + b, 0) / colours.length;
463
+ let cov = 0;
464
+ let varBg = 0;
465
+ let varCol = 0;
466
+ for (let i = 0; i < backgrounds.length; i++) {
467
+ cov += (backgrounds[i] - meanBg) * (colours[i] - meanCol);
468
+ varBg += (backgrounds[i] - meanBg) ** 2;
469
+ varCol += (colours[i] - meanCol) ** 2;
470
+ }
471
+ return varBg > 0 && varCol > 0 ? cov / Math.sqrt(varBg * varCol) : 0;
472
+ }
473
+ /** Blur radii for the second look. The right one depends on the hatch
474
+ * period, which depends on scale: measured on the benchmark, 1 to 4 px
475
+ * between them find hatched boards from 110 to 200 dpi and chess.com's
476
+ * newspaper board; 6 px added nothing. */
477
+ const BLUR_RADII = [1, 2, 3, 4];
478
+ /** Above this size the second look runs at half resolution: tiles are
479
+ * large enough to stand the coarser grid, and a page with no board on it
480
+ * (the extension's whole-tab scan) costs a quarter as much. Halving is
481
+ * itself a 2x2 blur, so the radii shrink with it. */
482
+ const HALF_RES_ABOVE = 1000;
483
+ const HALF_RES_BLUR_RADII = [0, 1, 2];
484
+ /** A second-look box must be square within this fraction... */
485
+ const MAX_ASPECT_ERROR = 0.08;
486
+ /** ...and look like a board at least this much (boardness). */
487
+ const MIN_BOARDNESS = 0.5;
488
+ function sameBox(a, b) {
489
+ return (Math.abs(a.x0 - b.x0) <= 1 && Math.abs(a.y0 - b.y0) <= 1 && Math.abs(a.x1 - b.x1) <= 1 && Math.abs(a.y1 - b.y1) <= 1);
490
+ }
491
+ /** Half-size copy, each pixel the mean of a 2x2 block. */
492
+ function halve(img) {
493
+ const w = img.width >> 1;
494
+ const h = img.height >> 1;
495
+ const out = new Float32Array(w * h);
496
+ for (let y = 0; y < h; y++) {
497
+ const top = 2 * y * img.width;
498
+ const bottom = top + img.width;
499
+ for (let x = 0; x < w; x++) {
500
+ out[y * w + x] = (img.data[top + 2 * x] + img.data[top + 2 * x + 1] + img.data[bottom + 2 * x] + img.data[bottom + 2 * x + 1]) / 4;
501
+ }
502
+ }
503
+ return { data: out, width: w, height: h };
504
+ }
505
+ /**
506
+ * Second look: boards the plain search misses or misplaces because the
507
+ * board itself is full of edges. Hatched dark squares (printed diagrams,
508
+ * chess.com's newspaper board) put more gradient energy inside the
509
+ * squares than on the grid lines, and marbled or low-contrast boards can
510
+ * slide the grid one tile diagonally, which keeps the colouring and so
511
+ * slips past repairParity. On a blurred copy the hatching melts to grey
512
+ * and the grid lines dominate again.
513
+ *
514
+ * Returns the boxes found on blurred copies, each with its grid-snapped
515
+ * variant, that are square and look like a board, without duplicates and
516
+ * without anything in `known`. They are CANDIDATES: the caller lets the
517
+ * tile classifier choose (recognize.ts).
518
+ */
519
+ export function findBlurredBoardCandidates(img, known = []) {
520
+ const found = [];
521
+ const consider = (box) => {
522
+ const w = box.x1 - box.x0;
523
+ const h = box.y1 - box.y0;
524
+ if (w <= 0 || Math.abs(w - h) / w > MAX_ASPECT_ERROR)
525
+ return;
526
+ if (known.some((k) => sameBox(k, box)) || found.some((f) => sameBox(f, box)))
527
+ return;
528
+ if (boardness(img, box) < MIN_BOARDNESS)
529
+ return;
530
+ found.push(box);
531
+ };
532
+ const half = Math.max(img.width, img.height) > HALF_RES_ABOVE;
533
+ const base = half ? halve(img) : img;
534
+ const scale = half ? 2 : 1;
535
+ const up = (b) => ({ x0: b.x0 * scale, y0: b.y0 * scale, x1: b.x1 * scale, y1: b.y1 * scale });
536
+ for (const radius of half ? HALF_RES_BLUR_RADII : BLUR_RADII) {
537
+ const blurred = radius > 0 ? boxBlur(base, radius) : base;
538
+ const box = findChessboardCorners(blurred);
539
+ if (!box)
540
+ continue;
541
+ consider(up(box));
542
+ consider(up(snapCorners(blurred, box)));
543
+ }
544
+ return found;
545
+ }
379
546
  export function findChessboardCorners(img) {
380
547
  const gradY = gradientRows(img);
381
548
  const gradX = gradientCols(img);
package/dist/index.d.ts CHANGED
@@ -1,5 +1,5 @@
1
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";
2
+ export { findChessboardCorners, findBlurredBoardCandidates, boardness, snapCorners, type BoardCorners, type GrayImage, } from "./detect";
3
3
  export { extractBoardImage, boardToTiles, extractTiles, rgbaToGray } from "./tiles";
4
4
  export { probsToPlacement, flipPlacement, resolveOrientation, type RecognitionResult, } from "./fen";
5
5
  export { inferCastling, placementToFen } from "./compose";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { createRecognizer, recognizeGray, CONFIDENCE_FLOOR, } from "./recognize";
2
- export { findChessboardCorners, snapCorners, } from "./detect";
2
+ export { findChessboardCorners, findBlurredBoardCandidates, boardness, snapCorners, } from "./detect";
3
3
  export { extractBoardImage, boardToTiles, extractTiles, rgbaToGray } from "./tiles";
4
4
  export { probsToPlacement, flipPlacement, resolveOrientation, } from "./fen";
5
5
  export { inferCastling, placementToFen } from "./compose";
@@ -32,6 +32,14 @@ export interface BoardScanResult extends RecognitionResult {
32
32
  * sparse kingless scatters; callers doing automatic whole-page scans
33
33
  * should treat implausible reads as "no board found". */
34
34
  plausible: boolean;
35
+ /** Size of the image `corners` are measured in. `recognize` scales large
36
+ * sources down before it looks for a board, so divide by this to place
37
+ * the box on the source (set by `recognize`; absent from recognizeGray,
38
+ * whose caller supplied the image). */
39
+ frame?: {
40
+ width: number;
41
+ height: number;
42
+ };
35
43
  }
36
44
  export interface RecognizerOptions {
37
45
  /** URL of the tile classifier model (`chess-tiles-v2.onnx`, shipped
package/dist/recognize.js CHANGED
@@ -20,7 +20,7 @@
20
20
  * piece set, partial board) and the caller should route the user to
21
21
  * an editor with a warning rather than trusting the result.
22
22
  */
23
- import { findChessboardCorners, snapCorners } from "./detect";
23
+ import { boardness, findBlurredBoardCandidates, findChessboardCorners, snapCorners, } from "./detect";
24
24
  import { extractTiles, rgbaToGray } from "./tiles";
25
25
  import { probsToPlacement } from "./fen";
26
26
  export const CONFIDENCE_FLOOR = 0.7;
@@ -60,30 +60,68 @@ function isPlausiblePosition(placement) {
60
60
  * including this library's own UI); masking it and rescanning finds
61
61
  * the board the user actually means. */
62
62
  const MAX_SCAN_PASSES = 3;
63
- async function scanOnce(gray, classify) {
63
+ /** A first-look read this good needs no second look: confident on every
64
+ * tile, a legal king count, and a box that looks like a board. Normal
65
+ * chess.com and Lichess screenshots stop here, at the cost they always
66
+ * had. */
67
+ const SETTLED_BOARDNESS = 0.8;
68
+ /** Picking the most confident of several alignments flatters the
69
+ * winner: the maximum of noisy confidences is biased upward, so a wrong
70
+ * read can clear CONFIDENCE_FLOOR by luck. When another alignment is
71
+ * nearly as confident (within this margin of the winner's mean) and
72
+ * reads a DIFFERENT position, the read is contested and not reliable.
73
+ * Measured on the benchmark and 488 Reddit screenshots: 0.03 removes
74
+ * every silent misread the second look would otherwise add. */
75
+ const CONTEST_MARGIN = 0.03;
76
+ async function readAll(boxes, classify) {
77
+ const reads = [];
78
+ for (const corners of boxes)
79
+ reads.push({ result: await classify(corners), corners });
80
+ return reads;
81
+ }
82
+ /** Highest mean confidence; the earlier box wins a tie. */
83
+ function mostConfident(reads) {
84
+ let best = null;
85
+ for (const r of reads) {
86
+ if (!best || r.result.meanConfidence > best.result.meanConfidence)
87
+ best = r;
88
+ }
89
+ return best;
90
+ }
91
+ function firstLookBoxes(gray) {
64
92
  const corners = findChessboardCorners(gray);
65
93
  if (!corners)
66
- return null;
67
- let bestCorners = corners;
68
- let best = await classify(corners);
94
+ return [];
69
95
  const snapped = snapCorners(gray, corners);
70
- if (snapped.x0 !== corners.x0 ||
71
- snapped.y0 !== corners.y0 ||
72
- snapped.x1 !== corners.x1 ||
73
- snapped.y1 !== corners.y1) {
74
- const snappedRead = await classify(snapped);
75
- if (snappedRead.meanConfidence > best.meanConfidence) {
76
- best = snappedRead;
77
- bestCorners = snapped;
78
- }
79
- }
96
+ const same = snapped.x0 === corners.x0 && snapped.y0 === corners.y0 && snapped.x1 === corners.x1 && snapped.y1 === corners.y1;
97
+ return same ? [corners] : [corners, snapped];
98
+ }
99
+ function toScan(read, reliable) {
80
100
  return {
81
- ...best,
82
- corners: bestCorners,
83
- reliable: best.minConfidence >= CONFIDENCE_FLOOR,
84
- plausible: isPlausiblePosition(best.placement),
101
+ ...read.result,
102
+ corners: read.corners,
103
+ reliable,
104
+ plausible: isPlausiblePosition(read.result.placement),
85
105
  };
86
106
  }
107
+ async function scanOnce(gray, classify) {
108
+ const boxes = firstLookBoxes(gray);
109
+ const reads = await readAll(boxes, classify);
110
+ const first = mostConfident(reads);
111
+ if (first &&
112
+ first.result.minConfidence >= CONFIDENCE_FLOOR &&
113
+ isPlausiblePosition(first.result.placement) &&
114
+ boardness(gray, first.corners) >= SETTLED_BOARDNESS) {
115
+ return toScan(first, true);
116
+ }
117
+ reads.push(...(await readAll(findBlurredBoardCandidates(gray, boxes), classify)));
118
+ const best = mostConfident(reads);
119
+ if (!best)
120
+ return null;
121
+ const contested = reads.some((r) => r.result.placement !== best.result.placement &&
122
+ r.result.meanConfidence >= best.result.meanConfidence - CONTEST_MARGIN);
123
+ return toScan(best, best.result.minConfidence >= CONFIDENCE_FLOOR && !contested);
124
+ }
87
125
  /** Flatten a region so its gradients vanish and the detector cannot
88
126
  * lock onto it again on the next pass. */
89
127
  function maskRegion(gray, box) {
@@ -164,11 +202,12 @@ export function createRecognizer(options) {
164
202
  const img = source instanceof File || source instanceof Blob ? await createImageBitmap(source) : source;
165
203
  const gray = imageToGray(img);
166
204
  const [ort, session] = await Promise.all([loadOrt(), getSession()]);
167
- return recognizeGray(gray, async (c) => {
205
+ const scan = await recognizeGray(gray, async (c) => {
168
206
  const tiles = extractTiles(gray, c);
169
207
  const out = await session.run({ tiles: new ort.Tensor("float32", tiles, [64, 1024]) });
170
208
  return probsToPlacement(out["probs"].data);
171
209
  });
210
+ return scan && { ...scan, frame: { width: gray.width, height: gray.height } };
172
211
  },
173
212
  };
174
213
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@scoriiu/fenshot",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
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",