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
fix(ocr): read the per-word confidences tesseract actually returns
Elian Dorana4291c3b4e2e
diff --git a/apps/server/src/services/ocr/processors/image_processor.spec.ts b/apps/server/src/services/ocr/processors/image_processor.spec.tsindex 5ecb52aff2..2e6143a41f 100644--- a/apps/server/src/services/ocr/processors/image_processor.spec.ts+++ b/apps/server/src/services/ocr/processors/image_processor.spec.ts@@ -60,6 +60,31 @@ afterEach(() => {const buffer = Buffer.from('fake-image');+/**+ * A recognition result in the shape tesseract.js actually answers with when the `blocks` output+ * format is requested: the words are nested under blocks → paragraphs → lines, and there is no+ * top-level `words` array to read them from.+ */+function pageWithLines(confidence: number, lines: [ text: string, confidence: number ][][]) {+ return {+ text: lines.map(line => line.map(([ text ]) => text).join(' ')).join('\n'),+ confidence,+ blocks: [ {+ paragraphs: [ {+ lines: lines.map(line => ({+ text: line.map(([ text ]) => text).join(' '),+ words: line.map(([ text, wordConfidence ]) => ({ text, confidence: wordConfidence }))+ }))+ } ]+ } ]+ };+}++/** What a recognition with no readable text answers with: text, a score, and `blocks: null`. */+function pageWithoutBlocks(text: string, confidence: number) {+ return { text, confidence, blocks: null };+}+describe('ImageProcessor', () => {it('reports the MIME types it can process', () => {const processor = new ImageProcessor();@@ -76,7 +101,7 @@ describe('ImageProcessor', () => {it('extracts text and returns it untrimmed-confidence when no threshold is set', async () => {const processor = new ImageProcessor();mockWorker.recognize.mockResolvedValue({- data: { text: ' hello world ', confidence: 88, words: [] }+ data: { text: ' hello world ', confidence: 88, blocks: null }});const result = await processor.extractText(buffer, { language: 'eng' });@@ -92,10 +117,21 @@ describe('ImageProcessor', () => {);});+ it('asks tesseract for the per-word breakdown the confidence filter needs', async () => {+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({ data: pageWithLines(80, [ [ [ 'x', 80 ] ] ]) });++ await processor.extractText(buffer, { language: '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(buffer, {}, { blocks: true });+ });+it('defaults the language to eng when none is supplied', async () => {const processor = new ImageProcessor();mockWorker.recognize.mockResolvedValue({- data: { text: 'x', confidence: 50, words: [] }+ data: pageWithLines(50, [ [ [ 'x', 50 ] ] ])});await processor.extractText(buffer);@@ -106,7 +142,7 @@ describe('ImageProcessor', () => {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: [] }+ data: pageWithLines(50, [ [ [ 'a', 50 ] ] ])});await processor.extractText(buffer, { language: 'eng' });@@ -122,7 +158,7 @@ describe('ImageProcessor', () => {it('invokes the recognizing-text logger callback', async () => {const processor = new ImageProcessor();mockWorker.recognize.mockResolvedValue({- data: { text: 'a', confidence: 50, words: [] }+ data: pageWithLines(50, [ [ [ 'a', 50 ] ] ])});await processor.extractText(buffer, { language: 'eng' });@@ -139,7 +175,7 @@ describe('ImageProcessor', () => {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: [] }+ data: pageWithLines(50, [ [ [ 'a', 50 ] ] ])});await processor.extractText(buffer, { language: 'eng' });@@ -166,49 +202,58 @@ describe('ImageProcessor', () => {});describe('confidence filtering', () => {- it('keeps only words above the configured threshold', async () => {+ it('keeps the words above the threshold on the lines they were read on', 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 }- ]- }+ data: pageWithLines(70, [+ [ [ 'good', 90 ], [ 'bad', 50 ] ],+ [ [ 'also', 95 ], [ 'good', 85 ] ]+ ])});const result = await processor.extractText(buffer, { language: 'eng' });- expect(result.text).toBe('good good');- expect(result.confidence).toBeCloseTo((0.9 + 0.95) / 2);+ expect(result.text).toBe('good\nalso good');+ expect(result.confidence).toBeCloseTo((0.9 + 0.95 + 0.85) / 3);});- it('returns empty confidence when no words pass the threshold', async () => {- mockOptions.getOption.mockReturnValue('0.99');+ 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');const processor = new ImageProcessor();mockWorker.recognize.mockResolvedValue({- data: {- text: 'low',- confidence: 10,- words: [{ text: 'low', confidence: 10 }]- }+ data: pageWithLines(60, [ [ [ 'Invoice', 96 ], [ '®', 0 ], [ 'total', 94 ] ] ])});const result = await processor.extractText(buffer, { language: 'eng' });- expect(result.text).toBe('');- expect(result.confidence).toBe(0);+ expect(result.text).toBe('Invoice total');});- it('handles an empty word array with a threshold set', async () => {- mockOptions.getOption.mockReturnValue('0.5');+ it('leaves no blank line where every word of one was dropped', async () => {+ mockOptions.getOption.mockReturnValue('0.8');+ const processor = new ImageProcessor();+ mockWorker.recognize.mockResolvedValue({+ data: pageWithLines(70, [+ [ [ 'kept', 90 ] ],+ [ [ 'noise', 10 ] ],+ [ [ 'also-kept', 90 ] ]+ ])+ });++ const result = await processor.extractText(buffer, { language: 'eng' });++ 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');const processor = new ImageProcessor();mockWorker.recognize.mockResolvedValue({- data: { text: 'ignored', confidence: 80, words: [] }+ data: pageWithLines(10, [ [ [ 'low', 10 ] ] ])});const result = await processor.extractText(buffer, { language: 'eng' });@@ -217,11 +262,11 @@ describe('ImageProcessor', () => {expect(result.confidence).toBe(0);});- it('falls back to overall confidence when there is no word-level data', async () => {+ it('falls back to overall confidence when nothing was broken down into words', async () => {mockOptions.getOption.mockReturnValue('0.5');const processor = new ImageProcessor();mockWorker.recognize.mockResolvedValue({- data: { text: ' whole text ', confidence: 80, words: undefined }+ data: pageWithoutBlocks(' whole text ', 80)});const result = await processor.extractText(buffer, { language: 'eng' });@@ -234,7 +279,7 @@ describe('ImageProcessor', () => {mockOptions.getOption.mockReturnValue('0.9');const processor = new ImageProcessor();mockWorker.recognize.mockResolvedValue({- data: { text: 'whole text', confidence: 40, words: undefined }+ data: pageWithoutBlocks('whole text', 40)});const result = await processor.extractText(buffer, { language: 'eng' });@@ -250,7 +295,7 @@ describe('ImageProcessor', () => {mockOptions.getOption.mockReturnValue(null);const processor = new ImageProcessor();mockWorker.recognize.mockResolvedValue({- data: { text: 'kept', confidence: 30, words: [{ text: 'kept', confidence: 30 }] }+ data: pageWithLines(30, [ [ [ 'kept', 30 ] ] ])});const result = await processor.extractText(buffer, { language: 'eng' });diff --git a/apps/server/src/services/ocr/processors/image_processor.ts b/apps/server/src/services/ocr/processors/image_processor.tsindex ccfe323263..c406ff3bb5 100644--- a/apps/server/src/services/ocr/processors/image_processor.ts+++ b/apps/server/src/services/ocr/processors/image_processor.ts@@ -35,12 +35,15 @@ export class ImageProcessor extends FileProcessor {async extractText(buffer: Buffer, options: OCRProcessingOptions = {}): Promise<OCRResult> {const language = options.language || "eng";- await this.ensureWorker(language);+ const worker = await this.ensureWorker(language);try {getLog().info(`Starting image OCR text extraction (language: ${language})...`);- const result = await this.worker!.recognize(buffer);+ // The per-word breakdown the confidence filter runs on is an opt-in output format:+ // by default `recognize` answers with the plain text and nothing else, leaving the+ // filter with only the whole image's mean confidence to judge by.+ const result = await worker.recognize(buffer, {}, { blocks: true });// Filter text based on minimum confidence thresholdconst { filteredText, overallConfidence } = this.filterTextByConfidence(result.data);@@ -66,12 +69,12 @@ export class ImageProcessor extends FileProcessor {}/**- * Ensures a Tesseract worker is ready for the given language.+ * Ensures a Tesseract worker is ready for the given language, and hands it back.* Creates a new worker if none exists or if the language has changed.*/- private async ensureWorker(language: string): Promise<void> {+ private async ensureWorker(language: string): Promise<Tesseract.Worker> {if (this.worker && this.currentLanguage === language) {- return;+ return this.worker;}if (this.worker) {@@ -97,13 +100,20 @@ export class ImageProcessor extends FileProcessor {}});this.currentLanguage = language;+ return this.worker;}/**- * Filter text based on minimum confidence threshold+ * Filter text based on minimum confidence threshold.+ *+ * Word by word, because the words Tesseract is least sure of are usually not words at all —+ * a border read as punctuation, a speck read as a comma — and it is those that drag the mean+ * for the image down. Judging the image by that mean throws away every well-read word on it+ * along with them, so what is kept is decided per word and reassembled line by line, leaving+ * the text laid out as it is on the picture.*/- private filterTextByConfidence(data: any): { filteredText: string; overallConfidence: number } {+ private filterTextByConfidence(data: Tesseract.Page): { filteredText: string; overallConfidence: number } {const minConfidence = this.getMinConfidenceThreshold();// If no minimum confidence set, return original text@@ -114,21 +124,11 @@ export class ImageProcessor extends FileProcessor {};}- const filteredWords: string[] = [];- const validConfidences: number[] = [];+ const lines = getRecognizedLines(data);- // 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+ // Nothing was broken down into words — an image nothing could be read from. There is only+ // the one score to go by, so the text stands or falls as a whole.+ if (lines.length === 0) {const overallConfidence = data.confidence / 100;if (overallConfidence >= minConfidence) {return {@@ -143,14 +143,38 @@ export class ImageProcessor extends FileProcessor {};}+ const keptLines: string[] = [];+ const keptConfidences: number[] = [];+ let totalWords = 0;++ for (const line of lines) {+ const keptWords: string[] = [];++ for (const word of line.words ?? []) {+ totalWords++;+ const wordConfidence = word.confidence / 100; // Convert to decimal++ if (wordConfidence >= minConfidence) {+ keptWords.push(word.text);+ keptConfidences.push(wordConfidence);+ }+ }++ // 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(' '));+ }+ }+// Calculate average confidence of accepted words- const averageConfidence = validConfidences.length > 0- ? validConfidences.reduce((sum, conf) => sum + conf, 0) / validConfidences.length+ const averageConfidence = keptConfidences.length > 0+ ? keptConfidences.reduce((sum, conf) => sum + conf, 0) / keptConfidences.length: 0;- const filteredText = filteredWords.join(' ').trim();+ const filteredText = keptLines.join('\n').trim();- getLog().info(`Filtered OCR text: ${filteredWords.length} words kept out of ${data.words?.length || 0} total words (min confidence: ${minConfidence})`);+ getLog().info(`Filtered OCR text: ${keptConfidences.length} words kept out of ${totalWords} total words (min confidence: ${minConfidence})`);return {filteredText,@@ -167,3 +191,16 @@ export class ImageProcessor extends FileProcessor {}}++/**+ * The words Tesseract read, in the lines it read them on.+ *+ * They sit three levels down the page it describes, and that description is only present when the+ * `blocks` output format was asked for — see {@link ImageProcessor.extractText}. Without it, and+ * for an image nothing was read from, this is empty.+ */+function getRecognizedLines(data: Tesseract.Page): Tesseract.Line[] {+ return (data.blocks ?? []).flatMap(+ block => (block.paragraphs ?? []).flatMap(paragraph => paragraph.lines ?? [])+ );+}