Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
style(ocr): use double quotes and keep comments to the constraint
Elian Doran8d229026ef5d
diff --git a/apps/server/src/services/ocr/pdf_renderer.spec.ts b/apps/server/src/services/ocr/pdf_renderer.spec.tsindex 0a0d59d822..b12c26cdfb 100644--- a/apps/server/src/services/ocr/pdf_renderer.spec.ts+++ b/apps/server/src/services/ocr/pdf_renderer.spec.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mockRender = vi.fn();const mockGetOriginalSize = vi.fn();@@ -7,31 +7,31 @@ const mockGetPage = vi.fn(() => ({ getOriginalSize: mockGetOriginalSize, render:const mockLoadDocument = vi.fn(async () => ({ getPage: mockGetPage, destroy: mockDestroy }));const mockInit = vi.fn(async () => ({ loadDocument: mockLoadDocument }));-vi.mock('@hyzyla/pdfium', () => ({+vi.mock("@hyzyla/pdfium", () => ({PDFiumLibrary: { init: mockInit }}));// Avoid reading the real 4 MB wasm from disk.-vi.mock('fs', () => ({+vi.mock("fs", () => ({default: {existsSync: () => false,- readFileSync: () => Buffer.from('wasm-bytes')+ readFileSync: () => Buffer.from("wasm-bytes")}}));-vi.mock('../resource_dir.js', () => ({- RESOURCE_DIR: '/tmp/trilium-resources'+vi.mock("../resource_dir.js", () => ({+ RESOURCE_DIR: "/tmp/trilium-resources"}));const mockLog = { info: vi.fn(), error: vi.fn() };-vi.mock('@triliumnext/core', async (importOriginal) => {- const actual = await importOriginal<typeof import('@triliumnext/core')>();+vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();return { ...actual, getLog: () => mockLog };});// A fresh singleton per test, so the cached library never leaks between them.-let renderer: typeof import('./pdf_renderer.js').default;+let renderer: typeof import("./pdf_renderer.js").default;let MAX_RENDER_PIXELS: number;beforeEach(async () => {@@ -40,7 +40,7 @@ beforeEach(async () => {mockGetOriginalSize.mockReturnValue({ originalWidth: 612, originalHeight: 792 });mockRender.mockResolvedValue({ data: new Uint8Array(16), width: 2, height: 2 });mockLoadDocument.mockImplementation(async () => ({ getPage: mockGetPage, destroy: mockDestroy }));- ({ default: renderer, MAX_RENDER_PIXELS } = await import('./pdf_renderer.js'));+ ({ default: renderer, MAX_RENDER_PIXELS } = await import("./pdf_renderer.js"));});afterEach(() => {@@ -54,41 +54,41 @@ function renderedScale() {return mockRender.mock.calls[0][0].scale;}-describe('PdfRenderer', () => {- it('renders the requested page in colour at the configured scale', async () => {+describe("PdfRenderer", () => {+ it("renders the requested page in colour at the configured scale", async () => {const page = await renderer.renderPage(pdf, 3);expect(mockLoadDocument).toHaveBeenCalledWith(pdf);// PDFium numbers pages from zero, the OCR pipeline from one.expect(mockGetPage).toHaveBeenCalledWith(2);- expect(mockRender.mock.calls[0][0]).toMatchObject({ scale: 2, render: 'bitmap', colorSpace: 'BGRA' });+ expect(mockRender.mock.calls[0][0]).toMatchObject({ scale: 2, render: "bitmap", colorSpace: "BGRA" });expect(page).toEqual({ data: new Uint8Array(16), width: 2, height: 2 });expect(mockDestroy).toHaveBeenCalledOnce();});- it('loads the library once and reuses it across pages', async () => {+ it("loads the library once and reuses it across pages", async () => {await renderer.renderPage(pdf, 1);await renderer.renderPage(pdf, 2);expect(mockInit).toHaveBeenCalledOnce();});- it('does not cache a failed load, so a later page can try again', async () => {- mockInit.mockRejectedValueOnce(new Error('no wasm'));+ it("does not cache a failed load, so a later page can try again", async () => {+ mockInit.mockRejectedValueOnce(new Error("no wasm"));- await expect(renderer.renderPage(pdf, 1)).rejects.toThrow('no wasm');+ await expect(renderer.renderPage(pdf, 1)).rejects.toThrow("no wasm");await expect(renderer.renderPage(pdf, 1)).resolves.toBeDefined();expect(mockInit).toHaveBeenCalledTimes(2);});- it('closes the document even when the render throws', async () => {- mockRender.mockRejectedValue(new Error('broken page'));+ it("closes the document even when the render throws", async () => {+ mockRender.mockRejectedValue(new Error("broken page"));- await expect(renderer.renderPage(pdf, 1)).rejects.toThrow('broken page');+ await expect(renderer.renderPage(pdf, 1)).rejects.toThrow("broken page");expect(mockDestroy).toHaveBeenCalledOnce();});- it('serializes renders so two pages never share the heap', async () => {+ it("serializes renders so two pages never share the heap", async () => {let releaseFirst: (value: unknown) => void = () => {};mockRender.mockReturnValueOnce(new Promise((resolve) => { releaseFirst = resolve; }))@@ -106,18 +106,18 @@ describe('PdfRenderer', () => {expect(mockRender).toHaveBeenCalledTimes(2);});- describe('pixel budget', () => {- it('leaves an ordinary page at the configured scale', async () => {+ describe("pixel budget", () => {+ it("leaves an ordinary page at the configured scale", async () => {// A1, the largest ISO size that fits the budget at full scale.mockGetOriginalSize.mockReturnValue({ originalWidth: 1684, originalHeight: 2384 });await renderer.renderPage(pdf, 1);expect(renderedScale()).toBe(2);- expect(mockLog.info).not.toHaveBeenCalledWith(expect.stringContaining('pixel budget'));+ expect(mockLog.info).not.toHaveBeenCalledWith(expect.stringContaining("pixel budget"));});- it('scales an outsized page down to the budget and says so', async () => {+ it("scales an outsized page down to the budget and says so", async () => {// The largest page the PDF format allows: 200 inches square. At full scale that is// 28800x28800 pixels, which would size the bitmap in gigabytes.mockGetOriginalSize.mockReturnValue({ originalWidth: 14400, originalHeight: 14400 });@@ -128,10 +128,10 @@ describe('PdfRenderer', () => {expect(scale).toBeLessThan(2);// Whatever the scale works out to, the page must land inside the budget.expect((14400 * scale) * (14400 * scale)).toBeLessThanOrEqual(MAX_RENDER_PIXELS);- expect(mockLog.info).toHaveBeenCalledWith(expect.stringContaining('pixel budget'));+ expect(mockLog.info).toHaveBeenCalledWith(expect.stringContaining("pixel budget"));});- it('falls back to the configured scale when the page reports no size', async () => {+ it("falls back to the configured scale when the page reports no size", async () => {mockGetOriginalSize.mockReturnValue({ originalWidth: 0, originalHeight: 0 });await renderer.renderPage(pdf, 1);diff --git a/apps/server/src/services/ocr/pdf_renderer.ts b/apps/server/src/services/ocr/pdf_renderer.tsindex 59e70c5ad4..eee787b482 100644--- a/apps/server/src/services/ocr/pdf_renderer.ts+++ b/apps/server/src/services/ocr/pdf_renderer.ts@@ -16,17 +16,13 @@ export interface RenderedPage {/*** Multiplier applied to a page's natural size (72 dpi) when rasterizing it for OCR, giving about- * 144 dpi. Recognition confidence climbs steeply below this and is flat above it: across a scanned- * document and a vector-drawn one, scale 1 scored 82/54, scale 1.5 scored 93/89 and scale 2 scored- * 94/93, while scale 3 and 4 added nothing but two to four times the pixels to encode and read.+ * 144 dpi. Recognition accuracy drops off below this and does not improve above it.*/const RENDER_SCALE = 2;/**- * Pages are rasterized in colour even though Tesseract reads them as grey. PDFium's own grayscale- * conversion flattens coloured text into its background — on the demo document it costs the whole- * "Organize your thoughts" panel, 60 characters that colour rendering and Tesseract's own greyscale- * conversion both keep. Raising the scale does not bring them back.+ * Pages rasterize in colour even though Tesseract reads them as grey, because PDFium's own+ * grayscale conversion drops coloured text into its background where Tesseract's keeps it.*/const RENDER_COLOR_SPACE = "BGRA";@@ -40,15 +36,14 @@ export const MAX_RENDER_PIXELS = 20_000_000;/*** Renders PDF pages for OCR through PDFium compiled to WebAssembly.*- * Rasterizing the page, rather than pulling out the images it paints, is what lets a scan be read- * at all when its text is drawn as vector outlines, when the scan is split across several images,- * or when the page carries a rotation the images themselves know nothing about. It also bounds the- * work: a page becomes a fixed number of pixels no matter what resolution it was scanned at.+ * Rasterizing a page reads text the page's embedded images do not carry: outlined text, a scan+ * split across several images, and page rotation. It also fixes the pixel count per page,+ * independently of the resolution the document was scanned at.*/class PdfRenderer {private library: Promise<PdfiumLibrary> | null = null;- // Serializes renders. The library holds one wasm heap that grows to fit the largest page it has- // been asked for, so overlapping renders would size it to their sum rather than their maximum.+ // Serializes renders. The library has one wasm heap sized to the largest page rendered so far,+ // so concurrent renders would size it to their combined area rather than to the largest.private queue: Promise<unknown> = Promise.resolve();/**@@ -77,8 +72,8 @@ class PdfRenderer {}/**- * Loads PDFium once and keeps it. Its heap settles at the size of the largest page rendered and- * is reused from then on, so a long-lived instance costs no more than the biggest single page.+ * Loads PDFium once and keeps it. Its heap grows to the largest page rendered and is reused+ * from then on, so holding the library costs no more than one page of that size.*/private ensureLibrary(): Promise<PdfiumLibrary> {if (!this.library) {@@ -139,16 +134,16 @@ interface PdfiumPage {/*** The PDFium wasm, read the way `core_assets.ts` reads schema.sql: copied beside the server's own- * assets by the build, resolved through node_modules when running from source. PDFium would- * otherwise locate it relative to `import.meta.url`, which in the split ESM bundle is a hash-named- * file under chunks/ rather than anywhere the wasm was copied to.+ * assets by the build, resolved through node_modules when running from source. PDFium otherwise+ * locates it relative to `import.meta.url`, which in the split ESM bundle names a hashed file under+ * chunks/ rather than the directory the wasm was copied to.*/function readWasm(): ArrayBuffer {const productionPath = path.join(RESOURCE_DIR, "pdfium.wasm");const bytes = fs.existsSync(productionPath)? fs.readFileSync(productionPath): fs.readFileSync(require.resolve("@hyzyla/pdfium/dist/pdfium.wasm"));- // Copied into an ArrayBuffer of its own: readFileSync can hand back a view into a pooled- // buffer, whose remainder has nothing to do with the module PDFium is about to compile.+ // Copied into an ArrayBuffer of its own, because readFileSync can return a view into a pooled+ // buffer and PDFium compiles the whole buffer it is given.return new Uint8Array(bytes).buffer;}diff --git a/apps/server/src/services/ocr/processors/pdf_processor.integration.spec.ts b/apps/server/src/services/ocr/processors/pdf_processor.integration.spec.tsindex 7392194139..94db2007c1 100644--- a/apps/server/src/services/ocr/processors/pdf_processor.integration.spec.ts+++ b/apps/server/src/services/ocr/processors/pdf_processor.integration.spec.ts@@ -1,6 +1,6 @@-import { readFileSync } from 'fs';-import { join } from 'path';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { readFileSync } from "fs";+import { join } from "path";+import { beforeEach, describe, expect, it, vi } from "vitest";// Unlike pdf_processor.spec.ts, this suite mocks NOTHING in the OCR chain: it runs// the real unpdf page/image extraction, the real Jimp PNG encoding and a real@@ -10,11 +10,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';// cannot. Only Trilium's option/log accessors are stubbed, since they would// otherwise need a live database.-const mockOptions = { getOption: vi.fn().mockReturnValue('0') };+const mockOptions = { getOption: vi.fn().mockReturnValue("0") };const mockLog = { info: vi.fn(), error: vi.fn() };-vi.mock('@triliumnext/core', async (importOriginal) => {- const actual = await importOriginal<typeof import('@triliumnext/core')>();+vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();return {...actual,options: mockOptions,@@ -22,9 +22,9 @@ vi.mock('@triliumnext/core', async (importOriginal) => {};});-let PDFProcessor: typeof import('./pdf_processor.js').PDFProcessor;+let PDFProcessor: typeof import("./pdf_processor.js").PDFProcessor;-const SAMPLE = join(__dirname, 'samples', 'scanned.pdf');+const SAMPLE = join(__dirname, "samples", "scanned.pdf");// The fixture (samples/scanned.pdf) is a two-page image-only PDF: each page is a// full-page raster with no embedded text layer, so the only way to reach this text@@ -32,23 +32,23 @@ const SAMPLE = join(__dirname, 'samples', 'scanned.pdf');// from page 1 and page 2 proves OCR ran across the whole document, not just page 1.// Kept lowercase and short because Tesseract output is imperfect.const EXPECTED_PHRASES = [- 'welcome to trilium notes', // page 1- 'showcase some of its features', // page 1- 'ludwig wittgenstein', // page 2- 'organize your thoughts' // page 2+ "welcome to trilium notes", // page 1+ "showcase some of its features", // page 1+ "ludwig wittgenstein", // page 2+ "organize your thoughts" // page 2];beforeEach(async () => {vi.clearAllMocks();- mockOptions.getOption.mockReturnValue('0');- ({ PDFProcessor } = await import('./pdf_processor.js'));+ mockOptions.getOption.mockReturnValue("0");+ ({ PDFProcessor } = await import("./pdf_processor.js"));});-describe('PDFProcessor (integration — real OCR on a scanned multi-page PDF)', () => {- it('recognizes text from the scanned pages via OCR', async () => {+describe("PDFProcessor (integration — real OCR on a scanned multi-page PDF)", () => {+ it("recognizes text from the scanned pages via OCR", async () => {const processor = new PDFProcessor();- const result = await processor.extractText(readFileSync(SAMPLE), { language: 'eng' });+ const result = await processor.extractText(readFileSync(SAMPLE), { language: "eng" });// A multi-page document was read...expect(result.pageCount).toBeGreaterThanOrEqual(2);diff --git a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts b/apps/server/src/services/ocr/processors/pdf_processor.spec.tsindex cfb1a06a06..9730fd2ee3 100644--- a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts+++ b/apps/server/src/services/ocr/processors/pdf_processor.spec.ts@@ -1,36 +1,36 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const mockGetDocumentProxy = vi.fn();const mockExtractText = vi.fn();-vi.mock('unpdf', () => ({+vi.mock("unpdf", () => ({getDocumentProxy: mockGetDocumentProxy,extractText: mockExtractText}));-const mockGetBuffer = vi.fn().mockResolvedValue(Buffer.from('png-bytes'));+const mockGetBuffer = vi.fn().mockResolvedValue(Buffer.from("png-bytes"));const mockFromBitmap = vi.fn(() => ({ getBuffer: mockGetBuffer }));-vi.mock('jimp', () => ({+vi.mock("jimp", () => ({Jimp: { fromBitmap: mockFromBitmap }}));const mockRenderPage = vi.fn();-vi.mock('../pdf_renderer.js', () => ({+vi.mock("../pdf_renderer.js", () => ({default: { renderPage: mockRenderPage }}));const mockRecognize = vi.fn();-vi.mock('../tesseract_recognizer.js', () => ({+vi.mock("../tesseract_recognizer.js", () => ({default: { recognize: mockRecognize }}));const mockLog = { info: vi.fn(), error: vi.fn() };-vi.mock('@triliumnext/core', async (importOriginal) => {- const actual = await importOriginal<typeof import('@triliumnext/core')>();+vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();return {...actual,getLog: () => mockLog@@ -44,23 +44,23 @@ const mockGetViewport = vi.fn(() => LETTER_VIEWPORT);const mockGetPage = vi.fn(async () => ({ getViewport: mockGetViewport }));const pdfProxy = { proxy: true, getPage: mockGetPage };-let PDFProcessor: typeof import('./pdf_processor.js').PDFProcessor;+let PDFProcessor: typeof import("./pdf_processor.js").PDFProcessor;beforeEach(async () => {vi.clearAllMocks();mockGetViewport.mockReturnValue(LETTER_VIEWPORT);mockGetPage.mockImplementation(async () => ({ getViewport: mockGetViewport }));mockGetDocumentProxy.mockResolvedValue(pdfProxy);- mockGetBuffer.mockResolvedValue(Buffer.from('png-bytes'));+ mockGetBuffer.mockResolvedValue(Buffer.from("png-bytes"));mockRenderPage.mockImplementation(async () => renderedPage());- ({ PDFProcessor } = await import('./pdf_processor.js'));+ ({ PDFProcessor } = await import("./pdf_processor.js"));});afterEach(() => {vi.restoreAllMocks();});-const buffer = Buffer.from('%PDF-1.4 fake');+const buffer = Buffer.from("%PDF-1.4 fake");/*** A page as the renderer returns it: four BGRA bytes per pixel, in a buffer of its own. Built fresh@@ -72,32 +72,32 @@ function renderedPage() {/** Embedded text dense enough for a Letter page to read as a real text layer rather than a scan. */function densePage(marker: string): string {- return `${marker} `.padEnd(300, 'lorem ipsum dolor sit amet ');+ return `${marker} `.padEnd(300, "lorem ipsum dolor sit amet ");}-describe('PDFProcessor', () => {- it('reports the MIME types it can process', () => {+describe("PDFProcessor", () => {+ it("reports the MIME types it can process", () => {const processor = new PDFProcessor();- expect(processor.canProcess('application/PDF')).toBe(true);- expect(processor.canProcess('image/png')).toBe(false);- expect(processor.getSupportedMimeTypes()).toEqual(['application/pdf']);- expect(processor.getProcessingType()).toBe('pdf');+ expect(processor.canProcess("application/PDF")).toBe(true);+ expect(processor.canProcess("image/png")).toBe(false);+ expect(processor.getSupportedMimeTypes()).toEqual(["application/pdf"]);+ expect(processor.getProcessingType()).toBe("pdf");});- it('uses the embedded text layer and never rasterizes when pages have text', async () => {+ it("uses the embedded text layer and never rasterizes when pages have text", async () => {const processor = new PDFProcessor();mockExtractText.mockResolvedValue({totalPages: 2,- text: [` ${densePage('first')} `, densePage('second')]+ text: [` ${densePage("first")} `, densePage("second")]});- const result = await processor.extractText(buffer, { language: 'fra' });+ const result = await processor.extractText(buffer, { language: "fra" });- expect(result.text).toBe(`${densePage('first').trim()}\n\n${densePage('second').trim()}`);+ expect(result.text).toBe(`${densePage("first").trim()}\n\n${densePage("second").trim()}`);expect(result.confidence).toBe(0.99);expect(result.pageCount).toBe(2);- expect(result.language).toBe('fra');+ expect(result.language).toBe("fra");expect(mockExtractText).toHaveBeenCalledWith(pdfProxy, { mergePages: false });// No scanned page → nothing rendered and no OCR.expect(mockRenderPage).not.toHaveBeenCalled();@@ -105,26 +105,26 @@ describe('PDFProcessor', () => {// buffer is wrapped into a Uint8Array carrying the SAME bytes before being passed to unpdfconst [docArg] = mockGetDocumentProxy.mock.calls[0];expect(docArg).toBeInstanceOf(Uint8Array);- expect(Buffer.from(docArg as Uint8Array).toString()).toBe('%PDF-1.4 fake');+ expect(Buffer.from(docArg as Uint8Array).toString()).toBe("%PDF-1.4 fake");});- it('OCRs a scanned (text-less) page by rendering it', async () => {+ it("OCRs a scanned (text-less) page by rendering it", async () => {const processor = new PDFProcessor();- mockExtractText.mockResolvedValue({ totalPages: 1, text: [' '] });- mockRecognize.mockResolvedValue({ text: 'recognized text', confidence: 0.9 });+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [" "] });+ mockRecognize.mockResolvedValue({ text: "recognized text", confidence: 0.9 });- const result = await processor.extractText(buffer, { language: 'eng' });+ const result = await processor.extractText(buffer, { language: "eng" });expect(mockRenderPage).toHaveBeenCalledWith(expect.any(Uint8Array), 1);- expect(mockRecognize).toHaveBeenCalledWith(Buffer.from('png-bytes'), 'eng');- expect(result.text).toBe('recognized text');+ expect(mockRecognize).toHaveBeenCalledWith(Buffer.from("png-bytes"), "eng");+ expect(result.text).toBe("recognized text");expect(result.confidence).toBeCloseTo(0.9);expect(result.pageCount).toBe(1);});- it('turns the rendered BGRA page into the RGBA bitmap Jimp encodes', async () => {+ it("turns the rendered BGRA page into the RGBA bitmap Jimp encodes", async () => {const processor = new PDFProcessor();- mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [""] });mockRenderPage.mockResolvedValue({// Two pixels, BGRA: an orange and a teal. The second is transparent, to prove alpha is// forced opaque rather than carried through.@@ -132,9 +132,9 @@ describe('PDFProcessor', () => {width: 2,height: 1});- mockRecognize.mockResolvedValue({ text: 'x', confidence: 0.5 });+ mockRecognize.mockResolvedValue({ text: "x", confidence: 0.5 });- await processor.extractText(buffer, { language: 'eng' });+ await processor.extractText(buffer, { language: "eng" });const [bitmap] = mockFromBitmap.mock.calls[0] as unknown as [{ data: Buffer; width: number; height: number }];expect(bitmap.width).toBe(2);@@ -145,30 +145,30 @@ describe('PDFProcessor', () => {]);});- it('hands the renderer bytes of its own, since pdf.js takes ownership of what it is given', async () => {+ it("hands the renderer bytes of its own, since pdf.js takes ownership of what it is given", async () => {const processor = new PDFProcessor();- mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });- mockRecognize.mockResolvedValue({ text: 'ocr', confidence: 0.9 });+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [""] });+ mockRecognize.mockResolvedValue({ text: "ocr", confidence: 0.9 });- await processor.extractText(buffer, { language: 'eng' });+ await processor.extractText(buffer, { language: "eng" });const [unpdfBytes] = mockGetDocumentProxy.mock.calls[0];const [renderBytes] = mockRenderPage.mock.calls[0];expect(renderBytes).not.toBe(unpdfBytes);- expect(Buffer.from(renderBytes as Uint8Array).toString()).toBe('%PDF-1.4 fake');+ expect(Buffer.from(renderBytes as Uint8Array).toString()).toBe("%PDF-1.4 fake");});- it('handles a mixed PDF, combining embedded text and OCR per page', async () => {+ it("handles a mixed PDF, combining embedded text and OCR per page", async () => {const processor = new PDFProcessor();mockExtractText.mockResolvedValue({totalPages: 2,- text: [densePage('a real text page'), '']+ text: [densePage("a real text page"), ""]});- mockRecognize.mockResolvedValue({ text: 'scanned page text', confidence: 0.8 });+ mockRecognize.mockResolvedValue({ text: "scanned page text", confidence: 0.8 });- const result = await processor.extractText(buffer, { language: 'eng' });+ const result = await processor.extractText(buffer, { language: "eng" });- expect(result.text).toBe(`${densePage('a real text page').trim()}\n\nscanned page text`);+ expect(result.text).toBe(`${densePage("a real text page").trim()}\n\nscanned page text`);// Only the second (scanned) page is rendered.expect(mockRenderPage).toHaveBeenCalledTimes(1);expect(mockRenderPage).toHaveBeenCalledWith(expect.any(Uint8Array), 2);@@ -176,80 +176,80 @@ describe('PDFProcessor', () => {expect(result.confidence).toBeCloseTo((0.99 + 0.8) / 2);});- it('OCRs a scan whose only embedded text is a header', async () => {+ it("OCRs a scan whose only embedded text is a header", async () => {const processor = new PDFProcessor();// A scanner stamps this much text on a page whose body is pure raster. Any flat character// bound low enough to be safe is cleared by it, and the page would never be recognized.- mockExtractText.mockResolvedValue({ totalPages: 1, text: ['ACME Corp — Invoice 2024-11-03'] });- mockRecognize.mockResolvedValue({ text: 'the body of the invoice', confidence: 0.9 });+ mockExtractText.mockResolvedValue({ totalPages: 1, text: ["ACME Corp — Invoice 2024-11-03"] });+ mockRecognize.mockResolvedValue({ text: "the body of the invoice", confidence: 0.9 });- const result = await processor.extractText(buffer, { language: 'eng' });+ const result = await processor.extractText(buffer, { language: "eng" });expect(mockRenderPage).toHaveBeenCalledWith(expect.any(Uint8Array), 1);- expect(result.text).toBe('the body of the invoice');+ expect(result.text).toBe("the body of the invoice");});- it('scales the text-layer threshold with page area rather than counting characters', async () => {+ it("scales the text-layer threshold with page area rather than counting characters", async () => {const processor = new PDFProcessor();// Four times the area of Letter, so the same text is four times as sparse on it.mockGetViewport.mockReturnValue({ width: 1224, height: 1584 });- mockExtractText.mockResolvedValue({ totalPages: 1, text: [densePage('sparse on a large page')] });- mockRecognize.mockResolvedValue({ text: 'recognized', confidence: 0.9 });+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [densePage("sparse on a large page")] });+ mockRecognize.mockResolvedValue({ text: "recognized", confidence: 0.9 });- const result = await processor.extractText(buffer, { language: 'eng' });+ const result = await processor.extractText(buffer, { language: "eng" });// The very same text is kept as-is on a Letter page (see the mixed-PDF case above).expect(mockRenderPage).toHaveBeenCalledOnce();- expect(result.text).toBe('recognized');+ expect(result.text).toBe("recognized");});- it('falls back to a Letter-sized page when the geometry cannot be read', async () => {+ it("falls back to a Letter-sized page when the geometry cannot be read", async () => {const processor = new PDFProcessor();- mockGetPage.mockRejectedValue(new Error('no such page'));- mockExtractText.mockResolvedValue({ totalPages: 1, text: [densePage('still a text page')] });+ mockGetPage.mockRejectedValue(new Error("no such page"));+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [densePage("still a text page")] });- const result = await processor.extractText(buffer, { language: 'eng' });+ const result = await processor.extractText(buffer, { language: "eng" });expect(mockRenderPage).not.toHaveBeenCalled();- expect(result.text).toBe(densePage('still a text page').trim());- expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining('Could not measure PDF page 1'));+ expect(result.text).toBe(densePage("still a text page").trim());+ expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining("Could not measure PDF page 1"));});- it('reports zero confidence and empty text when the page holds nothing recognizable', async () => {+ it("reports zero confidence and empty text when the page holds nothing recognizable", async () => {const processor = new PDFProcessor();- mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });- mockRecognize.mockResolvedValue({ text: '', confidence: 0 });+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [""] });+ mockRecognize.mockResolvedValue({ text: "", confidence: 0 });- const result = await processor.extractText(buffer, { language: 'eng' });+ const result = await processor.extractText(buffer, { language: "eng" });- expect(result.text).toBe('');+ expect(result.text).toBe("");expect(result.confidence).toBe(0);});- it('tolerates a render failure on a page without aborting the document', async () => {+ it("tolerates a render failure on a page without aborting the document", async () => {const processor = new PDFProcessor();- mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });- mockRenderPage.mockRejectedValue(new Error('broken page'));+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [""] });+ mockRenderPage.mockRejectedValue(new Error("broken page"));- const result = await processor.extractText(buffer, { language: 'eng' });+ const result = await processor.extractText(buffer, { language: "eng" });- expect(result.text).toBe('');+ expect(result.text).toBe("");expect(result.confidence).toBe(0);expect(mockRecognize).not.toHaveBeenCalled();- expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining('PDF OCR failed for page 1'));+ expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining("PDF OCR failed for page 1"));});- it('caps the number of OCR pages and logs the pages it skipped', async () => {+ it("caps the number of OCR pages and logs the pages it skipped", async () => {const processor = new PDFProcessor();const totalPages = 55;- mockExtractText.mockResolvedValue({ totalPages, text: Array(totalPages).fill('') });- mockRecognize.mockResolvedValue({ text: 'p', confidence: 0.9 });+ mockExtractText.mockResolvedValue({ totalPages, text: Array(totalPages).fill("") });+ mockRecognize.mockResolvedValue({ text: "p", confidence: 0.9 });- const result = await processor.extractText(buffer, { language: 'eng' });+ const result = await processor.extractText(buffer, { language: "eng" });// MAX_OCR_PAGES = 50; the remaining 5 scanned pages are skipped, not rendered.expect(mockRenderPage).toHaveBeenCalledTimes(50);- expect(result.text.split('\n\n')).toHaveLength(50);- expect(mockLog.info).toHaveBeenCalledWith(expect.stringContaining('page cap reached'));+ expect(result.text.split("\n\n")).toHaveLength(50);+ expect(mockLog.info).toHaveBeenCalledWith(expect.stringContaining("page cap reached"));});});diff --git a/apps/server/src/services/ocr/processors/pdf_processor.ts b/apps/server/src/services/ocr/processors/pdf_processor.tsindex 4223706a64..9464629587 100644--- a/apps/server/src/services/ocr/processors/pdf_processor.ts+++ b/apps/server/src/services/ocr/processors/pdf_processor.ts@@ -1,18 +1,16 @@import { getLog } from "@triliumnext/core";-import { OCRProcessingOptions, OCRResult } from '../ocr_service.js';-import renderer, { RenderedPage } from '../pdf_renderer.js';-import recognizer from '../tesseract_recognizer.js';-import { FileProcessor } from './file_processor.js';+import { OCRProcessingOptions, OCRResult } from "../ocr_service.js";+import renderer, { RenderedPage } from "../pdf_renderer.js";+import recognizer from "../tesseract_recognizer.js";+import { FileProcessor } from "./file_processor.js";-type PdfDocument = Awaited<ReturnType<typeof import('unpdf').getDocumentProxy>>;+type PdfDocument = Awaited<ReturnType<typeof import("unpdf").getDocumentProxy>>;/**- * Embedded characters per square point of page area below which a page is treated as scanned and- * sent to OCR. A flat character count cannot separate the two cases: a scan carrying a header, a- * watermark or a partial text layer clears any small bound while the body of the page stays unread.- * This works out to roughly 240 characters on Letter and A4 — far below a sparse but genuine text- * page, far above a header.+ * Embedded characters per square point of page area below which a page counts as scanned and goes+ * to OCR. Scaling by area rather than counting characters is what separates a genuine text layer+ * from the header or watermark a scan carries. Works out to roughly 240 characters on Letter and A4.*/const MIN_EMBEDDED_TEXT_DENSITY = 0.0005;@@ -20,43 +18,37 @@ const MIN_EMBEDDED_TEXT_DENSITY = 0.0005;const FALLBACK_PAGE_AREA = 612 * 792;/**- * Upper bound on how many scanned pages a single PDF may OCR. Rasterizing and- * recognizing a page costs seconds and non-trivial memory, so an unbounded scan- * of a large document could stall the OCR queue. Pages beyond the cap keep- * whatever embedded text they have (usually none) and are logged, never silently- * dropped.+ * Upper bound on how many scanned pages a single PDF may OCR. Rasterizing and recognizing a page+ * costs seconds and non-trivial memory, so a large scan would otherwise stall the OCR queue. Pages+ * beyond the cap keep whatever embedded text they have and are logged, never silently dropped.*/const MAX_OCR_PAGES = 50;-/** An embedded-text page is exact, so it is reported at the same high confidence the previous text-only path used. */+/** Embedded text is exact, so a page taken from the text layer reports this confidence. */const EMBEDDED_TEXT_CONFIDENCE = 0.99;/*** PDF processor. Prefers the PDF's embedded text layer (fast and exact) and falls back to OCR for- * pages carrying too little text for their size, rasterizing those through PDFium and reading them- * with the shared Tesseract recognizer. Detection is per page, so mixed PDFs (some real-text pages,- * some scans) are handled correctly.- *- * Reading the rendered page rather than the images it paints is what lets a scan be recognized when- * its text is drawn as vector outlines, when it is split across several images, or when the page- * carries a rotation the images know nothing about.+ * pages carrying too little text for their size, rasterizing those through {@link renderer} and+ * reading them with the shared Tesseract recognizer. Detection is per page, so a mixed PDF of real+ * text pages and scans is handled correctly.*/export class PDFProcessor extends FileProcessor {canProcess(mimeType: string): boolean {- return mimeType.toLowerCase() === 'application/pdf';+ return mimeType.toLowerCase() === "application/pdf";}getSupportedMimeTypes(): string[] {- return ['application/pdf'];+ return ["application/pdf"];}async extractText(buffer: Buffer, options: OCRProcessingOptions = {}): Promise<OCRResult> {- getLog().info('Starting PDF text extraction...');+ getLog().info("Starting PDF text extraction...");const language = options.language || "eng";// Dynamically imported so unpdf only loads when a PDF is actually processed.- const { extractText, getDocumentProxy } = await import('unpdf');+ const { extractText, getDocumentProxy } = await import("unpdf");const pdf = await getDocumentProxy(new Uint8Array(buffer));const { totalPages, text: pageTexts } = await extractText(pdf, { mergePages: false });@@ -119,7 +111,7 @@ export class PDFProcessor extends FileProcessor {}getProcessingType(): string {- return 'pdf';+ return "pdf";}/**@@ -153,10 +145,9 @@ async function getPageArea(pdf: PdfDocument, pageNum: number): Promise<number> {/*** Encode a rendered page into a PNG buffer that Tesseract can decode. The renderer produces BGRA- * and Jimp bitmaps are RGBA, so blue and red swap places within the page's own buffer: it belongs- * to this call and is dropped as soon as the PNG exists, and a full-page copy to swap two channels- * costs 8 MB for nothing. Alpha is forced opaque, or a transparent page background would reach- * Tesseract as black.+ * and Jimp bitmaps are RGBA, so blue and red swap places within the page's own buffer, which+ * belongs to this call. Alpha is forced opaque, or a transparent page background reaches Tesseract+ * as black.*/async function toPngBuffer({ data, width, height }: RenderedPage): Promise<Buffer> {const bitmap = Buffer.from(data.buffer, data.byteOffset, data.byteLength);diff --git a/apps/server/src/services/ocr/tesseract_recognizer.spec.ts b/apps/server/src/services/ocr/tesseract_recognizer.spec.tsindex 39734ce0a4..74bd334216 100644--- a/apps/server/src/services/ocr/tesseract_recognizer.spec.ts+++ b/apps/server/src/services/ocr/tesseract_recognizer.spec.ts@@ -1,4 +1,4 @@-import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";// Mock Tesseract.js so no real OCR model is ever loaded.const mockWorker = {@@ -10,20 +10,20 @@ const mockTesseract = {createWorker: vi.fn()};-vi.mock('tesseract.js', () => ({+vi.mock("tesseract.js", () => ({default: mockTesseract}));// Avoid touching the real filesystem for the worker cache directory.-vi.mock('fs', () => ({+vi.mock("fs", () => ({default: {mkdirSync: vi.fn()}}));-vi.mock('../data_dir.js', () => ({+vi.mock("../data_dir.js", () => ({default: {- OCR_CACHE_DIR: '/tmp/trilium-ocr-test-cache'+ OCR_CACHE_DIR: "/tmp/trilium-ocr-test-cache"}}));@@ -36,8 +36,8 @@ const mockLog = {error: vi.fn()};-vi.mock('@triliumnext/core', async (importOriginal) => {- const actual = await importOriginal<typeof import('@triliumnext/core')>();+vi.mock("@triliumnext/core", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@triliumnext/core")>();return {...actual,options: mockOptions,@@ -46,21 +46,21 @@ vi.mock('@triliumnext/core', async (importOriginal) => {});// A fresh singleton is imported per test so worker state never leaks between them.-let recognizer: typeof import('./tesseract_recognizer.js').default;+let recognizer: typeof import("./tesseract_recognizer.js").default;beforeEach(async () => {vi.resetModules();vi.clearAllMocks();- mockOptions.getOption.mockReturnValue('0');+ mockOptions.getOption.mockReturnValue("0");mockTesseract.createWorker.mockResolvedValue(mockWorker);- recognizer = (await import('./tesseract_recognizer.js')).default;+ recognizer = (await import("./tesseract_recognizer.js")).default;});afterEach(() => {vi.restoreAllMocks();});-const image = Buffer.from('fake-image');+const image = Buffer.from("fake-image");/*** A recognition result in the shape tesseract.js actually answers with when the `blocks` output@@ -69,12 +69,12 @@ const image = Buffer.from('fake-image');*/function pageWithLines(confidence: number, lines: [ text: string, confidence: number ][][]) {return {- text: lines.map(line => line.map(([ text ]) => text).join(' ')).join('\n'),+ text: lines.map(line => line.map(([ text ]) => text).join(" ")).join("\n"),confidence,blocks: [ {paragraphs: [ {lines: lines.map(line => ({- text: line.map(([ text ]) => text).join(' '),+ text: line.map(([ text ]) => text).join(" "),words: line.map(([ text, wordConfidence ]) => ({ text, confidence: wordConfidence }))}))} ]@@ -87,58 +87,58 @@ function pageWithoutBlocks(text: string, confidence: number) {return { text, confidence, blocks: null };}-describe('TesseractRecognizer', () => {- it('recognizes text and reports overall confidence when no threshold is set', async () => {+describe("TesseractRecognizer", () => {+ it("recognizes text and reports overall confidence when no threshold is set", async () => {mockWorker.recognize.mockResolvedValue({- data: pageWithoutBlocks(' hello world ', 88)+ data: pageWithoutBlocks(" hello world ", 88)});- const result = await recognizer.recognize(image, 'eng');+ const result = await recognizer.recognize(image, "eng");- expect(result.text).toBe('hello world');+ expect(result.text).toBe("hello world");expect(result.confidence).toBeCloseTo(0.88);expect(mockTesseract.createWorker).toHaveBeenCalledWith(- 'eng',+ "eng",1,- expect.objectContaining({ cachePath: '/tmp/trilium-ocr-test-cache' })+ expect.objectContaining({ cachePath: "/tmp/trilium-ocr-test-cache" }));});- it('asks tesseract for the per-word breakdown the confidence filter needs', async () => {- mockWorker.recognize.mockResolvedValue({ data: pageWithLines(80, [ [ [ 'x', 80 ] ] ]) });+ it("asks tesseract for the per-word breakdown the confidence filter needs", async () => {+ mockWorker.recognize.mockResolvedValue({ data: pageWithLines(80, [ [ [ "x", 80 ] ] ]) });- await recognizer.recognize(image, 'eng');+ await recognizer.recognize(image, "eng");// Without this output format the result carries the plain text alone, and every image is// judged by its mean confidence instead of word by word.expect(mockWorker.recognize).toHaveBeenCalledWith(image, {}, { blocks: true });});- it('reuses the worker for the same language and recreates it when the language changes', async () => {+ it("reuses the worker for the same language and recreates it when the language changes", async () => {mockWorker.recognize.mockResolvedValue({- data: pageWithLines(50, [ [ [ 'a', 50 ] ] ])+ data: pageWithLines(50, [ [ [ "a", 50 ] ] ])});- await recognizer.recognize(image, 'eng');- await recognizer.recognize(image, 'eng');+ await recognizer.recognize(image, "eng");+ await recognizer.recognize(image, "eng");expect(mockTesseract.createWorker).toHaveBeenCalledTimes(1);expect(mockWorker.terminate).not.toHaveBeenCalled();- await recognizer.recognize(image, 'deu');+ await recognizer.recognize(image, "deu");expect(mockWorker.terminate).toHaveBeenCalledTimes(1);expect(mockTesseract.createWorker).toHaveBeenCalledTimes(2);});- it('serializes overlapping calls so a language switch cannot tear down an in-flight worker', async () => {+ it("serializes overlapping calls so a language switch cannot tear down an in-flight worker", async () => {// Hold the first recognition open so the second call is issued while it runs.let releaseFirst: (value: unknown) => void = () => {};const firstRecognition = new Promise((resolve) => { releaseFirst = resolve; });mockWorker.recognize.mockReturnValueOnce(firstRecognition)- .mockResolvedValue({ data: pageWithLines(50, [ [ [ 'second', 50 ] ] ]) });+ .mockResolvedValue({ data: pageWithLines(50, [ [ [ "second", 50 ] ] ]) });- const p1 = recognizer.recognize(image, 'eng');- const p2 = recognizer.recognize(image, 'deu');+ const p1 = recognizer.recognize(image, "eng");+ const p2 = recognizer.recognize(image, "deu");// Let microtasks settle while the first job is still running.await new Promise((resolve) => setTimeout(resolve, 0));@@ -148,147 +148,147 @@ describe('TesseractRecognizer', () => {expect(mockTesseract.createWorker).toHaveBeenCalledTimes(1);expect(mockWorker.terminate).not.toHaveBeenCalled();- releaseFirst({ data: pageWithLines(50, [ [ [ 'first', 50 ] ] ]) });+ releaseFirst({ data: pageWithLines(50, [ [ [ "first", 50 ] ] ]) });const [r1, r2] = await Promise.all([p1, p2]);- expect(r1.text).toBe('first');- expect(r2.text).toBe('second');+ expect(r1.text).toBe("first");+ expect(r2.text).toBe("second");// Only after the first job finished did the language switch tear down and rebuild.expect(mockWorker.terminate).toHaveBeenCalledTimes(1);expect(mockTesseract.createWorker).toHaveBeenCalledTimes(2);});- it('invokes the recognizing-text logger callback', async () => {+ it("invokes the recognizing-text logger callback", async () => {mockWorker.recognize.mockResolvedValue({- data: pageWithLines(50, [ [ [ 'a', 50 ] ] ])+ data: pageWithLines(50, [ [ [ "a", 50 ] ] ])});- await recognizer.recognize(image, 'eng');+ await recognizer.recognize(image, "eng");const config = mockTesseract.createWorker.mock.calls[0][2];- config.logger({ status: 'recognizing text', progress: 0.5 });- config.logger({ status: 'loading', progress: 0.1 });+ config.logger({ status: "recognizing text", progress: 0.5 });+ config.logger({ status: "loading", progress: 0.1 });expect(mockLog.info).toHaveBeenCalledWith(- expect.stringContaining('OCR progress')+ expect.stringContaining("OCR progress"));});- it('passes an errorHandler that logs worker errors instead of rethrowing them', async () => {+ it("passes an errorHandler that logs worker errors instead of rethrowing them", async () => {mockWorker.recognize.mockResolvedValue({- data: pageWithLines(50, [ [ [ 'a', 50 ] ] ])+ data: pageWithLines(50, [ [ [ "a", 50 ] ] ])});- await recognizer.recognize(image, 'eng');+ await recognizer.recognize(image, "eng");// Without an errorHandler, tesseract.js turns job failures into uncaught// exceptions, which surface as Electron's "JavaScript error" dialog (#9754).const config = mockTesseract.createWorker.mock.calls[0][2];- expect(() => config.errorHandler('Error attempting to read image.')).not.toThrow();+ expect(() => config.errorHandler("Error attempting to read image.")).not.toThrow();expect(mockLog.error).toHaveBeenCalledWith(- 'Tesseract worker error: Error attempting to read image.'+ "Tesseract worker error: Error attempting to read image.");});- it('propagates recognition errors to the caller', async () => {- mockWorker.recognize.mockRejectedValue(new Error('recognize failed'));+ it("propagates recognition errors to the caller", async () => {+ mockWorker.recognize.mockRejectedValue(new Error("recognize failed"));- await expect(recognizer.recognize(image, 'eng')).rejects.toThrow('recognize failed');+ await expect(recognizer.recognize(image, "eng")).rejects.toThrow("recognize failed");});- describe('confidence filtering', () => {- it('keeps the words above the threshold on the lines they were read on', async () => {- mockOptions.getOption.mockReturnValue('0.8');+ describe("confidence filtering", () => {+ it("keeps the words above the threshold on the lines they were read on", async () => {+ mockOptions.getOption.mockReturnValue("0.8");mockWorker.recognize.mockResolvedValue({data: pageWithLines(70, [- [ [ 'good', 90 ], [ 'bad', 50 ] ],- [ [ 'also', 95 ], [ 'good', 85 ] ]+ [ [ "good", 90 ], [ "bad", 50 ] ],+ [ [ "also", 95 ], [ "good", 85 ] ]])});- const result = await recognizer.recognize(image, 'eng');+ const result = await recognizer.recognize(image, "eng");- expect(result.text).toBe('good\nalso good');+ expect(result.text).toBe("good\nalso good");expect(result.confidence).toBeCloseTo((0.9 + 0.95 + 0.85) / 3);});- it('keeps well-read words on an image whose mean confidence is below the threshold', async () => {+ it("keeps well-read words on an image whose mean confidence is below the threshold", async () => {// The mean is dragged under the line by the marks Tesseract misread as text, which is// exactly what the per-word filter is for — judging the image by that mean instead// would throw away every word on it.- mockOptions.getOption.mockReturnValue('0.75');+ mockOptions.getOption.mockReturnValue("0.75");mockWorker.recognize.mockResolvedValue({- data: pageWithLines(60, [ [ [ 'Invoice', 96 ], [ '®', 0 ], [ 'total', 94 ] ] ])+ data: pageWithLines(60, [ [ [ "Invoice", 96 ], [ "®", 0 ], [ "total", 94 ] ] ])});- const result = await recognizer.recognize(image, 'eng');+ const result = await recognizer.recognize(image, "eng");- expect(result.text).toBe('Invoice total');+ expect(result.text).toBe("Invoice total");});- it('leaves no blank line where every word of one was dropped', async () => {- mockOptions.getOption.mockReturnValue('0.8');+ it("leaves no blank line where every word of one was dropped", async () => {+ mockOptions.getOption.mockReturnValue("0.8");mockWorker.recognize.mockResolvedValue({data: pageWithLines(70, [- [ [ 'kept', 90 ] ],- [ [ 'noise', 10 ] ],- [ [ 'also-kept', 90 ] ]+ [ [ "kept", 90 ] ],+ [ [ "noise", 10 ] ],+ [ [ "also-kept", 90 ] ]])});- const result = await recognizer.recognize(image, 'eng');+ const result = await recognizer.recognize(image, "eng");- expect(result.text).toBe('kept\nalso-kept');+ expect(result.text).toBe("kept\nalso-kept");});- it('returns empty text and no confidence when no word passes the threshold', async () => {- mockOptions.getOption.mockReturnValue('0.99');+ it("returns empty text and no confidence when no word passes the threshold", async () => {+ mockOptions.getOption.mockReturnValue("0.99");mockWorker.recognize.mockResolvedValue({- data: pageWithLines(10, [ [ [ 'low', 10 ] ] ])+ data: pageWithLines(10, [ [ [ "low", 10 ] ] ])});- const result = await recognizer.recognize(image, 'eng');+ const result = await recognizer.recognize(image, "eng");- expect(result.text).toBe('');+ expect(result.text).toBe("");expect(result.confidence).toBe(0);});- it('falls back to overall confidence when nothing was broken down into words', async () => {- mockOptions.getOption.mockReturnValue('0.5');+ it("falls back to overall confidence when nothing was broken down into words", async () => {+ mockOptions.getOption.mockReturnValue("0.5");mockWorker.recognize.mockResolvedValue({- data: pageWithoutBlocks(' whole text ', 80)+ data: pageWithoutBlocks(" whole text ", 80)});- const result = await recognizer.recognize(image, 'eng');+ const result = await recognizer.recognize(image, "eng");- expect(result.text).toBe('whole text');+ expect(result.text).toBe("whole text");expect(result.confidence).toBeCloseTo(0.8);});- it('drops all text via the fallback when overall confidence is too low', async () => {- mockOptions.getOption.mockReturnValue('0.9');+ it("drops all text via the fallback when overall confidence is too low", async () => {+ mockOptions.getOption.mockReturnValue("0.9");mockWorker.recognize.mockResolvedValue({- data: pageWithoutBlocks('whole text', 40)+ data: pageWithoutBlocks("whole text", 40)});- const result = await recognizer.recognize(image, 'eng');+ const result = await recognizer.recognize(image, "eng");- expect(result.text).toBe('');+ expect(result.text).toBe("");expect(result.confidence).toBeCloseTo(0.4);expect(mockLog.info).toHaveBeenCalledWith(- expect.stringContaining('Entire text filtered out')+ expect.stringContaining("Entire text filtered out"));});- it('defaults the threshold to 0 when the option is null', async () => {+ it("defaults the threshold to 0 when the option is null", async () => {mockOptions.getOption.mockReturnValue(null);mockWorker.recognize.mockResolvedValue({- data: pageWithLines(30, [ [ [ 'kept', 30 ] ] ])+ data: pageWithLines(30, [ [ [ "kept", 30 ] ] ])});- const result = await recognizer.recognize(image, 'eng');+ const result = await recognizer.recognize(image, "eng");- expect(result.text).toBe('kept');+ expect(result.text).toBe("kept");});});});diff --git a/apps/server/src/services/ocr/tesseract_recognizer.ts b/apps/server/src/services/ocr/tesseract_recognizer.tsindex 145b93dc5b..5f654b0197 100644--- a/apps/server/src/services/ocr/tesseract_recognizer.ts+++ b/apps/server/src/services/ocr/tesseract_recognizer.ts@@ -1,8 +1,8 @@-import { getLog, options } from '@triliumnext/core';-import fs from 'fs';-import Tesseract from 'tesseract.js';+import { getLog, options } from "@triliumnext/core";+import fs from "fs";+import Tesseract from "tesseract.js";-import dataDirs from '../data_dir.js';+import dataDirs from "../data_dir.js";export interface RecognitionResult {/** Recognized text after per-word confidence filtering. */@@ -21,11 +21,9 @@ export interface RecognitionResult {class TesseractRecognizer {private worker: Tesseract.Worker | null = null;private currentLanguage: string | null = null;- // Serializes recognition jobs. The worker is a single shared resource and a- // language change tears it down and rebuilds it, so two overlapping calls (e.g.- // a manual reprocess arriving mid-batch) could otherwise terminate a worker that- // another call is mid-recognition with. Chaining also bounds OCR to one CPU-heavy- // job at a time.+ // Serializes recognition jobs. A language change terminates the shared worker and builds a new+ // one, so a second call arriving mid-recognition could otherwise destroy the worker the first+ // is using. Chaining also bounds OCR to one CPU-heavy job at a time.private queue: Promise<unknown> = Promise.resolve();/**@@ -75,7 +73,7 @@ class TesseractRecognizer {getLog().error(`Tesseract worker error: ${error}`);},logger: (m: { status: string; progress: number }) => {- if (m.status === 'recognizing text') {+ if (m.status === "recognizing text") {getLog().info(`OCR progress (${language}): ${Math.round(m.progress * 100)}%`);}}@@ -119,7 +117,7 @@ class TesseractRecognizer {}getLog().info(`Entire text filtered out due to low confidence ${overallConfidence} (below threshold ${minConfidence})`);return {- text: '',+ text: "",confidence: overallConfidence};}@@ -144,7 +142,7 @@ class TesseractRecognizer {// A line every word of which was dropped leaves no blank behind: the gap would read as// spacing on the picture that isn't there.if (keptWords.length > 0) {- keptLines.push(keptWords.join(' '));+ keptLines.push(keptWords.join(" "));}}@@ -156,7 +154,7 @@ class TesseractRecognizer {getLog().info(`Filtered OCR text: ${keptConfidences.length} words kept out of ${totalWords} total words (min confidence: ${minConfidence})`);return {- text: keptLines.join('\n').trim(),+ text: keptLines.join("\n").trim(),confidence: averageConfidence};}@@ -165,7 +163,7 @@ class TesseractRecognizer {* Get minimum confidence threshold from options*/private getMinConfidenceThreshold(): number {- const minConfidence = options.getOption('ocrMinConfidence') ?? 0;+ const minConfidence = options.getOption("ocrMinConfidence") ?? 0;return parseFloat(minConfidence);}}