@kibitzo/chess-book-reader 0.0.0-stage → 0.2.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 +36 -2
- package/dist/Library.d.ts +11 -0
- package/dist/Library.js +74 -0
- package/dist/PageView.d.ts +29 -0
- package/dist/PageView.js +80 -0
- package/dist/ReadApp.d.ts +9 -0
- package/dist/ReadApp.js +126 -0
- package/dist/Reader.d.ts +8 -0
- package/dist/Reader.js +117 -0
- package/dist/ReaderBar.d.ts +32 -0
- package/dist/ReaderBar.js +36 -0
- package/dist/SideGrip.d.ts +12 -0
- package/dist/SideGrip.js +66 -0
- package/dist/find.d.ts +64 -0
- package/dist/find.js +275 -0
- package/dist/host.d.ts +97 -0
- package/dist/host.js +66 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +3 -0
- package/dist/pdf.d.ts +54 -0
- package/dist/pdf.js +131 -0
- package/dist/protocol.d.ts +64 -0
- package/dist/protocol.js +7 -0
- package/dist/reader.css +1084 -0
- package/dist/search.d.ts +18 -0
- package/dist/search.js +45 -0
- package/dist/store.d.ts +63 -0
- package/dist/store.js +103 -0
- package/dist/useDiagrams.d.ts +25 -0
- package/dist/useDiagrams.js +208 -0
- package/dist/usePages.d.ts +18 -0
- package/dist/usePages.js +148 -0
- package/dist/worker.d.ts +1 -0
- package/dist/worker.js +78 -0
- package/package.json +59 -4
package/dist/SideGrip.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { jsx as _jsx } from "react/jsx-runtime";
|
|
2
|
+
import { useRef } from "react";
|
|
3
|
+
/**
|
|
4
|
+
* The edge between the book and the board: drag it to give the board more room or less, press the arrow keys for
|
|
5
|
+
* small steps, double-click for the width it came with. The width is kept on this device. While the edge is
|
|
6
|
+
* dragged only a CSS variable on the reader changes (no render); the reader learns the new width when it is let go.
|
|
7
|
+
*/
|
|
8
|
+
export const SIDE_DEFAULT = 480;
|
|
9
|
+
const SIDE_MIN = 340, STEP = 24, KEY = "fenshot-read-side";
|
|
10
|
+
const widest = () => Math.max(SIDE_MIN, Math.round(window.innerWidth * 0.62));
|
|
11
|
+
const held = (w) => Math.round(Math.min(widest(), Math.max(SIDE_MIN, w)));
|
|
12
|
+
export function storedSide() {
|
|
13
|
+
try {
|
|
14
|
+
const kept = Number(localStorage.getItem(KEY));
|
|
15
|
+
return kept > 0 ? held(kept) : SIDE_DEFAULT;
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
return SIDE_DEFAULT;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export function SideGrip({ width, label, onWidth }) {
|
|
22
|
+
const now = useRef(width);
|
|
23
|
+
const settle = (w) => {
|
|
24
|
+
const next = held(w);
|
|
25
|
+
try {
|
|
26
|
+
localStorage.setItem(KEY, String(next));
|
|
27
|
+
}
|
|
28
|
+
catch { /* a private window: the width lasts the visit */ }
|
|
29
|
+
onWidth(next);
|
|
30
|
+
};
|
|
31
|
+
const press = (down) => {
|
|
32
|
+
if (down.button > 0)
|
|
33
|
+
return;
|
|
34
|
+
const grip = down.currentTarget, reader = grip.closest(".rd");
|
|
35
|
+
if (!reader)
|
|
36
|
+
return;
|
|
37
|
+
down.preventDefault();
|
|
38
|
+
grip.setPointerCapture(down.pointerId);
|
|
39
|
+
const rtl = getComputedStyle(reader).direction === "rtl";
|
|
40
|
+
reader.classList.add("rd-resizing");
|
|
41
|
+
const move = (e) => {
|
|
42
|
+
now.current = held(rtl ? e.clientX : window.innerWidth - e.clientX);
|
|
43
|
+
reader.style.setProperty("--rd-side", `${now.current}px`);
|
|
44
|
+
};
|
|
45
|
+
const up = () => {
|
|
46
|
+
grip.removeEventListener("pointermove", move);
|
|
47
|
+
grip.removeEventListener("pointerup", up);
|
|
48
|
+
grip.removeEventListener("pointercancel", up);
|
|
49
|
+
reader.classList.remove("rd-resizing");
|
|
50
|
+
settle(now.current);
|
|
51
|
+
};
|
|
52
|
+
now.current = width;
|
|
53
|
+
grip.addEventListener("pointermove", move);
|
|
54
|
+
grip.addEventListener("pointerup", up);
|
|
55
|
+
grip.addEventListener("pointercancel", up);
|
|
56
|
+
};
|
|
57
|
+
const key = (e) => {
|
|
58
|
+
const rtl = getComputedStyle(e.currentTarget).direction === "rtl";
|
|
59
|
+
const wider = rtl ? "ArrowRight" : "ArrowLeft", narrower = rtl ? "ArrowLeft" : "ArrowRight";
|
|
60
|
+
if (e.key !== wider && e.key !== narrower)
|
|
61
|
+
return;
|
|
62
|
+
e.preventDefault();
|
|
63
|
+
settle(width + (e.key === wider ? STEP : -STEP));
|
|
64
|
+
};
|
|
65
|
+
return (_jsx("div", { className: "rd-grip", role: "separator", "aria-orientation": "vertical", "aria-label": label, "aria-valuenow": width, "aria-valuemin": SIDE_MIN, "aria-valuemax": widest(), tabIndex: 0, onPointerDown: press, onKeyDown: key, onDoubleClick: () => settle(SIDE_DEFAULT), "data-testid": "read-grip" }));
|
|
66
|
+
}
|
package/dist/find.d.ts
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diagrams on a page of a book. Three ways in:
|
|
3
|
+
* - findDiagrams reads a whole page in the background: the board finder is run, what it found is covered, and it
|
|
4
|
+
* is run again, so a page with several diagrams gives them all;
|
|
5
|
+
* - readAt reads the diagram under a double-click, for a diagram the background pass missed: a window around
|
|
6
|
+
* the click, then wider ones, until a board is found that the click is on;
|
|
7
|
+
* - readBox reads the diagram in a box the reader drew.
|
|
8
|
+
* Measured 2026-12-05 on a modern typeset book (41 pages): a board found on 37, every one read with all squares
|
|
9
|
+
* at 75% or more. An old scanned printing reads far worse; such a read opens in the editor to be checked.
|
|
10
|
+
*/
|
|
11
|
+
import { type BoardScanResult } from "@scoriiu/fenshot";
|
|
12
|
+
import type { Diagram } from "./store";
|
|
13
|
+
/**
|
|
14
|
+
* All of this runs in the search worker (worker.ts), off the page's thread, on canvases of its own: nothing here
|
|
15
|
+
* may touch the document.
|
|
16
|
+
*/
|
|
17
|
+
type Canvas = OffscreenCanvas;
|
|
18
|
+
/** The model, as the worker holds it: what it reads in a picture, with the size of the frame it looked at. */
|
|
19
|
+
export interface Scanner {
|
|
20
|
+
recognize(source: Canvas): Promise<(BoardScanResult & {
|
|
21
|
+
frame: {
|
|
22
|
+
width: number;
|
|
23
|
+
height: number;
|
|
24
|
+
};
|
|
25
|
+
}) | null>;
|
|
26
|
+
}
|
|
27
|
+
type Rect = [x: number, y: number, w: number, h: number];
|
|
28
|
+
/** A read worth showing as a diagram without being asked: every square at least this sure. */
|
|
29
|
+
export declare const SURE = 0.6;
|
|
30
|
+
/**
|
|
31
|
+
* Black to move, as many books print it: a filled mark (a triangle, a square, a disc) beside the board's right
|
|
32
|
+
* edge, level with its bottom rank or its top one. A hollow mark, or none, says nothing here. The mark is told
|
|
33
|
+
* from the rank numbers some books print on that side by its shape: about as wide as tall, and filled.
|
|
34
|
+
* Seen 2026-12-05 in a book of exercises: 18 of its 44 diagrams carry the filled mark, and each of them has a
|
|
35
|
+
* mate in one for Black. The box is the board in the canvas's pixels.
|
|
36
|
+
*/
|
|
37
|
+
export declare function blackMarked(page: Canvas, x0: number, y0: number, x1: number, y1: number): boolean;
|
|
38
|
+
/** A board in a book is square and takes a real share of the page's width. */
|
|
39
|
+
export declare function plausible(x0: number, y0: number, x1: number, y1: number, pageW: number): boolean;
|
|
40
|
+
/** The windows to read around a click, nearest first. */
|
|
41
|
+
export declare function windowsAt(pageW: number, pageH: number, cx: number, cy: number): Rect[];
|
|
42
|
+
/** The diagram at a point of the page (fractions), or null when no board is found there. */
|
|
43
|
+
export declare function readAt(scanner: Scanner, page: Canvas, fx: number, fy: number): Promise<Diagram | null>;
|
|
44
|
+
/**
|
|
45
|
+
* The diagram in a box the reader drew on the page (fractions of the page), for one neither the search nor a
|
|
46
|
+
* double-click found: the box with a little room around it, then the box itself. Null when it cannot be read.
|
|
47
|
+
*/
|
|
48
|
+
export declare function readBox(scanner: Scanner, page: Canvas, box: {
|
|
49
|
+
x0: number;
|
|
50
|
+
y0: number;
|
|
51
|
+
x1: number;
|
|
52
|
+
y1: number;
|
|
53
|
+
}): Promise<Diagram | null>;
|
|
54
|
+
/**
|
|
55
|
+
* Every diagram of a page that reads surely, told one by one as it is found (`onFound`). A look asks first whether
|
|
56
|
+
* anything looks like a board (boardOn); only then the model reads. What was looked at is covered and the page is
|
|
57
|
+
* looked at again. On a page of several diagrams the look at the whole page can stop seeing the rest once some are
|
|
58
|
+
* covered (measured 2026-12-05: 2 of a page's 4, a book of exercises in two columns), so the places where the
|
|
59
|
+
* found ones leave a gap in their rows and columns are then looked at one by one (gapsIn). Looking at every part
|
|
60
|
+
* of every such page instead found the same diagrams and took four times as long (325 s against 83 s on a book
|
|
61
|
+
* of 187 pages). The page's canvas is drawn over: pass a copy.
|
|
62
|
+
*/
|
|
63
|
+
export declare function findDiagrams(scanner: Scanner, page: Canvas, onFound?: (d: Diagram) => void): Promise<Diagram[]>;
|
|
64
|
+
export {};
|
package/dist/find.js
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Diagrams on a page of a book. Three ways in:
|
|
3
|
+
* - findDiagrams reads a whole page in the background: the board finder is run, what it found is covered, and it
|
|
4
|
+
* is run again, so a page with several diagrams gives them all;
|
|
5
|
+
* - readAt reads the diagram under a double-click, for a diagram the background pass missed: a window around
|
|
6
|
+
* the click, then wider ones, until a board is found that the click is on;
|
|
7
|
+
* - readBox reads the diagram in a box the reader drew.
|
|
8
|
+
* Measured 2026-12-05 on a modern typeset book (41 pages): a board found on 37, every one read with all squares
|
|
9
|
+
* at 75% or more. An old scanned printing reads far worse; such a read opens in the editor to be checked.
|
|
10
|
+
*/
|
|
11
|
+
import { boardness, findBlurredBoardCandidates, findChessboardCorners, rgbaToGray, snapCorners } from "@scoriiu/fenshot";
|
|
12
|
+
/** A read worth showing as a diagram without being asked: every square at least this sure. */
|
|
13
|
+
export const SURE = 0.6;
|
|
14
|
+
/** A page of exercises holds six or eight diagrams, sometimes twelve. Each look finds one. */
|
|
15
|
+
const MAX_LOOKS = 24;
|
|
16
|
+
/**
|
|
17
|
+
* A read worth opening at all. On a print the model does not know (an old scan with hatched squares) it answers
|
|
18
|
+
* with scattered pieces at 15% to 40% on its worst square, also where there is only text: showing that as the
|
|
19
|
+
* book's position would be a lie. Between this and SURE the board opens with a word of caution.
|
|
20
|
+
*/
|
|
21
|
+
const READABLE_MIN = 0.45, READABLE_MEAN = 0.85;
|
|
22
|
+
const readable = (r) => r.minConfidence >= READABLE_MIN && r.meanConfidence >= READABLE_MEAN && r.placement !== "8/8/8/8/8/8/8/8";
|
|
23
|
+
/**
|
|
24
|
+
* Black to move, as many books print it: a filled mark (a triangle, a square, a disc) beside the board's right
|
|
25
|
+
* edge, level with its bottom rank or its top one. A hollow mark, or none, says nothing here. The mark is told
|
|
26
|
+
* from the rank numbers some books print on that side by its shape: about as wide as tall, and filled.
|
|
27
|
+
* Seen 2026-12-05 in a book of exercises: 18 of its 44 diagrams carry the filled mark, and each of them has a
|
|
28
|
+
* mate in one for Black. The box is the board in the canvas's pixels.
|
|
29
|
+
*/
|
|
30
|
+
export function blackMarked(page, x0, y0, x1, y1) {
|
|
31
|
+
const side = x1 - x0, pen = page.getContext("2d", { willReadFrequently: true });
|
|
32
|
+
const left = Math.round(x1 + side * 0.01), width = Math.min(page.width - left, Math.round(side * 0.2));
|
|
33
|
+
if (!pen || width < 6)
|
|
34
|
+
return false;
|
|
35
|
+
const filledMark = (top, height) => {
|
|
36
|
+
const y = Math.max(0, Math.round(top)), hgt = Math.min(page.height - y, Math.round(height));
|
|
37
|
+
if (hgt < 6)
|
|
38
|
+
return false;
|
|
39
|
+
const px = pen.getImageData(left, y, width, hgt).data;
|
|
40
|
+
const dark = (i) => px[i * 4] * 0.3 + px[i * 4 + 1] * 0.59 + px[i * 4 + 2] * 0.11 < 110;
|
|
41
|
+
const seen = new Uint8Array(width * hgt);
|
|
42
|
+
for (let start = 0; start < width * hgt; start++) {
|
|
43
|
+
if (seen[start] || !dark(start))
|
|
44
|
+
continue;
|
|
45
|
+
// One blot of ink: its box and how much of the box it fills.
|
|
46
|
+
let minX = width, maxX = 0, minY = hgt, maxY = 0, ink = 0;
|
|
47
|
+
const todo = [start];
|
|
48
|
+
seen[start] = 1;
|
|
49
|
+
while (todo.length) {
|
|
50
|
+
const i = todo.pop(), cx = i % width, cy = (i - cx) / width;
|
|
51
|
+
ink++;
|
|
52
|
+
minX = Math.min(minX, cx);
|
|
53
|
+
maxX = Math.max(maxX, cx);
|
|
54
|
+
minY = Math.min(minY, cy);
|
|
55
|
+
maxY = Math.max(maxY, cy);
|
|
56
|
+
for (const [nx, ny] of [[cx - 1, cy], [cx + 1, cy], [cx, cy - 1], [cx, cy + 1]]) {
|
|
57
|
+
const j = ny * width + nx;
|
|
58
|
+
if (nx < 0 || ny < 0 || nx >= width || ny >= hgt || seen[j] || !dark(j))
|
|
59
|
+
continue;
|
|
60
|
+
seen[j] = 1;
|
|
61
|
+
todo.push(j);
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
const bw = maxX - minX + 1, bh = maxY - minY + 1;
|
|
65
|
+
const sized = bw >= side * 0.03 && bh >= side * 0.03 && bw <= side * 0.14 && bh <= side * 0.14;
|
|
66
|
+
if (sized && bw / bh > 0.62 && bw / bh < 1.6 && ink / (bw * bh) >= 0.42)
|
|
67
|
+
return true;
|
|
68
|
+
}
|
|
69
|
+
return false;
|
|
70
|
+
};
|
|
71
|
+
return filledMark(y1 - side * 0.16, side * 0.2) || filledMark(y0 - side * 0.04, side * 0.2);
|
|
72
|
+
}
|
|
73
|
+
/** A board in a book is square and takes a real share of the page's width. */
|
|
74
|
+
export function plausible(x0, y0, x1, y1, pageW) {
|
|
75
|
+
const w = x1 - x0, h = y1 - y0;
|
|
76
|
+
return w > pageW * 0.12 && w < pageW * 0.85 && Math.abs(w - h) < w * 0.12;
|
|
77
|
+
}
|
|
78
|
+
/** The windows to read around a click, nearest first. */
|
|
79
|
+
export function windowsAt(pageW, pageH, cx, cy) {
|
|
80
|
+
const square = (share) => {
|
|
81
|
+
const side = Math.min(pageW * share, pageH);
|
|
82
|
+
const x = Math.min(Math.max(0, cx - side / 2), pageW - side), y = Math.min(Math.max(0, cy - side / 2), pageH - side);
|
|
83
|
+
return [Math.round(x), Math.round(y), Math.round(side), Math.round(side)];
|
|
84
|
+
};
|
|
85
|
+
const band = Math.min(pageH, pageW * 1.2);
|
|
86
|
+
const top = Math.min(Math.max(0, cy - band / 2), pageH - band);
|
|
87
|
+
return [square(0.5), square(0.8), [0, Math.round(top), pageW, Math.round(band)], [0, 0, pageW, pageH]];
|
|
88
|
+
}
|
|
89
|
+
/** The board's corners in the pixels of what was read: the recognizer answers in its own, smaller frame. */
|
|
90
|
+
function inPixels(r, width) {
|
|
91
|
+
const k = width / r.frame.width;
|
|
92
|
+
return { x0: r.corners.x0 * k, y0: r.corners.y0 * k, x1: r.corners.x1 * k, y1: r.corners.y1 * k };
|
|
93
|
+
}
|
|
94
|
+
async function read(scanner, source, [x, y, w, h], pageW, pageH) {
|
|
95
|
+
const part = new OffscreenCanvas(w, h);
|
|
96
|
+
part.getContext("2d")?.drawImage(source, x, y, w, h, 0, 0, w, h);
|
|
97
|
+
const r = await scanner.recognize(part);
|
|
98
|
+
if (!r || !readable(r))
|
|
99
|
+
return null;
|
|
100
|
+
const { x0, y0, x1, y1 } = inPixels(r, w);
|
|
101
|
+
if (!plausible(x0, y0, x1, y1, pageW))
|
|
102
|
+
return null;
|
|
103
|
+
const d = { x0: (x + x0) / pageW, y0: (y + y0) / pageH, x1: (x + x1) / pageW, y1: (y + y1) / pageH, placement: r.placement, flipped: false, min: r.minConfidence, mean: r.meanConfidence };
|
|
104
|
+
return blackMarked(source, x + x0, y + y0, x + x1, y + y1) ? { ...d, turn: "b" } : d;
|
|
105
|
+
}
|
|
106
|
+
const holds = (d, fx, fy) => {
|
|
107
|
+
const padX = (d.x1 - d.x0) * 0.06, padY = (d.y1 - d.y0) * 0.06;
|
|
108
|
+
return fx >= d.x0 - padX && fx <= d.x1 + padX && fy >= d.y0 - padY && fy <= d.y1 + padY;
|
|
109
|
+
};
|
|
110
|
+
/** The diagram at a point of the page (fractions), or null when no board is found there. */
|
|
111
|
+
export async function readAt(scanner, page, fx, fy) {
|
|
112
|
+
const { width: w, height: h } = page;
|
|
113
|
+
let best = null;
|
|
114
|
+
for (const rect of windowsAt(w, h, fx * w, fy * h)) {
|
|
115
|
+
const d = await read(scanner, page, rect, w, h);
|
|
116
|
+
if (!d || !holds(d, fx, fy))
|
|
117
|
+
continue;
|
|
118
|
+
if (d.min >= SURE)
|
|
119
|
+
return d;
|
|
120
|
+
if (!best || d.mean > best.mean)
|
|
121
|
+
best = d;
|
|
122
|
+
}
|
|
123
|
+
return best;
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* The diagram in a box the reader drew on the page (fractions of the page), for one neither the search nor a
|
|
127
|
+
* double-click found: the box with a little room around it, then the box itself. Null when it cannot be read.
|
|
128
|
+
*/
|
|
129
|
+
export async function readBox(scanner, page, box) {
|
|
130
|
+
const { width: w, height: h } = page;
|
|
131
|
+
const x0 = box.x0 * w, y0 = box.y0 * h, bw = (box.x1 - box.x0) * w, bh = (box.y1 - box.y0) * h;
|
|
132
|
+
for (const room of [0.08, 0]) {
|
|
133
|
+
const left = Math.max(0, Math.round(x0 - bw * room)), top = Math.max(0, Math.round(y0 - bh * room));
|
|
134
|
+
const right = Math.min(w, Math.round(x0 + bw * (1 + room))), bottom = Math.min(h, Math.round(y0 + bh * (1 + room)));
|
|
135
|
+
const d = await read(scanner, page, [left, top, right - left, bottom - top], w, h);
|
|
136
|
+
if (d)
|
|
137
|
+
return d;
|
|
138
|
+
}
|
|
139
|
+
return null;
|
|
140
|
+
}
|
|
141
|
+
/** A square that looks like a board this much (see `boardness`) is read; below it the page has no more boards. */
|
|
142
|
+
const BOARDLIKE = 0.6;
|
|
143
|
+
/** The page in greys, at the size the recognizer looks at, and that size over the page's. */
|
|
144
|
+
function greysOf(page, scratch) {
|
|
145
|
+
const k = Math.min(1, 1600 / Math.max(page.width, page.height));
|
|
146
|
+
scratch.width = Math.round(page.width * k);
|
|
147
|
+
scratch.height = Math.round(page.height * k);
|
|
148
|
+
const pen = scratch.getContext("2d", { willReadFrequently: true });
|
|
149
|
+
if (!pen)
|
|
150
|
+
return null;
|
|
151
|
+
pen.drawImage(page, 0, 0, scratch.width, scratch.height);
|
|
152
|
+
return { greys: rgbaToGray(pen.getImageData(0, 0, scratch.width, scratch.height).data, scratch.width, scratch.height), k };
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* The most board-like square on a page, in the page's pixels, or null when nothing on it looks like a board.
|
|
156
|
+
* This is the cheap question, asked before the model is: measured 2026-12-05 on three books, every diagram the
|
|
157
|
+
* model then read surely scored 0.97 or more here (53 of 53), and no stretch of text scored over 0.29 (74 of
|
|
158
|
+
* 74). A page of text costs about 150 ms this way; asking the model about it cost 400 ms, and three to eight
|
|
159
|
+
* seconds when it was asked again and again.
|
|
160
|
+
*/
|
|
161
|
+
function boardOn(page, scratch, pageW = page.width) {
|
|
162
|
+
const seen = greysOf(page, scratch);
|
|
163
|
+
if (!seen)
|
|
164
|
+
return null;
|
|
165
|
+
const { greys, k } = seen;
|
|
166
|
+
const raw = findChessboardCorners(greys);
|
|
167
|
+
let best = null, score = BOARDLIKE;
|
|
168
|
+
for (const c of [...(raw ? [raw, snapCorners(greys, raw)] : []), ...findBlurredBoardCandidates(greys, [])]) {
|
|
169
|
+
if (!plausible(c.x0 / k, c.y0 / k, c.x1 / k, c.y1 / k, pageW))
|
|
170
|
+
continue;
|
|
171
|
+
const b = boardness(greys, c);
|
|
172
|
+
if (b >= score) {
|
|
173
|
+
best = c;
|
|
174
|
+
score = b;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return best && { x0: best.x0 / k, y0: best.y0 / k, x1: best.x1 / k, y1: best.y1 / k };
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* One look at a region of the page (the whole page, or a window of it): is a board there, and if so what does the
|
|
181
|
+
* model read. Answers the box to cover before the next look (null when nothing board-like is left) and the
|
|
182
|
+
* diagram when it read surely. Boxes are in the page's pixels.
|
|
183
|
+
*/
|
|
184
|
+
async function lookIn(scanner, page, [x, y, w, h], scratch, crop) {
|
|
185
|
+
const whole = x === 0 && y === 0 && w === page.width && h === page.height;
|
|
186
|
+
const region = whole ? page : crop;
|
|
187
|
+
if (!whole) {
|
|
188
|
+
crop.width = w;
|
|
189
|
+
crop.height = h;
|
|
190
|
+
crop.getContext("2d")?.drawImage(page, x, y, w, h, 0, 0, w, h);
|
|
191
|
+
}
|
|
192
|
+
const box = boardOn(region, scratch, page.width);
|
|
193
|
+
if (!box)
|
|
194
|
+
return null;
|
|
195
|
+
const r = await scanner.recognize(region);
|
|
196
|
+
const shift = (b) => ({ x0: b.x0 + x, y0: b.y0 + y, x1: b.x1 + x, y1: b.y1 + y });
|
|
197
|
+
const read = r && shift(inPixels(r, w));
|
|
198
|
+
if (!r || !read || !plausible(read.x0, read.y0, read.x1, read.y1, page.width) || r.minConfidence < SURE)
|
|
199
|
+
return { cover: shift(box), diagram: null };
|
|
200
|
+
const { width: pw, height: ph } = page;
|
|
201
|
+
const d = { x0: read.x0 / pw, y0: read.y0 / ph, x1: read.x1 / pw, y1: read.y1 / ph, placement: r.placement, flipped: false, min: r.minConfidence, mean: r.meanConfidence };
|
|
202
|
+
if (blackMarked(page, read.x0, read.y0, read.x1, read.y1))
|
|
203
|
+
d.turn = "b";
|
|
204
|
+
return { cover: read, diagram: d };
|
|
205
|
+
}
|
|
206
|
+
/**
|
|
207
|
+
* Where more diagrams are likely, from those already found: a book sets its diagrams in rows and columns, all of
|
|
208
|
+
* one size, so every crossing of a found column with a found row that holds no diagram yet is a place to look.
|
|
209
|
+
* A page with one diagram, or with all of its grid found, gives none: the common case costs nothing.
|
|
210
|
+
*/
|
|
211
|
+
function gapsIn(found, w, h) {
|
|
212
|
+
if (found.length < 2)
|
|
213
|
+
return [];
|
|
214
|
+
const side = found.map((d) => (d.x1 - d.x0) * w).sort((a, b) => a - b)[found.length >> 1], near = side * 0.25;
|
|
215
|
+
const lines = (values) => values.sort((a, b) => a - b).filter((v, i, all) => i === 0 || v - all[i - 1] > near);
|
|
216
|
+
const out = [];
|
|
217
|
+
for (const top of lines(found.map((d) => d.y0 * h))) {
|
|
218
|
+
for (const left of lines(found.map((d) => d.x0 * w))) {
|
|
219
|
+
if (found.some((d) => Math.abs(d.x0 * w - left) <= near && Math.abs(d.y0 * h - top) <= near))
|
|
220
|
+
continue;
|
|
221
|
+
const room = side * 0.18, x = Math.max(0, Math.round(left - room)), y = Math.max(0, Math.round(top - room));
|
|
222
|
+
out.push([x, y, Math.min(w - x, Math.round(side + 2 * room)), Math.min(h - y, Math.round(side + 2 * room))]);
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
/**
|
|
228
|
+
* Every diagram of a page that reads surely, told one by one as it is found (`onFound`). A look asks first whether
|
|
229
|
+
* anything looks like a board (boardOn); only then the model reads. What was looked at is covered and the page is
|
|
230
|
+
* looked at again. On a page of several diagrams the look at the whole page can stop seeing the rest once some are
|
|
231
|
+
* covered (measured 2026-12-05: 2 of a page's 4, a book of exercises in two columns), so the places where the
|
|
232
|
+
* found ones leave a gap in their rows and columns are then looked at one by one (gapsIn). Looking at every part
|
|
233
|
+
* of every such page instead found the same diagrams and took four times as long (325 s against 83 s on a book
|
|
234
|
+
* of 187 pages). The page's canvas is drawn over: pass a copy.
|
|
235
|
+
*/
|
|
236
|
+
export async function findDiagrams(scanner, page, onFound) {
|
|
237
|
+
const { width: w, height: h } = page;
|
|
238
|
+
const pen = page.getContext("2d");
|
|
239
|
+
if (!pen)
|
|
240
|
+
return [];
|
|
241
|
+
const scratch = new OffscreenCanvas(1, 1), crop = new OffscreenCanvas(1, 1);
|
|
242
|
+
const found = [];
|
|
243
|
+
let looks = 0;
|
|
244
|
+
const search = async (rect, tries) => {
|
|
245
|
+
for (let i = 0; i < tries && looks < MAX_LOOKS; i++, looks++) {
|
|
246
|
+
const seen = await lookIn(scanner, page, rect, scratch, crop);
|
|
247
|
+
if (!seen)
|
|
248
|
+
return;
|
|
249
|
+
const d = seen.diagram;
|
|
250
|
+
if (d && !found.some((f) => overlap(f, d) > 0.5)) {
|
|
251
|
+
found.push(d);
|
|
252
|
+
onFound?.(d);
|
|
253
|
+
}
|
|
254
|
+
// Cover what was read, or the board that could not be, and look again for another.
|
|
255
|
+
const { cover } = seen, pad = (cover.x1 - cover.x0) * 0.05;
|
|
256
|
+
pen.fillStyle = "#fff";
|
|
257
|
+
pen.fillRect(cover.x0 - pad, cover.y0 - pad, cover.x1 - cover.x0 + 2 * pad, cover.y1 - cover.y0 + 2 * pad);
|
|
258
|
+
}
|
|
259
|
+
};
|
|
260
|
+
await search([0, 0, w, h], MAX_LOOKS);
|
|
261
|
+
// A gap that is filled can open another (a third row found through its second column), so ask again, a few times.
|
|
262
|
+
for (let round = 0; round < 3; round++) {
|
|
263
|
+
const before = found.length;
|
|
264
|
+
for (const rect of gapsIn(found, w, h))
|
|
265
|
+
await search(rect, 1);
|
|
266
|
+
if (found.length === before)
|
|
267
|
+
break;
|
|
268
|
+
}
|
|
269
|
+
return found.sort((a, b) => a.y0 - b.y0 || a.x0 - b.x0);
|
|
270
|
+
}
|
|
271
|
+
/** How much of the smaller of two diagrams the other covers, 0..1. */
|
|
272
|
+
function overlap(a, b) {
|
|
273
|
+
const x = Math.max(0, Math.min(a.x1, b.x1) - Math.max(a.x0, b.x0)), y = Math.max(0, Math.min(a.y1, b.y1) - Math.max(a.y0, b.y0));
|
|
274
|
+
return (x * y) / Math.min((a.x1 - a.x0) * (a.y1 - a.y0), (b.x1 - b.x0) * (b.y1 - b.y0));
|
|
275
|
+
}
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
import { type ComponentType, type ReactNode } from "react";
|
|
2
|
+
import type { Recognition } from "./protocol";
|
|
3
|
+
import type { Diagram } from "./store";
|
|
4
|
+
/**
|
|
5
|
+
* What a site gives the reader: where the model and pdf.js's files are, the search worker, its words, where to
|
|
6
|
+
* count what readers do, and the board beside the page. fenshot.com and kibitzo.com each give their own; the
|
|
7
|
+
* reader itself (finding diagrams, the pages, the library) is this one package, so the two can never drift.
|
|
8
|
+
*/
|
|
9
|
+
export interface Picked {
|
|
10
|
+
page: number;
|
|
11
|
+
diagram: Diagram;
|
|
12
|
+
/** Nothing could be read where the reader pointed: an empty board to set up, the book beside it. */
|
|
13
|
+
byHand?: boolean;
|
|
14
|
+
}
|
|
15
|
+
export interface BoardPanelProps {
|
|
16
|
+
picked: Picked;
|
|
17
|
+
onClose(): void;
|
|
18
|
+
}
|
|
19
|
+
export interface ReaderHost {
|
|
20
|
+
/** Where the tile model (@scoriiu/fenshot's chess-tiles-v2.onnx) and onnxruntime-web's wasm files are served. */
|
|
21
|
+
recognition: Recognition;
|
|
22
|
+
/**
|
|
23
|
+
* Start the search worker. The site has a file of one line, `import "@kibitzo/chess-book-reader/worker"`, and
|
|
24
|
+
* answers here with `new Worker(new URL("./that-file", import.meta.url), { type: "module" })`, so its own
|
|
25
|
+
* bundler builds the worker. Called once for a book that is opened; the reader ends it.
|
|
26
|
+
*/
|
|
27
|
+
searchWorker(): Worker;
|
|
28
|
+
/** pdf.js: its worker, and a base address holding wasm/, cmaps/, standard_fonts/ and iccs/ (scripts/sync-pdfjs.mjs). */
|
|
29
|
+
pdf: {
|
|
30
|
+
workerSrc: string;
|
|
31
|
+
assets: string;
|
|
32
|
+
};
|
|
33
|
+
t(key: ReaderKey, vars?: Record<string, string | number>): string;
|
|
34
|
+
/** One anonymous count of something a reader did. Never the book, a page or a position. */
|
|
35
|
+
track?(event: string, data?: Record<string, string | number | boolean>): void;
|
|
36
|
+
/** The board beside the page, inside the reader's side panel (a bottom sheet on a phone). */
|
|
37
|
+
BoardPanel: ComponentType<BoardPanelProps>;
|
|
38
|
+
/** Over the library: the site's own header. */
|
|
39
|
+
header?: ReactNode;
|
|
40
|
+
/** Under the place to drop a book, while the library is empty (a demo film, say). */
|
|
41
|
+
emptyLibrary?: ReactNode;
|
|
42
|
+
}
|
|
43
|
+
export declare const READER_EN: {
|
|
44
|
+
readonly readWhy1: "Every diagram, counted";
|
|
45
|
+
readonly readWhy1Sub: "fenshot goes through the whole book as you read. The bar says how many diagrams it holds, and its arrows take you from one to the next.";
|
|
46
|
+
readonly readWhy2: "Play it, or play Boris";
|
|
47
|
+
readonly readWhy2Sub: "A click puts a diagram on a board next to the page: legal moves, Stockfish if you ask for it, and a game against Kibitzo's coach from that position.";
|
|
48
|
+
readonly readWhy3: "Your PDF stays with you";
|
|
49
|
+
readonly readWhy3Sub: "The book is read by your browser and kept on this computer, never uploaded. It opens again on the page where you left it.";
|
|
50
|
+
readonly readAddBook: "Add a book";
|
|
51
|
+
readonly readByHand: "Set it up by hand";
|
|
52
|
+
readonly readCancel: "Cancel";
|
|
53
|
+
readonly readCantOpen: "This PDF could not be opened.";
|
|
54
|
+
readonly readChoose: "Open a PDF";
|
|
55
|
+
readonly readContents: "Contents";
|
|
56
|
+
readonly readDiagramNext: "Next diagram";
|
|
57
|
+
readonly readDiagramPrev: "Previous diagram";
|
|
58
|
+
readonly readDiagrams: "{n} diagrams in this book";
|
|
59
|
+
readonly readDiagramsShort: "{n} diagrams";
|
|
60
|
+
readonly readDropSub: "or drop it anywhere on this page";
|
|
61
|
+
readonly readDropTitle: "Open a chess book";
|
|
62
|
+
readonly readFinding: "Finding the diagrams: {done} of {pages} pages";
|
|
63
|
+
readonly readGoToPage: "Go to page";
|
|
64
|
+
readonly readHint: "Double-click a diagram";
|
|
65
|
+
readonly readHintSub: "It opens here as a board you can play on. The arrows at the top go from one diagram to the next.";
|
|
66
|
+
readonly readLibrary: "Library";
|
|
67
|
+
readonly readMore: "More";
|
|
68
|
+
readonly readNoDiagram: "No diagram could be read there.";
|
|
69
|
+
readonly readNotPdf: "That file is not a PDF.";
|
|
70
|
+
readonly readOpen: "Open";
|
|
71
|
+
readonly readOpenAt: "Open at page {page}";
|
|
72
|
+
readonly readOpening: "Opening your book…";
|
|
73
|
+
readonly readPageOf: "Page {page} of {pages}";
|
|
74
|
+
readonly readPrivate: "Read inside your browser. Your book is never uploaded.";
|
|
75
|
+
readonly readRemove: "Remove";
|
|
76
|
+
readonly readRemoveAsk: "Remove this book from this device?";
|
|
77
|
+
readonly readRename: "Rename";
|
|
78
|
+
readonly readResize: "Resize the board";
|
|
79
|
+
readonly readSelect: "Select diagram";
|
|
80
|
+
readonly readSelectHint: "Drag a box around the diagram.";
|
|
81
|
+
readonly readSelectTitle: "Draw a box around a diagram that was not found";
|
|
82
|
+
readonly readShelf: "On this device";
|
|
83
|
+
readonly readShelfCount: "{n} books";
|
|
84
|
+
readonly readShelfOne: "1 book";
|
|
85
|
+
readonly readZoomIn: "Larger";
|
|
86
|
+
readonly readZoomOut: "Smaller";
|
|
87
|
+
readonly readZoomReset: "Back to 100%";
|
|
88
|
+
};
|
|
89
|
+
export type ReaderKey = keyof typeof READER_EN;
|
|
90
|
+
/** English words with {placeholders} filled, for a site with no translations of its own. */
|
|
91
|
+
export declare function englishWords(key: ReaderKey, vars?: Record<string, string | number>): string;
|
|
92
|
+
export declare const ReaderHostProvider: import("react").Provider<ReaderHost | null>;
|
|
93
|
+
export declare function useReaderHost(): ReaderHost;
|
|
94
|
+
/** The site's words, as `t`. */
|
|
95
|
+
export declare const useT: () => (key: ReaderKey, vars?: Record<string, string | number>) => string;
|
|
96
|
+
/** `track`, safe to call when the site counts nothing. The same function from one render to the next. */
|
|
97
|
+
export declare function useTrack(): (event: string, data?: Record<string, string | number | boolean>) => void | undefined;
|
package/dist/host.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { createContext, useCallback, useContext } from "react";
|
|
2
|
+
export const READER_EN = {
|
|
3
|
+
"readWhy1": "Every diagram, counted",
|
|
4
|
+
"readWhy1Sub": "fenshot goes through the whole book as you read. The bar says how many diagrams it holds, and its arrows take you from one to the next.",
|
|
5
|
+
"readWhy2": "Play it, or play Boris",
|
|
6
|
+
"readWhy2Sub": "A click puts a diagram on a board next to the page: legal moves, Stockfish if you ask for it, and a game against Kibitzo's coach from that position.",
|
|
7
|
+
"readWhy3": "Your PDF stays with you",
|
|
8
|
+
"readWhy3Sub": "The book is read by your browser and kept on this computer, never uploaded. It opens again on the page where you left it.",
|
|
9
|
+
"readAddBook": "Add a book",
|
|
10
|
+
"readByHand": "Set it up by hand",
|
|
11
|
+
"readCancel": "Cancel",
|
|
12
|
+
"readCantOpen": "This PDF could not be opened.",
|
|
13
|
+
"readChoose": "Open a PDF",
|
|
14
|
+
"readContents": "Contents",
|
|
15
|
+
"readDiagramNext": "Next diagram",
|
|
16
|
+
"readDiagramPrev": "Previous diagram",
|
|
17
|
+
"readDiagrams": "{n} diagrams in this book",
|
|
18
|
+
"readDiagramsShort": "{n} diagrams",
|
|
19
|
+
"readDropSub": "or drop it anywhere on this page",
|
|
20
|
+
"readDropTitle": "Open a chess book",
|
|
21
|
+
"readFinding": "Finding the diagrams: {done} of {pages} pages",
|
|
22
|
+
"readGoToPage": "Go to page",
|
|
23
|
+
"readHint": "Double-click a diagram",
|
|
24
|
+
"readHintSub": "It opens here as a board you can play on. The arrows at the top go from one diagram to the next.",
|
|
25
|
+
"readLibrary": "Library",
|
|
26
|
+
"readMore": "More",
|
|
27
|
+
"readNoDiagram": "No diagram could be read there.",
|
|
28
|
+
"readNotPdf": "That file is not a PDF.",
|
|
29
|
+
"readOpen": "Open",
|
|
30
|
+
"readOpenAt": "Open at page {page}",
|
|
31
|
+
"readOpening": "Opening your book…",
|
|
32
|
+
"readPageOf": "Page {page} of {pages}",
|
|
33
|
+
"readPrivate": "Read inside your browser. Your book is never uploaded.",
|
|
34
|
+
"readRemove": "Remove",
|
|
35
|
+
"readRemoveAsk": "Remove this book from this device?",
|
|
36
|
+
"readRename": "Rename",
|
|
37
|
+
"readResize": "Resize the board",
|
|
38
|
+
"readSelect": "Select diagram",
|
|
39
|
+
"readSelectHint": "Drag a box around the diagram.",
|
|
40
|
+
"readSelectTitle": "Draw a box around a diagram that was not found",
|
|
41
|
+
"readShelf": "On this device",
|
|
42
|
+
"readShelfCount": "{n} books",
|
|
43
|
+
"readShelfOne": "1 book",
|
|
44
|
+
"readZoomIn": "Larger",
|
|
45
|
+
"readZoomOut": "Smaller",
|
|
46
|
+
"readZoomReset": "Back to 100%"
|
|
47
|
+
};
|
|
48
|
+
/** English words with {placeholders} filled, for a site with no translations of its own. */
|
|
49
|
+
export function englishWords(key, vars) {
|
|
50
|
+
return READER_EN[key].replace(/\{(\w+)\}/g, (m, v) => (vars && v in vars ? String(vars[v]) : m));
|
|
51
|
+
}
|
|
52
|
+
const HostContext = createContext(null);
|
|
53
|
+
export const ReaderHostProvider = HostContext.Provider;
|
|
54
|
+
export function useReaderHost() {
|
|
55
|
+
const host = useContext(HostContext);
|
|
56
|
+
if (!host)
|
|
57
|
+
throw new Error("the reader needs a ReaderHostProvider");
|
|
58
|
+
return host;
|
|
59
|
+
}
|
|
60
|
+
/** The site's words, as `t`. */
|
|
61
|
+
export const useT = () => useReaderHost().t;
|
|
62
|
+
/** `track`, safe to call when the site counts nothing. The same function from one render to the next. */
|
|
63
|
+
export function useTrack() {
|
|
64
|
+
const { track } = useReaderHost();
|
|
65
|
+
return useCallback((event, data) => track?.(event, data), [track]);
|
|
66
|
+
}
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/pdf.d.ts
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pdf.js, loaded only when a book is opened (it is 1 MB): a document from a file, and a page drawn to a canvas at
|
|
3
|
+
* a width in pixels. Everything happens in the browser; no part of a book leaves the device.
|
|
4
|
+
*/
|
|
5
|
+
import type { PDFDocumentProxy, RenderTask } from "pdfjs-dist";
|
|
6
|
+
export type Doc = PDFDocumentProxy;
|
|
7
|
+
export declare function configurePdf(next: {
|
|
8
|
+
workerSrc: string;
|
|
9
|
+
assets: string;
|
|
10
|
+
}): void;
|
|
11
|
+
export declare function openPdf(file: Blob): Promise<Doc>;
|
|
12
|
+
/** A page's height over its width. */
|
|
13
|
+
export declare function ratioOf(doc: Doc, n: number): Promise<number>;
|
|
14
|
+
/** Draw page `n` on `canvas`, `width` pixels wide. The returned task can be cancelled when the page scrolls away. */
|
|
15
|
+
export declare function drawPage(doc: Doc, n: number, width: number, canvas: HTMLCanvasElement): Promise<RenderTask>;
|
|
16
|
+
/** The book's own list of chapters, each with the page it opens on. Empty when the PDF has none. */
|
|
17
|
+
export declare function chaptersOf(doc: Doc): Promise<{
|
|
18
|
+
title: string;
|
|
19
|
+
page: number;
|
|
20
|
+
depth: number;
|
|
21
|
+
}[]>;
|
|
22
|
+
/** A piece of a page's text and where it starts, in fractions of the page. */
|
|
23
|
+
export interface Word {
|
|
24
|
+
text: string;
|
|
25
|
+
fx: number;
|
|
26
|
+
fy: number;
|
|
27
|
+
}
|
|
28
|
+
/** A page's text, read once for all of its diagrams. Empty for a scan. */
|
|
29
|
+
export declare function wordsOf(doc: Doc, n: number): Promise<Word[]>;
|
|
30
|
+
/**
|
|
31
|
+
* Who is to move in a diagram, when the book says so in the words beside it ("Black to play"): the nearest such
|
|
32
|
+
* words under the board, or over it. Null when the page has no text (a scan) or says nothing.
|
|
33
|
+
* `box` is the diagram in fractions of the page.
|
|
34
|
+
*/
|
|
35
|
+
export declare function turnNear(words: Word[], box: {
|
|
36
|
+
x0: number;
|
|
37
|
+
y0: number;
|
|
38
|
+
x1: number;
|
|
39
|
+
y1: number;
|
|
40
|
+
}): "w" | "b" | null;
|
|
41
|
+
/** The book's first page as a small picture, for its card in the library. */
|
|
42
|
+
export declare function coverOf(doc: Doc): Promise<string | undefined>;
|
|
43
|
+
/**
|
|
44
|
+
* Which side a diagram is printed from, when the page carries the board's coordinates as text: "black" when the
|
|
45
|
+
* rank numbers beside it run 1 to 8 downwards or the file letters under it run h to a, "white" the other way,
|
|
46
|
+
* null when the page says nothing (the coordinates are part of a picture, or there are none).
|
|
47
|
+
* `box` is the diagram in fractions of the page.
|
|
48
|
+
*/
|
|
49
|
+
export declare function sideBelow(words: Word[], box: {
|
|
50
|
+
x0: number;
|
|
51
|
+
y0: number;
|
|
52
|
+
x1: number;
|
|
53
|
+
y1: number;
|
|
54
|
+
}): "white" | "black" | null;
|