Repository navigation
Expand file tree
/
Copy pathoffscreen.js
More file actions
47 lines (43 loc) · 1.86 KB
/
Copy pathoffscreen.js
File metadata and controls
47 lines (43 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Offscreen document that runs Tesseract OCR for the service worker, which
// can't start the Web Worker Tesseract runs in. Everything is loaded from the
// extension itself: MV3 doesn't allow remote code, and the default CDN paths
// would be exactly that.
const VENDOR = chrome.runtime.getURL("vendor/tesseract");
let workerPromise = null;
// One worker for the document's lifetime; loading the model takes a second.
function getWorker() {
workerPromise ??= Tesseract.createWorker("eng", 1, {
workerPath: `${VENDOR}/worker.min.js`,
corePath: VENDOR,
langPath: VENDOR,
workerBlobURL: false, // a blob: worker can't importScripts extension files
cacheMethod: "none", // already local; don't copy it into IndexedDB
}).catch((err) => {
workerPromise = null;
throw err;
});
return workerPromise;
}
chrome.runtime.onMessage.addListener((msg, _sender, sendResponse) => {
if (msg.target !== "offscreen") return;
ocr(msg).then(sendResponse, (err) => sendResponse({ error: String(err?.message || err) }));
return true;
});
// Recognize each rectangle (page column) of the image separately and return
// its text lines, and their words, with boxes in image pixels (the words let
// the worker tell which ones are italic, bold or highlighted). Read as one,
// Tesseract takes the gutter of a two-page spread for a word space and joins
// both pages' lines.
async function ocr({ image, rects }) {
const worker = await getWorker();
const columns = [];
for (const rectangle of rects) {
const { data } = await worker.recognize(image, { rectangle }, { blocks: true, text: false });
columns.push(
(data.blocks || [])
.flatMap((b) => b.paragraphs.flatMap((p) => p.lines))
.map((l) => ({ ...l.bbox, text: l.text, confidence: l.confidence, words: (l.words || []).map((w) => ({ ...w.bbox, text: w.text })) }))
);
}
return { columns };
}