kreuzberg 4.7.2

High-performance document intelligence library for Rust. Extract text, metadata, and structured data from PDFs, Office documents, images, and 91+ formats and 248 programming languages via tree-sitter code intelligence with async/sync APIs.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
//! OCR error handling and edge case tests.
//!
//! This module tests OCR error scenarios to ensure robust error handling:
//! - Invalid configurations (bad language codes, invalid PSM values)
//! - Corrupted or invalid image inputs
//! - Missing dependencies (Tesseract not installed)
//! - Cache-related errors
//! - Concurrent processing scenarios
//!
//! Test philosophy:
//! - Verify graceful handling of all error conditions
//! - Ensure error messages are informative
//! - Test recovery from transient failures
//! - Validate resource limits and constraints

#![cfg(feature = "ocr")]

mod helpers;

use helpers::*;
use kreuzberg::core::config::{ExtractionConfig, OcrConfig};
use kreuzberg::types::TesseractConfig;
use kreuzberg::{KreuzbergError, extract_bytes_sync, extract_file_sync};

#[test]
fn test_ocr_invalid_language_code() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "invalid_lang_99999".to_string(),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Err(KreuzbergError::Ocr { message, .. }) => {
            tracing::debug!("Expected OCR error for invalid language: {}", message);
            assert!(
                message.contains("language") || message.contains("lang") || message.contains("invalid"),
                "Error message should mention language issue: {}",
                message
            );
        }
        Err(e) => {
            tracing::debug!("Invalid language produced error: {}", e);
        }
        Ok(_) => {
            tracing::debug!("Invalid language was accepted (fallback behavior)");
        }
    }
}

#[test]
fn test_ocr_invalid_psm_mode() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                psm: 999,
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Err(KreuzbergError::Ocr { message, .. }) | Err(KreuzbergError::Validation { message, .. }) => {
            tracing::debug!("Expected error for invalid PSM: {}", message);
            assert!(
                message.contains("psm") || message.contains("segmentation") || message.contains("mode"),
                "Error message should mention PSM issue: {}",
                message
            );
        }
        Err(e) => {
            tracing::debug!("Invalid PSM produced error: {}", e);
        }
        Ok(result) => {
            tracing::debug!("Invalid PSM was accepted (fallback behavior)");
            assert_non_empty_content(&result);
        }
    }
}

#[test]
fn test_ocr_invalid_backend_name() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "nonexistent_ocr_backend_xyz".to_string(),
            language: "eng".to_string(),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(extraction_result) => {
            tracing::debug!("Invalid backend name ignored, fallback to Tesseract (expected behavior in Rust core)");
            assert_non_empty_content(&extraction_result);
        }
        Err(KreuzbergError::Ocr { message, .. }) => {
            tracing::debug!("OCR error for invalid backend: {}", message);
        }
        Err(KreuzbergError::MissingDependency(msg)) => {
            tracing::debug!("MissingDependency error for invalid backend: {}", msg);
        }
        Err(KreuzbergError::Validation { message, .. }) => {
            tracing::debug!("Validation error for invalid backend: {}", message);
        }
        Err(e) => {
            tracing::debug!("Invalid backend produced error: {}", e);
        }
    }
}

#[test]
fn test_ocr_corrupted_image_data() {
    let corrupted_data = vec![0xFF, 0xD8, 0xFF, 0xE0, 0x00, 0x10];
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            ..Default::default()
        }),
        force_ocr: true,
        ..Default::default()
    };

    let result = extract_bytes_sync(&corrupted_data, "image/jpeg", &config);

    match result {
        Err(KreuzbergError::ImageProcessing { message, .. })
        | Err(KreuzbergError::Parsing { message, .. })
        | Err(KreuzbergError::Ocr { message, .. }) => {
            tracing::debug!("Expected error for corrupted image: {}", message);
        }
        Err(e) => {
            tracing::debug!("Corrupted image produced error: {}", e);
        }
        Ok(_) => {
            tracing::debug!("Corrupted image was processed (partial success)");
        }
    }
}

#[test]
fn test_ocr_empty_image() {
    let empty_data = vec![];
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            ..Default::default()
        }),
        force_ocr: true,
        ..Default::default()
    };

    let result = extract_bytes_sync(&empty_data, "image/png", &config);

    assert!(result.is_err(), "Empty image data should produce an error");

    match result {
        Err(KreuzbergError::Validation { message, .. })
        | Err(KreuzbergError::Parsing { message, .. })
        | Err(KreuzbergError::ImageProcessing { message, .. }) => {
            tracing::debug!("Expected error for empty image: {}", message);
        }
        Err(e) => {
            tracing::debug!("Empty image produced error: {}", e);
        }
        Ok(_) => unreachable!(),
    }
}

#[test]
fn test_ocr_non_image_data() {
    let text_data = b"This is plain text, not an image";
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            ..Default::default()
        }),
        force_ocr: true,
        ..Default::default()
    };

    let result = extract_bytes_sync(text_data, "image/png", &config);

    match result {
        Err(KreuzbergError::Parsing { message, .. }) | Err(KreuzbergError::ImageProcessing { message, .. }) => {
            tracing::debug!("Expected error for non-image data: {}", message);
        }
        Err(e) => {
            tracing::debug!("Non-image data produced error: {}", e);
        }
        Ok(_) => {
            tracing::debug!("Non-image data was accepted");
        }
    }
}

#[test]
fn test_ocr_extreme_table_threshold() {
    if skip_if_missing("images/simple_table.png") {
        return;
    }

    let file_path = get_test_file_path("images/simple_table.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                enable_table_detection: true,
                table_min_confidence: 1.5,
                table_column_threshold: -50,
                table_row_threshold_ratio: 10.0,
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(extraction_result) => {
            tracing::debug!("Extreme table config was accepted (values may be clamped)");
            assert_non_empty_content(&extraction_result);
        }
        Err(KreuzbergError::Validation { message, .. }) => {
            tracing::debug!("Configuration validation caught extreme values: {}", message);
        }
        Err(e) => {
            tracing::debug!("Extreme table config produced error: {}", e);
        }
    }
}

#[test]
fn test_ocr_negative_psm() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                psm: -5,
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(_) => {
            tracing::debug!("Negative PSM was accepted (clamped or default used)");
        }
        Err(e) => {
            tracing::debug!("Negative PSM produced error: {}", e);
        }
    }
}

#[test]
fn test_ocr_empty_whitelist() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                tessedit_char_whitelist: "".to_string(),
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(extraction_result) => {
            tracing::debug!(
                "Empty whitelist accepted, content length: {}",
                extraction_result.content.len()
            );
        }
        Err(e) => {
            tracing::debug!("Empty whitelist produced error: {}", e);
        }
    }
}

#[test]
fn test_ocr_conflicting_whitelist_blacklist() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                tessedit_char_whitelist: "abc".to_string(),
                tessedit_char_blacklist: "abc".to_string(),
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(extraction_result) => {
            tracing::debug!(
                "Conflicting whitelist/blacklist accepted: {}",
                extraction_result.content.len()
            );
        }
        Err(e) => {
            tracing::debug!("Conflicting config produced error: {}", e);
        }
    }
}

#[test]
fn test_ocr_empty_language() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "".to_string(),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(_) => {
            tracing::debug!("Empty language accepted (fallback to default)");
        }
        Err(KreuzbergError::Validation { message, .. }) | Err(KreuzbergError::Ocr { message, .. }) => {
            tracing::debug!("Empty language rejected: {}", message);
        }
        Err(e) => {
            tracing::debug!("Empty language produced error: {}", e);
        }
    }
}

#[test]
fn test_ocr_malformed_multi_language() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng++deu++fra".to_string(),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(_) => {
            tracing::debug!("Malformed multi-language accepted (parser tolerant)");
        }
        Err(e) => {
            tracing::debug!("Malformed language string produced error: {}", e);
        }
    }
}

#[test]
fn test_ocr_cache_disabled_then_enabled() {
    if skip_if_missing("images/ocr_image.jpg") {
        return;
    }

    let file_path = get_test_file_path("images/ocr_image.jpg");

    let config_no_cache = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                use_cache: false,
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        use_cache: false,
        ..Default::default()
    };

    let result1 = extract_file_sync(&file_path, None, &config_no_cache);
    if matches!(result1, Err(KreuzbergError::MissingDependency(_))) {
        return;
    }
    assert!(result1.is_ok(), "First extraction should succeed");

    let config_with_cache = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                use_cache: true,
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        use_cache: true,
        ..Default::default()
    };

    let result2 = extract_file_sync(&file_path, None, &config_with_cache);
    if matches!(result2, Err(KreuzbergError::MissingDependency(_))) {
        return;
    }
    assert!(result2.is_ok(), "Second extraction should succeed");

    assert_non_empty_content(&result1.expect("Operation failed"));
    assert_non_empty_content(&result2.expect("Operation failed"));
}

#[test]
fn test_ocr_concurrent_same_file() {
    if skip_if_missing("images/ocr_image.jpg") {
        return;
    }

    use std::sync::Arc;
    use std::thread;

    let file_path = Arc::new(get_test_file_path("images/ocr_image.jpg"));
    let config = Arc::new(ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            ..Default::default()
        }),
        force_ocr: false,
        use_cache: true,
        ..Default::default()
    });

    if matches!(
        extract_file_sync(&*file_path, None, &config),
        Err(KreuzbergError::MissingDependency(_))
    ) {
        return;
    }

    let mut handles = vec![];
    for i in 0..5 {
        let file_path_clone = Arc::clone(&file_path);
        let config_clone = Arc::clone(&config);

        let handle = thread::spawn(move || {
            let result = extract_file_sync(&*file_path_clone, None, &config_clone);
            let success = result.is_ok();
            match result {
                Ok(extraction_result) => {
                    tracing::debug!("Thread {} succeeded", i);
                    assert_non_empty_content(&extraction_result);
                }
                Err(e) => {
                    tracing::debug!("Thread {} failed: {}", i, e);
                }
            }
            success
        });

        handles.push(handle);
    }

    let successes: usize = handles
        .into_iter()
        .map(|h| if h.join().expect("Iterator failed") { 1 } else { 0 })
        .sum();

    tracing::debug!("Concurrent processing: {}/5 threads succeeded", successes);

    assert!(
        successes >= 1,
        "At least one concurrent thread should succeed (got {})",
        successes
    );
}

#[test]
fn test_ocr_concurrent_different_files() {
    if skip_if_missing("images/ocr_image.jpg") || skip_if_missing("images/test_hello_world.png") {
        return;
    }

    use std::sync::Arc;
    use std::thread;

    let files = Arc::new(vec![
        get_test_file_path("images/ocr_image.jpg"),
        get_test_file_path("images/test_hello_world.png"),
    ]);

    let config = Arc::new(ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            ..Default::default()
        }),
        force_ocr: false,
        use_cache: true,
        ..Default::default()
    });

    if matches!(
        extract_file_sync(&files[0], None, &config),
        Err(KreuzbergError::MissingDependency(_))
    ) {
        return;
    }

    let mut handles = vec![];
    for (i, file_path) in files.iter().enumerate() {
        let file_path_clone = file_path.clone();
        let config_clone = Arc::clone(&config);

        let handle = thread::spawn(move || {
            let result = extract_file_sync(&file_path_clone, None, &config_clone);
            match result {
                Ok(extraction_result) => {
                    tracing::debug!("File {} extraction succeeded", i);
                    assert_non_empty_content(&extraction_result);
                    true
                }
                Err(e) => {
                    tracing::debug!("File {} extraction failed: {}", i, e);
                    false
                }
            }
        });

        handles.push(handle);
    }

    let successes: usize = handles
        .into_iter()
        .map(|h| if h.join().expect("Iterator failed") { 1 } else { 0 })
        .sum();

    assert_eq!(
        successes, 2,
        "All concurrent threads should succeed with different files"
    );
}

#[test]
fn test_ocr_with_preprocessing_extreme_dpi() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    use kreuzberg::types::ImagePreprocessingConfig;

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                preprocessing: Some(ImagePreprocessingConfig {
                    target_dpi: 10000,
                    auto_rotate: true,
                    deskew: true,
                    denoise: false,
                    contrast_enhance: false,
                    binarization_method: "otsu".to_string(),
                    invert_colors: false,
                }),
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(extraction_result) => {
            tracing::debug!("Extreme DPI accepted (clamped): {}", extraction_result.content.len());
        }
        Err(KreuzbergError::ImageProcessing { message, .. }) | Err(KreuzbergError::Validation { message, .. }) => {
            tracing::debug!("Extreme DPI rejected: {}", message);
        }
        Err(e) => {
            tracing::debug!("Extreme DPI produced error: {}", e);
        }
    }
}

#[test]
fn test_ocr_with_invalid_binarization_method() {
    if skip_if_missing("images/test_hello_world.png") {
        return;
    }

    use kreuzberg::types::ImagePreprocessingConfig;

    let file_path = get_test_file_path("images/test_hello_world.png");
    let config = ExtractionConfig {
        ocr: Some(OcrConfig {
            backend: "tesseract".to_string(),
            language: "eng".to_string(),
            tesseract_config: Some(TesseractConfig {
                preprocessing: Some(ImagePreprocessingConfig {
                    target_dpi: 300,
                    auto_rotate: true,
                    deskew: true,
                    denoise: false,
                    contrast_enhance: false,
                    binarization_method: "invalid_method_xyz".to_string(),
                    invert_colors: false,
                }),
                ..Default::default()
            }),
            ..Default::default()
        }),
        force_ocr: false,
        ..Default::default()
    };

    let result = extract_file_sync(&file_path, None, &config);

    match result {
        Ok(_) => {
            tracing::debug!("Invalid binarization method accepted (fallback used)");
        }
        Err(KreuzbergError::Validation { message, .. }) | Err(KreuzbergError::ImageProcessing { message, .. }) => {
            tracing::debug!("Invalid binarization method rejected: {}", message);
        }
        Err(e) => {
            tracing::debug!("Invalid binarization method produced error: {}", e);
        }
    }
}