Skip to content

Build your personal knowledge base with Trilium Notes

fix(ocr): address automated review feedback

Elian Doran7112ca530faa
diff --git a/apps/server/src/services/ocr/ocr_service.spec.ts b/apps/server/src/services/ocr/ocr_service.spec.ts
index d769c66475..a6ad7d7b28 100644
--- a/apps/server/src/services/ocr/ocr_service.spec.ts
+++ b/apps/server/src/services/ocr/ocr_service.spec.ts
@@ -752,18 +752,17 @@ describe('OCRService', () => {
]);
});
- it('re-selects blobs whose previous OCR produced an empty result', () => {
+ it('re-selects only PDF blobs whose previous OCR produced an empty result', () => {
mockSql.getRows.mockReturnValue([]);
ocrService.getBlobsNeedingOCR();
- // Both the note and attachment queries must match blobs with an empty
- // text representation (a previous run that extracted nothing), not only
- // never-processed (NULL) ones — otherwise scanned PDFs processed before
- // OCR fallback existed would never be picked up by a batch run.
+ // Empty text representations are re-processed only for PDFs (which gained
+ // the scanned-page fallback). Other formats keep the NULL-only semantics,
+ // otherwise every text-less image would be re-OCR'd on every batch run.
expect(mockSql.getRows.mock.calls).toHaveLength(2);
for (const [sqlText] of mockSql.getRows.mock.calls) {
- expect(sqlText).toContain("textRepresentation = ''");
+ expect(sqlText).toContain("application/pdf' AND b.textRepresentation = ''");
}
});
diff --git a/apps/server/src/services/ocr/ocr_service.ts b/apps/server/src/services/ocr/ocr_service.ts
index a61dfba9ee..05113c442e 100644
--- a/apps/server/src/services/ocr/ocr_service.ts
+++ b/apps/server/src/services/ocr/ocr_service.ts
@@ -411,10 +411,12 @@ class OCRService {
/**
- * Get blobs that need OCR processing: those with no stored text representation
- * yet. An empty string counts as "not processed" (matching {@link hasStoredOCRResult}),
- * so blobs a previous run extracted nothing from — e.g. scanned PDFs processed
- * before OCR fallback existed — are picked up again on the next batch.
+ * Get blobs that need OCR processing. A NULL text representation means "never
+ * processed". An empty string means "processed, found no text"; that is only
+ * re-selected for PDFs, which gained the scanned-page OCR fallback and so may
+ * yield text now where an earlier run stored nothing. Images and Office files
+ * behave as before, so their empty results are final and left alone — otherwise
+ * every text-less image would be re-OCR'd on every batch run.
*/
getBlobsNeedingOCR(): Array<{ blobId: string; mimeType: string; entityType: 'note' | 'attachment'; entityId: string }> {
try {
@@ -432,7 +434,7 @@ class OCRService {
WHERE (n.type = 'image' OR (n.type = 'file' AND n.mime IN (${placeholders})))
AND n.isDeleted = 0
AND n.blobId IS NOT NULL
- AND (b.textRepresentation IS NULL OR b.textRepresentation = '')
+ AND (b.textRepresentation IS NULL OR (n.mime = 'application/pdf' AND b.textRepresentation = ''))
`, supportedMimes);
const attachmentBlobs = sql.getRows<{
@@ -446,7 +448,7 @@ class OCRService {
WHERE (a.role = 'image' OR (a.role = 'file' AND a.mime IN (${placeholders})))
AND a.isDeleted = 0
AND a.blobId IS NOT NULL
- AND (b.textRepresentation IS NULL OR b.textRepresentation = '')
+ AND (b.textRepresentation IS NULL OR (a.mime = 'application/pdf' AND b.textRepresentation = ''))
`, supportedMimes);
// Combine results
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 e0b438bf8d..c73453d6c4 100644
--- a/apps/server/src/services/ocr/processors/pdf_processor.spec.ts
+++ b/apps/server/src/services/ocr/processors/pdf_processor.spec.ts
@@ -47,8 +47,9 @@ 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' };
+// A full-page grayscale scan, as unpdf's extractImages returns it — comfortably
+// above the minimum OCR dimension so it isn't skipped as a decorative image.
+const scannedImage = { data: new Uint8ClampedArray(100 * 100), width: 100, height: 100, channels: 1, key: 'img_0' };
describe('PDFProcessor', () => {
it('reports the MIME types it can process', () => {
@@ -142,6 +143,49 @@ describe('PDFProcessor', () => {
expect(mockLog.error).toHaveBeenCalledWith(expect.stringContaining('PDF OCR failed for page 1'));
});
+ it('skips embedded images below the minimum OCR dimension', async () => {
+ const processor = new PDFProcessor();
+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });
+ // A 20x20 icon — too small to hold recognizable text.
+ mockExtractImages.mockResolvedValue([
+ { data: new Uint8ClampedArray(20 * 20), width: 20, height: 20, channels: 1, key: 'icon' }
+ ]);
+
+ const result = await processor.extractText(buffer, { language: 'eng' });
+
+ expect(mockFromBitmap).not.toHaveBeenCalled();
+ expect(mockRecognize).not.toHaveBeenCalled();
+ expect(result.text).toBe('');
+ });
+
+ it('OCRs an RGBA page image', async () => {
+ const processor = new PDFProcessor();
+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });
+ mockExtractImages.mockResolvedValue([
+ { data: new Uint8ClampedArray(60 * 60 * 4), width: 60, height: 60, channels: 4, key: 'rgba' }
+ ]);
+ mockRecognize.mockResolvedValue({ text: 'rgba text', confidence: 0.7 });
+
+ const result = await processor.extractText(buffer, { language: 'eng' });
+
+ expect(mockFromBitmap).toHaveBeenCalledOnce();
+ expect(result.text).toBe('rgba text');
+ });
+
+ it('skips a page whose image has an unsupported channel count, logging the failure', async () => {
+ const processor = new PDFProcessor();
+ mockExtractText.mockResolvedValue({ totalPages: 1, text: [''] });
+ mockExtractImages.mockResolvedValue([
+ { data: new Uint8ClampedArray(50 * 50 * 2), width: 50, height: 50, channels: 2, key: 'weird' }
+ ]);
+
+ const result = await processor.extractText(buffer, { language: 'eng' });
+
+ expect(mockRecognize).not.toHaveBeenCalled();
+ expect(result.text).toBe('');
+ 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;
diff --git a/apps/server/src/services/ocr/processors/pdf_processor.ts b/apps/server/src/services/ocr/processors/pdf_processor.ts
index a0eca98436..70ccd8ccd7 100644
--- a/apps/server/src/services/ocr/processors/pdf_processor.ts
+++ b/apps/server/src/services/ocr/processors/pdf_processor.ts
@@ -23,6 +23,13 @@ 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;
+/**
+ * Embedded images smaller than this on either side are skipped: scanned pages are
+ * full-page raster, whereas tiny images are almost always icons, bullets or rules
+ * that hold no recognizable text and would only waste an OCR pass.
+ */
+const MIN_OCR_IMAGE_DIM = 50;
+
/**
* 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
@@ -120,6 +127,9 @@ export class PDFProcessor extends FileProcessor {
const confidences: number[] = [];
for (const image of images) {
+ if (image.width < MIN_OCR_IMAGE_DIM || image.height < MIN_OCR_IMAGE_DIM) {
+ continue;
+ }
const png = await toPngBuffer(image);
const { text, confidence } = await recognizer.recognize(png, language);
if (text.length > 0) {
@@ -145,40 +155,44 @@ interface ExtractedImage {
data: Uint8ClampedArray;
width: number;
height: number;
- channels: 1 | 3 | 4;
+ // Typed as a plain number rather than `1 | 3 | 4`: the value is whatever unpdf
+ // hands us at runtime, so it is validated below rather than trusted here.
+ channels: number;
}
/**
* 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.
+ * Jimp bitmaps are always RGBA, so narrower formats are expanded here. An
+ * unexpected channel count throws rather than silently producing garbled pixels.
*/
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];
+
+ let rgba: Buffer;
+ if (channels === 4) {
+ // Already RGBA — reuse the underlying bytes instead of copying pixel by pixel.
+ rgba = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
+ } else if (channels === 3 || channels === 1) {
+ 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;
+ } else {
+ 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];
}
+ } else {
+ throw new Error(`Unsupported image channel count: ${channels}`);
}
const jimpImage = Jimp.fromBitmap({ data: rgba, width, height });
diff --git a/apps/server/src/services/ocr/tesseract_recognizer.spec.ts b/apps/server/src/services/ocr/tesseract_recognizer.spec.ts
index ab5acca86f..f0c179efdf 100644
--- a/apps/server/src/services/ocr/tesseract_recognizer.spec.ts
+++ b/apps/server/src/services/ocr/tesseract_recognizer.spec.ts
@@ -94,6 +94,35 @@ describe('TesseractRecognizer', () => {
expect(mockTesseract.createWorker).toHaveBeenCalledTimes(2);
});
+ 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: { text: 'second', confidence: 50, words: [] } });
+
+ 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));
+
+ // The second (different-language) job must not have started: no second worker
+ // was created and the in-flight worker was not terminated mid-recognition.
+ expect(mockTesseract.createWorker).toHaveBeenCalledTimes(1);
+ expect(mockWorker.terminate).not.toHaveBeenCalled();
+
+ releaseFirst({ data: { text: 'first', confidence: 50, words: [] } });
+ const [r1, r2] = await Promise.all([p1, p2]);
+
+ 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 () => {
mockWorker.recognize.mockResolvedValue({
data: { text: 'a', confidence: 50, words: [] }
diff --git a/apps/server/src/services/ocr/tesseract_recognizer.ts b/apps/server/src/services/ocr/tesseract_recognizer.ts
index 9e53676dd6..850e71d2a3 100644
--- a/apps/server/src/services/ocr/tesseract_recognizer.ts
+++ b/apps/server/src/services/ocr/tesseract_recognizer.ts
@@ -30,15 +30,28 @@ interface RecognizedData {
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.
+ private queue: Promise<unknown> = Promise.resolve();
/**
* Recognize text in an encoded image buffer (PNG/JPEG/etc.) for the given
* Tesseract language code(s), applying the configured confidence filtering.
+ * Calls are queued so only one recognition runs at a time.
*/
- async recognize(image: Buffer, language: string): Promise<RecognitionResult> {
- const worker = await this.ensureWorker(language);
- const { data } = await worker.recognize(image);
- return this.filterTextByConfidence(data);
+ recognize(image: Buffer, language: string): Promise<RecognitionResult> {
+ const result = this.queue.then(async () => {
+ const worker = await this.ensureWorker(language);
+ const { data } = await worker.recognize(image);
+ return this.filterTextByConfidence(data);
+ });
+ // Keep the chain going regardless of this job's outcome, without swallowing
+ // the result/error the caller receives.
+ this.queue = result.catch(() => {});
+ return result;
}
/**