Skip to content

Build your personal knowledge base with Trilium Notes

feat(ocr): extract text from scanned PDFs via per-page OCR

Elian Doranbb8fbb484e0b
diff --git a/apps/server/src/services/ocr/processors/image_processor.spec.ts b/apps/server/src/services/ocr/processors/image_processor.spec.ts
index 5ecb52aff2..cedace5218 100644
--- a/apps/server/src/services/ocr/processors/image_processor.spec.ts
+++ b/apps/server/src/services/ocr/processors/image_processor.spec.ts
@@ -1,36 +1,11 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
-// Mock Tesseract.js so no real OCR model is ever loaded.
-const mockWorker = {
- recognize: vi.fn(),
- terminate: vi.fn().mockResolvedValue(undefined)
-};
-
-const mockTesseract = {
- createWorker: vi.fn()
-};
-
-vi.mock('tesseract.js', () => ({
- default: mockTesseract
-}));
-
-// Avoid touching the real filesystem for the worker cache directory.
-vi.mock('fs', () => ({
- default: {
- mkdirSync: vi.fn()
- }
-}));
+const mockRecognize = vi.fn();
-vi.mock('../../data_dir.js', () => ({
- default: {
- OCR_CACHE_DIR: '/tmp/trilium-ocr-test-cache'
- }
+vi.mock('../tesseract_recognizer.js', () => ({
+ default: { recognize: mockRecognize }
}));
-const mockOptions = {
- getOption: vi.fn()
-};
-
const mockLog = {
info: vi.fn(),
error: vi.fn()
@@ -40,7 +15,6 @@ vi.mock('@triliumnext/core', async (importOriginal) => {
const actual = await importOriginal<typeof import('@triliumnext/core')>();
return {
...actual,
- options: mockOptions,
getLog: () => mockLog
};
});
@@ -49,8 +23,6 @@ let ImageProcessor: typeof import('./image_processor.js').ImageProcessor;
beforeEach(async () => {
vi.clearAllMocks();
- mockOptions.getOption.mockReturnValue('0');
- mockTesseract.createWorker.mockResolvedValue(mockWorker);
({ ImageProcessor } = await import('./image_processor.js'));
});
@@ -73,89 +45,31 @@ describe('ImageProcessor', () => {
expect(processor.getProcessingType()).toBe('image');
});
- it('extracts text and returns it untrimmed-confidence when no threshold is set', async () => {
+ it('delegates recognition to the shared recognizer and wraps the result', async () => {
const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: ' hello world ', confidence: 88, words: [] }
- });
+ mockRecognize.mockResolvedValue({ text: 'hello world', confidence: 0.88 });
const result = await processor.extractText(buffer, { language: 'eng' });
+ expect(mockRecognize).toHaveBeenCalledWith(buffer, 'eng');
expect(result.text).toBe('hello world');
expect(result.confidence).toBeCloseTo(0.88);
expect(result.language).toBe('eng');
expect(result.pageCount).toBe(1);
- expect(mockTesseract.createWorker).toHaveBeenCalledWith(
- 'eng',
- 1,
- expect.objectContaining({ cachePath: '/tmp/trilium-ocr-test-cache' })
- );
});
it('defaults the language to eng when none is supplied', async () => {
const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: 'x', confidence: 50, words: [] }
- });
+ mockRecognize.mockResolvedValue({ text: 'x', confidence: 0.5 });
await processor.extractText(buffer);
- expect(mockTesseract.createWorker).toHaveBeenCalledWith('eng', 1, expect.anything());
- });
-
- it('reuses the worker for the same language and recreates it when the language changes', async () => {
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: 'a', confidence: 50, words: [] }
- });
-
- await processor.extractText(buffer, { language: 'eng' });
- await processor.extractText(buffer, { language: 'eng' });
- expect(mockTesseract.createWorker).toHaveBeenCalledTimes(1);
- expect(mockWorker.terminate).not.toHaveBeenCalled();
-
- await processor.extractText(buffer, { language: 'deu' });
- expect(mockWorker.terminate).toHaveBeenCalledTimes(1);
- expect(mockTesseract.createWorker).toHaveBeenCalledTimes(2);
- });
-
- it('invokes the recognizing-text logger callback', async () => {
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: 'a', confidence: 50, words: [] }
- });
-
- await processor.extractText(buffer, { language: 'eng' });
-
- const config = mockTesseract.createWorker.mock.calls[0][2];
- config.logger({ status: 'recognizing text', progress: 0.5 });
- config.logger({ status: 'loading', progress: 0.1 });
-
- expect(mockLog.info).toHaveBeenCalledWith(
- expect.stringContaining('Image OCR progress')
- );
- });
-
- it('passes an errorHandler that logs worker errors instead of rethrowing them', async () => {
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: 'a', confidence: 50, words: [] }
- });
-
- await processor.extractText(buffer, { language: '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(mockLog.error).toHaveBeenCalledWith(
- 'Tesseract worker error: Error attempting to read image.'
- );
+ expect(mockRecognize).toHaveBeenCalledWith(buffer, 'eng');
});
it('propagates and logs recognition errors', async () => {
const processor = new ImageProcessor();
- mockWorker.recognize.mockRejectedValue(new Error('recognize failed'));
+ mockRecognize.mockRejectedValue(new Error('recognize failed'));
await expect(processor.extractText(buffer, { language: 'eng' })).rejects.toThrow(
'recognize failed'
@@ -164,98 +78,4 @@ describe('ImageProcessor', () => {
expect.stringContaining('Image OCR text extraction failed')
);
});
-
- describe('confidence filtering', () => {
- it('keeps only words above the configured threshold', async () => {
- mockOptions.getOption.mockReturnValue('0.8');
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: {
- text: 'good bad good',
- confidence: 70,
- words: [
- { text: 'good', confidence: 90 },
- { text: 'bad', confidence: 50 },
- { text: 'good', confidence: 95 }
- ]
- }
- });
-
- const result = await processor.extractText(buffer, { language: 'eng' });
-
- expect(result.text).toBe('good good');
- expect(result.confidence).toBeCloseTo((0.9 + 0.95) / 2);
- });
-
- it('returns empty confidence when no words pass the threshold', async () => {
- mockOptions.getOption.mockReturnValue('0.99');
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: {
- text: 'low',
- confidence: 10,
- words: [{ text: 'low', confidence: 10 }]
- }
- });
-
- const result = await processor.extractText(buffer, { language: 'eng' });
-
- expect(result.text).toBe('');
- expect(result.confidence).toBe(0);
- });
-
- it('handles an empty word array with a threshold set', async () => {
- mockOptions.getOption.mockReturnValue('0.5');
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: 'ignored', confidence: 80, words: [] }
- });
-
- const result = await processor.extractText(buffer, { language: 'eng' });
-
- expect(result.text).toBe('');
- expect(result.confidence).toBe(0);
- });
-
- it('falls back to overall confidence when there is no word-level data', async () => {
- mockOptions.getOption.mockReturnValue('0.5');
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: ' whole text ', confidence: 80, words: undefined }
- });
-
- const result = await processor.extractText(buffer, { language: 'eng' });
-
- 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');
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: 'whole text', confidence: 40, words: undefined }
- });
-
- const result = await processor.extractText(buffer, { language: 'eng' });
-
- expect(result.text).toBe('');
- expect(result.confidence).toBeCloseTo(0.4);
- expect(mockLog.info).toHaveBeenCalledWith(
- expect.stringContaining('Entire text filtered out')
- );
- });
-
- it('defaults the threshold to 0 when the option is null', async () => {
- mockOptions.getOption.mockReturnValue(null);
- const processor = new ImageProcessor();
- mockWorker.recognize.mockResolvedValue({
- data: { text: 'kept', confidence: 30, words: [{ text: 'kept', confidence: 30 }] }
- });
-
- const result = await processor.extractText(buffer, { language: 'eng' });
-
- expect(result.text).toBe('kept');
- });
- });
});
diff --git a/apps/server/src/services/ocr/processors/image_processor.ts b/apps/server/src/services/ocr/processors/image_processor.ts
index ccfe323263..e61d58a2e0 100644
--- a/apps/server/src/services/ocr/processors/image_processor.ts
+++ b/apps/server/src/services/ocr/processors/image_processor.ts
@@ -1,18 +1,13 @@
-import { options } from '@triliumnext/core';
-import fs from 'fs';
-import Tesseract from 'tesseract.js';
-
-import dataDirs from '../../data_dir.js';
import { getLog } from "@triliumnext/core";
-import { OCRProcessingOptions,OCRResult } from '../ocr_service.js';
+
+import { OCRProcessingOptions, OCRResult } from '../ocr_service.js';
+import recognizer from '../tesseract_recognizer.js';
import { FileProcessor } from './file_processor.js';
/**
* Image processor for extracting text from image files using Tesseract
*/
export class ImageProcessor extends FileProcessor {
- private worker: Tesseract.Worker | null = null;
- private currentLanguage: string | null = null;
// Formats that tesseract.js can actually decode (see its docs/image-format.md);
// TIFF is deliberately absent — Leptonica in tesseract.js-core is built without libtiff,
// so TIFF buffers always fail with "Error attempting to read image".
@@ -35,26 +30,19 @@ export class ImageProcessor extends FileProcessor {
async extractText(buffer: Buffer, options: OCRProcessingOptions = {}): Promise<OCRResult> {
const language = options.language || "eng";
- await this.ensureWorker(language);
try {
getLog().info(`Starting image OCR text extraction (language: ${language})...`);
- const result = await this.worker!.recognize(buffer);
-
- // Filter text based on minimum confidence threshold
- const { filteredText, overallConfidence } = this.filterTextByConfidence(result.data);
+ const { text, confidence } = await recognizer.recognize(buffer, language);
- const ocrResult: OCRResult = {
- text: filteredText,
- confidence: overallConfidence,
+ return {
+ text,
+ confidence,
extractedAt: new Date().toISOString(),
language,
pageCount: 1
};
-
- return ocrResult;
-
} catch (error) {
getLog().error(`Image OCR text extraction failed: ${error}`);
throw error;
@@ -64,106 +52,4 @@ export class ImageProcessor extends FileProcessor {
getProcessingType(): string {
return 'image';
}
-
- /**
- * Ensures a Tesseract worker is ready for the given language.
- * Creates a new worker if none exists or if the language has changed.
- */
- private async ensureWorker(language: string): Promise<void> {
- if (this.worker && this.currentLanguage === language) {
- return;
- }
-
- if (this.worker) {
- await this.worker.terminate();
- }
-
- fs.mkdirSync(dataDirs.OCR_CACHE_DIR, { recursive: true });
-
- getLog().info(`Initializing Tesseract worker for language(s): ${language}`);
- this.worker = await Tesseract.createWorker(language, 1, {
- cachePath: dataDirs.OCR_CACHE_DIR,
- // Without an errorHandler, tesseract.js rethrows job failures (e.g. undecodable
- // images) from its worker message handler as uncaught exceptions — in the desktop
- // app that surfaces as Electron's blocking "JavaScript error" dialog (#9754).
- // The job promise still rejects, so callers handle the failure normally.
- errorHandler: (error: unknown) => {
- getLog().error(`Tesseract worker error: ${error}`);
- },
- logger: (m: { status: string; progress: number }) => {
- if (m.status === 'recognizing text') {
- getLog().info(`Image OCR progress (${language}): ${Math.round(m.progress * 100)}%`);
- }
- }
- });
- this.currentLanguage = language;
- }
-
-
- /**
- * Filter text based on minimum confidence threshold
- */
- private filterTextByConfidence(data: any): { filteredText: string; overallConfidence: number } {
- const minConfidence = this.getMinConfidenceThreshold();
-
- // If no minimum confidence set, return original text
- if (minConfidence <= 0) {
- return {
- filteredText: data.text.trim(),
- overallConfidence: data.confidence / 100
- };
- }
-
- const filteredWords: string[] = [];
- const validConfidences: number[] = [];
-
- // Tesseract provides word-level data
- if (data.words && Array.isArray(data.words)) {
- for (const word of data.words) {
- const wordConfidence = word.confidence / 100; // Convert to decimal
-
- if (wordConfidence >= minConfidence) {
- filteredWords.push(word.text);
- validConfidences.push(wordConfidence);
- }
- }
- } else {
- // Fallback: if word-level data not available, use overall confidence
- const overallConfidence = data.confidence / 100;
- if (overallConfidence >= minConfidence) {
- return {
- filteredText: data.text.trim(),
- overallConfidence
- };
- }
- getLog().info(`Entire text filtered out due to low confidence ${overallConfidence} (below threshold ${minConfidence})`);
- return {
- filteredText: '',
- overallConfidence
- };
- }
-
- // Calculate average confidence of accepted words
- const averageConfidence = validConfidences.length > 0
- ? validConfidences.reduce((sum, conf) => sum + conf, 0) / validConfidences.length
- : 0;
-
- const filteredText = filteredWords.join(' ').trim();
-
- getLog().info(`Filtered OCR text: ${filteredWords.length} words kept out of ${data.words?.length || 0} total words (min confidence: ${minConfidence})`);
-
- return {
- filteredText,
- overallConfidence: averageConfidence
- };
- }
-
- /**
- * Get minimum confidence threshold from options
- */
- private getMinConfidenceThreshold(): number {
- const minConfidence = options.getOption('ocrMinConfidence') ?? 0;
- return parseFloat(minConfidence);
- }
-
}
diff --git a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts b/apps/server/src/services/ocr/processors/pdf_processor.spec.ts
index 48fa740550..e0b438bf8d 100644
--- a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts
+++ b/apps/server/src/services/ocr/processors/pdf_processor.spec.ts
@@ -2,10 +2,25 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const mockGetDocumentProxy = vi.fn();
const mockExtractText = vi.fn();
+const mockExtractImages = vi.fn();
vi.mock('unpdf', () => ({
getDocumentProxy: mockGetDocumentProxy,
- extractText: mockExtractText
+ extractText: mockExtractText,
+ extractImages: mockExtractImages
+}));
+
+const mockGetBuffer = vi.fn().mockResolvedValue(Buffer.from('png-bytes'));
+const mockFromBitmap = vi.fn(() => ({ getBuffer: mockGetBuffer }));
+
+vi.mock('jimp', () => ({
+ Jimp: { fromBitmap: mockFromBitmap }
+}));
+
+const mockRecognize = vi.fn();
+
+vi.mock('../tesseract_recognizer.js', () => ({
+ default: { recognize: mockRecognize }
}));
const mockLog = { info: vi.fn(), error: vi.fn() };
@@ -23,6 +38,7 @@ let PDFProcessor: typeof import('./pdf_processor.js').PDFProcessor;
beforeEach(async () => {
vi.clearAllMocks();
mockGetDocumentProxy.mockResolvedValue({ proxy: true });
+ mockGetBuffer.mockResolvedValue(Buffer.from('png-bytes'));
({ PDFProcessor } = await import('./pdf_processor.js'));
});
@@ -31,6 +47,8 @@ afterEach(() => {
});
const buffer = Buffer.from('%PDF-1.4 fake');
+// A 1x1 grayscale image, as unpdf's extractImages returns it.
+const scannedImage = { data: new Uint8ClampedArray([128]), width: 1, height: 1, channels: 1, key: 'img_0' };
describe('PDFProcessor', () => {
it('reports the MIME types it can process', () => {
@@ -42,34 +60,100 @@ describe('PDFProcessor', () => {
expect(processor.getProcessingType()).toBe('pdf');
});
- it('extracts merged text and reports high confidence when text is present', async () => {
+ it('uses the embedded text layer and never rasterizes when pages have text', async () => {
const processor = new PDFProcessor();
- mockExtractText.mockResolvedValue({ totalPages: 3, text: ' hello pdf ' });
+ mockExtractText.mockResolvedValue({
+ totalPages: 2,
+ text: [' first page with plenty of text ', 'second page with plenty of text']
+ });
const result = await processor.extractText(buffer, { language: 'fra' });
- expect(result.text).toBe('hello pdf');
+ expect(result.text).toBe('first page with plenty of text\n\nsecond page with plenty of text');
expect(result.confidence).toBe(0.99);
- expect(result.pageCount).toBe(3);
+ expect(result.pageCount).toBe(2);
expect(result.language).toBe('fra');
- expect(mockExtractText).toHaveBeenCalledWith(
- { proxy: true },
- { mergePages: true }
- );
+ expect(mockExtractText).toHaveBeenCalledWith({ proxy: true }, { mergePages: false });
+ // No scanned page → no image extraction and no OCR.
+ expect(mockExtractImages).not.toHaveBeenCalled();
+ expect(mockRecognize).not.toHaveBeenCalled();
// buffer is wrapped into a Uint8Array carrying the SAME bytes before being passed to unpdf
const [docArg] = mockGetDocumentProxy.mock.calls[0];
expect(docArg).toBeInstanceOf(Uint8Array);
expect(Buffer.from(docArg as Uint8Array).toString()).toBe('%PDF-1.4 fake');
});
- it('reports zero confidence and defaults language when no text is extracted', async () => {
+ it('OCRs a scanned (text-less) page via its embedded images', async () => {
+ const processor = new PDFProcessor();
+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [' '] });
+ mockExtractImages.mockResolvedValue([scannedImage]);
+ mockRecognize.mockResolvedValue({ text: 'recognized text', confidence: 0.9 });
+
+ const result = await processor.extractText(buffer, { language: 'eng' });
+
+ expect(mockExtractImages).toHaveBeenCalledWith({ proxy: true }, 1);
+ expect(mockFromBitmap).toHaveBeenCalledOnce();
+ 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('handles a mixed PDF, combining embedded text and OCR per page', async () => {
+ const processor = new PDFProcessor();
+ mockExtractText.mockResolvedValue({
+ totalPages: 2,
+ text: ['a real text page long enough', '']
+ });
+ mockExtractImages.mockResolvedValue([scannedImage]);
+ mockRecognize.mockResolvedValue({ text: 'scanned page text', confidence: 0.8 });
+
+ const result = await processor.extractText(buffer, { language: 'eng' });
+
+ expect(result.text).toBe('a real text page long enough\n\nscanned page text');
+ // Only the second (scanned) page is OCR'd.
+ expect(mockExtractImages).toHaveBeenCalledTimes(1);
+ expect(mockExtractImages).toHaveBeenCalledWith({ proxy: true }, 2);
+ // Average of the embedded-page (0.99) and OCR-page (0.8) confidences.
+ expect(result.confidence).toBeCloseTo((0.99 + 0.8) / 2);
+ });
+
+ it('reports zero confidence and empty text for a scanned page with nothing recognizable', async () => {
const processor = new PDFProcessor();
- mockExtractText.mockResolvedValue({ totalPages: 1, text: ' ' });
+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });
+ mockExtractImages.mockResolvedValue([]);
- const result = await processor.extractText(buffer);
+ const result = await processor.extractText(buffer, { language: 'eng' });
expect(result.text).toBe('');
expect(result.confidence).toBe(0);
- expect(result.language).toBe('eng');
+ expect(mockRecognize).not.toHaveBeenCalled();
+ });
+
+ it('tolerates an image extraction failure on a page without aborting the document', async () => {
+ const processor = new PDFProcessor();
+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });
+ mockExtractImages.mockRejectedValue(new Error('broken page'));
+
+ const result = await processor.extractText(buffer, { language: 'eng' });
+
+ expect(result.text).toBe('');
+ expect(result.confidence).toBe(0);
+ 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 () => {
+ const processor = new PDFProcessor();
+ const totalPages = 55;
+ mockExtractText.mockResolvedValue({ totalPages, text: Array(totalPages).fill('') });
+ mockExtractImages.mockResolvedValue([scannedImage]);
+ mockRecognize.mockResolvedValue({ text: 'p', confidence: 0.9 });
+
+ const result = await processor.extractText(buffer, { language: 'eng' });
+
+ // MAX_OCR_PAGES = 50; the remaining 5 scanned pages are skipped, not OCR'd.
+ expect(mockRecognize).toHaveBeenCalledTimes(50);
+ 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.ts
index 3581e18e06..a0eca98436 100644
--- a/apps/server/src/services/ocr/processors/pdf_processor.ts
+++ b/apps/server/src/services/ocr/processors/pdf_processor.ts
@@ -1,11 +1,34 @@
-import { extractText, getDocumentProxy } from 'unpdf';
-
import { getLog } from "@triliumnext/core";
+import { Jimp } from "jimp";
+import { extractImages, extractText, getDocumentProxy } from 'unpdf';
+
import { OCRProcessingOptions, OCRResult } from '../ocr_service.js';
+import recognizer from '../tesseract_recognizer.js';
import { FileProcessor } from './file_processor.js';
+type PdfDocument = Awaited<ReturnType<typeof getDocumentProxy>>;
+
+/** A page whose embedded text is shorter than this (after trimming) is treated as scanned and sent to OCR. */
+const MIN_EMBEDDED_PAGE_CHARS = 16;
+
+/**
+ * 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.
+ */
+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. */
+const EMBEDDED_TEXT_CONFIDENCE = 0.99;
+
/**
- * PDF processor for extracting embedded text from PDF files using unpdf.
+ * PDF processor. Prefers the PDF's embedded text layer (fast and exact) and
+ * falls back to OCR for scanned, image-only pages by extracting each page's
+ * embedded images and running them through the shared Tesseract recognizer.
+ * Detection is per page, so mixed PDFs (some real-text pages, some scans) are
+ * handled correctly.
*/
export class PDFProcessor extends FileProcessor {
@@ -20,15 +43,59 @@ export class PDFProcessor extends FileProcessor {
async extractText(buffer: Buffer, options: OCRProcessingOptions = {}): Promise<OCRResult> {
getLog().info('Starting PDF text extraction...');
+ const language = options.language || "eng";
const pdf = await getDocumentProxy(new Uint8Array(buffer));
- const { totalPages, text } = await extractText(pdf, { mergePages: true });
- const trimmed = text.trim();
+ const { totalPages, text: pageTexts } = await extractText(pdf, { mergePages: false });
+
+ const pageResults: string[] = [];
+ const pageConfidences: number[] = [];
+ let ocrPagesProcessed = 0;
+ let ocrPagesSkipped = 0;
+
+ for (let pageNum = 1; pageNum <= totalPages; pageNum++) {
+ const embedded = (pageTexts[pageNum - 1] ?? "").trim();
+
+ if (embedded.length >= MIN_EMBEDDED_PAGE_CHARS) {
+ pageResults.push(embedded);
+ pageConfidences.push(EMBEDDED_TEXT_CONFIDENCE);
+ continue;
+ }
+
+ if (ocrPagesProcessed >= MAX_OCR_PAGES) {
+ ocrPagesSkipped++;
+ if (embedded.length > 0) {
+ pageResults.push(embedded);
+ pageConfidences.push(EMBEDDED_TEXT_CONFIDENCE);
+ }
+ continue;
+ }
+
+ ocrPagesProcessed++;
+ const ocr = await this.ocrPage(pdf, pageNum, language);
+ if (ocr.text.length > 0) {
+ pageResults.push(ocr.text);
+ pageConfidences.push(ocr.confidence);
+ } else if (embedded.length > 0) {
+ // Nothing OCR-able on the page; keep whatever little embedded text it had.
+ pageResults.push(embedded);
+ pageConfidences.push(EMBEDDED_TEXT_CONFIDENCE);
+ }
+ }
+
+ if (ocrPagesSkipped > 0) {
+ getLog().info(`PDF OCR page cap reached: OCR'd ${MAX_OCR_PAGES} page(s), skipped ${ocrPagesSkipped} further scanned page(s).`);
+ }
+
+ const text = pageResults.join("\n\n").trim();
+ const confidence = text.length === 0 || pageConfidences.length === 0
+ ? 0
+ : pageConfidences.reduce((sum, c) => sum + c, 0) / pageConfidences.length;
return {
- text: trimmed,
- confidence: trimmed.length > 0 ? 0.99 : 0,
+ text,
+ confidence,
extractedAt: new Date().toISOString(),
- language: options.language || "eng",
+ language,
pageCount: totalPages
};
}
@@ -37,4 +104,83 @@ export class PDFProcessor extends FileProcessor {
return 'pdf';
}
+ /**
+ * OCR a single scanned page by recognizing each embedded image it paints and
+ * concatenating the results. Failures on an individual page are logged and
+ * treated as "no text" so one bad page never aborts the whole document.
+ */
+ private async ocrPage(pdf: PdfDocument, pageNum: number, language: string): Promise<{ text: string; confidence: number }> {
+ try {
+ const images = await extractImages(pdf, pageNum);
+ if (images.length === 0) {
+ return { text: "", confidence: 0 };
+ }
+
+ const parts: string[] = [];
+ const confidences: number[] = [];
+
+ for (const image of images) {
+ const png = await toPngBuffer(image);
+ const { text, confidence } = await recognizer.recognize(png, language);
+ if (text.length > 0) {
+ parts.push(text);
+ confidences.push(confidence);
+ }
+ }
+
+ return {
+ text: parts.join("\n"),
+ confidence: confidences.length > 0
+ ? confidences.reduce((sum, c) => sum + c, 0) / confidences.length
+ : 0
+ };
+ } catch (error) {
+ getLog().error(`PDF OCR failed for page ${pageNum}: ${error}`);
+ return { text: "", confidence: 0 };
+ }
+ }
+}
+
+interface ExtractedImage {
+ data: Uint8ClampedArray;
+ width: number;
+ height: number;
+ channels: 1 | 3 | 4;
+}
+
+/**
+ * Encode a raw image extracted from a PDF into a PNG buffer that Tesseract can
+ * decode. unpdf returns 1- (grayscale), 3- (RGB) or 4-channel (RGBA) pixel data;
+ * Jimp bitmaps are always RGBA, so narrower formats are expanded here.
+ */
+async function toPngBuffer(image: ExtractedImage): Promise<Buffer> {
+ const { data, width, height, channels } = image;
+ const pixelCount = width * height;
+ const rgba = Buffer.alloc(pixelCount * 4);
+
+ for (let i = 0; i < pixelCount; i++) {
+ const out = i * 4;
+ if (channels === 1) {
+ const value = data[i];
+ rgba[out] = value;
+ rgba[out + 1] = value;
+ rgba[out + 2] = value;
+ rgba[out + 3] = 255;
+ } else if (channels === 3) {
+ const src = i * 3;
+ rgba[out] = data[src];
+ rgba[out + 1] = data[src + 1];
+ rgba[out + 2] = data[src + 2];
+ rgba[out + 3] = 255;
+ } else {
+ const src = i * 4;
+ rgba[out] = data[src];
+ rgba[out + 1] = data[src + 1];
+ rgba[out + 2] = data[src + 2];
+ rgba[out + 3] = data[src + 3];
+ }
+ }
+
+ const jimpImage = Jimp.fromBitmap({ data: rgba, width, height });
+ return jimpImage.getBuffer("image/png");
}
diff --git a/apps/server/src/services/ocr/tesseract_recognizer.spec.ts b/apps/server/src/services/ocr/tesseract_recognizer.spec.ts
new file mode 100644
index 0000000000..ab5acca86f
--- /dev/null
+++ b/apps/server/src/services/ocr/tesseract_recognizer.spec.ts
@@ -0,0 +1,222 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Mock Tesseract.js so no real OCR model is ever loaded.
+const mockWorker = {
+ recognize: vi.fn(),
+ terminate: vi.fn().mockResolvedValue(undefined)
+};
+
+const mockTesseract = {
+ createWorker: vi.fn()
+};
+
+vi.mock('tesseract.js', () => ({
+ default: mockTesseract
+}));
+
+// Avoid touching the real filesystem for the worker cache directory.
+vi.mock('fs', () => ({
+ default: {
+ mkdirSync: vi.fn()
+ }
+}));
+
+vi.mock('../data_dir.js', () => ({
+ default: {
+ OCR_CACHE_DIR: '/tmp/trilium-ocr-test-cache'
+ }
+}));
+
+const mockOptions = {
+ getOption: vi.fn()
+};
+
+const mockLog = {
+ info: vi.fn(),
+ error: vi.fn()
+};
+
+vi.mock('@triliumnext/core', async (importOriginal) => {
+ const actual = await importOriginal<typeof import('@triliumnext/core')>();
+ return {
+ ...actual,
+ options: mockOptions,
+ getLog: () => mockLog
+ };
+});
+
+// A fresh singleton is imported per test so worker state never leaks between them.
+let recognizer: typeof import('./tesseract_recognizer.js').default;
+
+beforeEach(async () => {
+ vi.resetModules();
+ vi.clearAllMocks();
+ mockOptions.getOption.mockReturnValue('0');
+ mockTesseract.createWorker.mockResolvedValue(mockWorker);
+ recognizer = (await import('./tesseract_recognizer.js')).default;
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+const image = Buffer.from('fake-image');
+
+describe('TesseractRecognizer', () => {
+ it('recognizes text and reports overall confidence when no threshold is set', async () => {
+ mockWorker.recognize.mockResolvedValue({
+ data: { text: ' hello world ', confidence: 88, words: [] }
+ });
+
+ const result = await recognizer.recognize(image, 'eng');
+
+ expect(result.text).toBe('hello world');
+ expect(result.confidence).toBeCloseTo(0.88);
+ expect(mockTesseract.createWorker).toHaveBeenCalledWith(
+ 'eng',
+ 1,
+ expect.objectContaining({ cachePath: '/tmp/trilium-ocr-test-cache' })
+ );
+ });
+
+ it('reuses the worker for the same language and recreates it when the language changes', async () => {
+ mockWorker.recognize.mockResolvedValue({
+ data: { text: 'a', confidence: 50, words: [] }
+ });
+
+ 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');
+ expect(mockWorker.terminate).toHaveBeenCalledTimes(1);
+ expect(mockTesseract.createWorker).toHaveBeenCalledTimes(2);
+ });
+
+ it('invokes the recognizing-text logger callback', async () => {
+ mockWorker.recognize.mockResolvedValue({
+ data: { text: 'a', confidence: 50, words: [] }
+ });
+
+ 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 });
+
+ expect(mockLog.info).toHaveBeenCalledWith(
+ expect.stringContaining('OCR progress')
+ );
+ });
+
+ it('passes an errorHandler that logs worker errors instead of rethrowing them', async () => {
+ mockWorker.recognize.mockResolvedValue({
+ data: { text: 'a', confidence: 50, words: [] }
+ });
+
+ 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(mockLog.error).toHaveBeenCalledWith(
+ 'Tesseract worker error: Error attempting to read image.'
+ );
+ });
+
+ 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');
+ });
+
+ describe('confidence filtering', () => {
+ it('keeps only words above the configured threshold', async () => {
+ mockOptions.getOption.mockReturnValue('0.8');
+ mockWorker.recognize.mockResolvedValue({
+ data: {
+ text: 'good bad good',
+ confidence: 70,
+ words: [
+ { text: 'good', confidence: 90 },
+ { text: 'bad', confidence: 50 },
+ { text: 'good', confidence: 95 }
+ ]
+ }
+ });
+
+ const result = await recognizer.recognize(image, 'eng');
+
+ expect(result.text).toBe('good good');
+ expect(result.confidence).toBeCloseTo((0.9 + 0.95) / 2);
+ });
+
+ it('returns empty confidence when no words pass the threshold', async () => {
+ mockOptions.getOption.mockReturnValue('0.99');
+ mockWorker.recognize.mockResolvedValue({
+ data: {
+ text: 'low',
+ confidence: 10,
+ words: [{ text: 'low', confidence: 10 }]
+ }
+ });
+
+ const result = await recognizer.recognize(image, 'eng');
+
+ expect(result.text).toBe('');
+ expect(result.confidence).toBe(0);
+ });
+
+ it('handles an empty word array with a threshold set', async () => {
+ mockOptions.getOption.mockReturnValue('0.5');
+ mockWorker.recognize.mockResolvedValue({
+ data: { text: 'ignored', confidence: 80, words: [] }
+ });
+
+ const result = await recognizer.recognize(image, 'eng');
+
+ expect(result.text).toBe('');
+ expect(result.confidence).toBe(0);
+ });
+
+ it('falls back to overall confidence when there is no word-level data', async () => {
+ mockOptions.getOption.mockReturnValue('0.5');
+ mockWorker.recognize.mockResolvedValue({
+ data: { text: ' whole text ', confidence: 80, words: undefined }
+ });
+
+ const result = await recognizer.recognize(image, 'eng');
+
+ 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');
+ mockWorker.recognize.mockResolvedValue({
+ data: { text: 'whole text', confidence: 40, words: undefined }
+ });
+
+ const result = await recognizer.recognize(image, 'eng');
+
+ expect(result.text).toBe('');
+ expect(result.confidence).toBeCloseTo(0.4);
+ expect(mockLog.info).toHaveBeenCalledWith(
+ expect.stringContaining('Entire text filtered out')
+ );
+ });
+
+ it('defaults the threshold to 0 when the option is null', async () => {
+ mockOptions.getOption.mockReturnValue(null);
+ mockWorker.recognize.mockResolvedValue({
+ data: { text: 'kept', confidence: 30, words: [{ text: 'kept', confidence: 30 }] }
+ });
+
+ const result = await recognizer.recognize(image, 'eng');
+
+ expect(result.text).toBe('kept');
+ });
+ });
+});
diff --git a/apps/server/src/services/ocr/tesseract_recognizer.ts b/apps/server/src/services/ocr/tesseract_recognizer.ts
new file mode 100644
index 0000000000..9e53676dd6
--- /dev/null
+++ b/apps/server/src/services/ocr/tesseract_recognizer.ts
@@ -0,0 +1,148 @@
+import { getLog, options } from '@triliumnext/core';
+import fs from 'fs';
+import Tesseract from 'tesseract.js';
+
+import dataDirs from '../data_dir.js';
+
+export interface RecognitionResult {
+ /** Recognized text after per-word confidence filtering. */
+ text: string;
+ /** Overall confidence in the range [0, 1] of the kept text. */
+ confidence: number;
+}
+
+/** The subset of Tesseract's page result this recognizer relies on. */
+interface RecognizedData {
+ text: string;
+ /** Overall page confidence, 0–100. */
+ confidence: number;
+ /** Per-word data; absent in some Tesseract output configurations. */
+ words?: Array<{ text: string; confidence: number }>;
+}
+
+/**
+ * Owns a single long-lived Tesseract.js worker and the confidence filtering
+ * shared by every OCR path that recognizes raster images — standalone image
+ * notes/attachments and, page by page, scanned PDFs. Keeping one worker (rather
+ * than one per processor) avoids paying the model-load cost repeatedly and lets
+ * an image and a PDF page reuse the same loaded language data.
+ */
+class TesseractRecognizer {
+ private worker: Tesseract.Worker | null = null;
+ private currentLanguage: string | null = null;
+
+ /**
+ * Recognize text in an encoded image buffer (PNG/JPEG/etc.) for the given
+ * Tesseract language code(s), applying the configured confidence filtering.
+ */
+ async recognize(image: Buffer, language: string): Promise<RecognitionResult> {
+ const worker = await this.ensureWorker(language);
+ const { data } = await worker.recognize(image);
+ return this.filterTextByConfidence(data);
+ }
+
+ /**
+ * Ensures a Tesseract worker is ready for the given language.
+ * Creates a new worker if none exists or if the language has changed.
+ */
+ private async ensureWorker(language: string): Promise<Tesseract.Worker> {
+ if (this.worker && this.currentLanguage === language) {
+ return this.worker;
+ }
+
+ if (this.worker) {
+ await this.worker.terminate();
+ this.worker = null;
+ }
+
+ fs.mkdirSync(dataDirs.OCR_CACHE_DIR, { recursive: true });
+
+ getLog().info(`Initializing Tesseract worker for language(s): ${language}`);
+ const worker = await Tesseract.createWorker(language, 1, {
+ cachePath: dataDirs.OCR_CACHE_DIR,
+ // Without an errorHandler, tesseract.js rethrows job failures (e.g. undecodable
+ // images) from its worker message handler as uncaught exceptions — in the desktop
+ // app that surfaces as Electron's blocking "JavaScript error" dialog (#9754).
+ // The job promise still rejects, so callers handle the failure normally.
+ errorHandler: (error: unknown) => {
+ getLog().error(`Tesseract worker error: ${error}`);
+ },
+ logger: (m: { status: string; progress: number }) => {
+ if (m.status === 'recognizing text') {
+ getLog().info(`OCR progress (${language}): ${Math.round(m.progress * 100)}%`);
+ }
+ }
+ });
+ this.worker = worker;
+ this.currentLanguage = language;
+ return worker;
+ }
+
+ /**
+ * Filter text based on minimum confidence threshold
+ */
+ private filterTextByConfidence(data: RecognizedData): RecognitionResult {
+ const minConfidence = this.getMinConfidenceThreshold();
+
+ // If no minimum confidence set, return original text
+ if (minConfidence <= 0) {
+ return {
+ text: data.text.trim(),
+ confidence: data.confidence / 100
+ };
+ }
+
+ const filteredWords: string[] = [];
+ const validConfidences: number[] = [];
+
+ // Tesseract provides word-level data
+ if (data.words && Array.isArray(data.words)) {
+ for (const word of data.words) {
+ const wordConfidence = word.confidence / 100; // Convert to decimal
+
+ if (wordConfidence >= minConfidence) {
+ filteredWords.push(word.text);
+ validConfidences.push(wordConfidence);
+ }
+ }
+ } else {
+ // Fallback: if word-level data not available, use overall confidence
+ const overallConfidence = data.confidence / 100;
+ if (overallConfidence >= minConfidence) {
+ return {
+ text: data.text.trim(),
+ confidence: overallConfidence
+ };
+ }
+ getLog().info(`Entire text filtered out due to low confidence ${overallConfidence} (below threshold ${minConfidence})`);
+ return {
+ text: '',
+ confidence: overallConfidence
+ };
+ }
+
+ // Calculate average confidence of accepted words
+ const averageConfidence = validConfidences.length > 0
+ ? validConfidences.reduce((sum, conf) => sum + conf, 0) / validConfidences.length
+ : 0;
+
+ const filteredText = filteredWords.join(' ').trim();
+
+ getLog().info(`Filtered OCR text: ${filteredWords.length} words kept out of ${data.words?.length || 0} total words (min confidence: ${minConfidence})`);
+
+ return {
+ text: filteredText,
+ confidence: averageConfidence
+ };
+ }
+
+ /**
+ * Get minimum confidence threshold from options
+ */
+ private getMinConfidenceThreshold(): number {
+ const minConfidence = options.getOption('ocrMinConfidence') ?? 0;
+ return parseFloat(minConfidence);
+ }
+}
+
+export default new TesseractRecognizer();