ruvector-scipix 2.0.4

Rust OCR engine for scientific documents - extract LaTeX, MathML from math equations, research papers, and technical diagrams with ONNX GPU acceleration
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
//! Complete preprocessing pipeline with builder pattern and parallel processing

use super::Result;
use crate::preprocess::{deskew, enhancement, rotation, transforms};
use image::{DynamicImage, GrayImage};
use rayon::prelude::*;
use std::sync::Arc;

/// Progress callback type
pub type ProgressCallback = Arc<dyn Fn(&str, f32) + Send + Sync>;

/// Complete preprocessing pipeline with configurable steps
pub struct PreprocessPipeline {
    auto_rotate: bool,
    auto_deskew: bool,
    enhance_contrast: bool,
    denoise: bool,
    blur_sigma: f32,
    clahe_clip_limit: f32,
    clahe_tile_size: u32,
    threshold: Option<u8>,
    adaptive_threshold: bool,
    adaptive_window_size: u32,
    target_width: Option<u32>,
    target_height: Option<u32>,
    progress_callback: Option<ProgressCallback>,
}

/// Builder for preprocessing pipeline
pub struct PreprocessPipelineBuilder {
    auto_rotate: bool,
    auto_deskew: bool,
    enhance_contrast: bool,
    denoise: bool,
    blur_sigma: f32,
    clahe_clip_limit: f32,
    clahe_tile_size: u32,
    threshold: Option<u8>,
    adaptive_threshold: bool,
    adaptive_window_size: u32,
    target_width: Option<u32>,
    target_height: Option<u32>,
    progress_callback: Option<ProgressCallback>,
}

impl Default for PreprocessPipelineBuilder {
    fn default() -> Self {
        Self {
            auto_rotate: true,
            auto_deskew: true,
            enhance_contrast: true,
            denoise: true,
            blur_sigma: 1.0,
            clahe_clip_limit: 2.0,
            clahe_tile_size: 8,
            threshold: None,
            adaptive_threshold: true,
            adaptive_window_size: 15,
            target_width: None,
            target_height: None,
            progress_callback: None,
        }
    }
}

impl PreprocessPipelineBuilder {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn auto_rotate(mut self, enable: bool) -> Self {
        self.auto_rotate = enable;
        self
    }

    pub fn auto_deskew(mut self, enable: bool) -> Self {
        self.auto_deskew = enable;
        self
    }

    pub fn enhance_contrast(mut self, enable: bool) -> Self {
        self.enhance_contrast = enable;
        self
    }

    pub fn denoise(mut self, enable: bool) -> Self {
        self.denoise = enable;
        self
    }

    pub fn blur_sigma(mut self, sigma: f32) -> Self {
        self.blur_sigma = sigma;
        self
    }

    pub fn clahe_clip_limit(mut self, limit: f32) -> Self {
        self.clahe_clip_limit = limit;
        self
    }

    pub fn clahe_tile_size(mut self, size: u32) -> Self {
        self.clahe_tile_size = size;
        self
    }

    pub fn threshold(mut self, threshold: Option<u8>) -> Self {
        self.threshold = threshold;
        self
    }

    pub fn adaptive_threshold(mut self, enable: bool) -> Self {
        self.adaptive_threshold = enable;
        self
    }

    pub fn adaptive_window_size(mut self, size: u32) -> Self {
        self.adaptive_window_size = size;
        self
    }

    pub fn target_size(mut self, width: Option<u32>, height: Option<u32>) -> Self {
        self.target_width = width;
        self.target_height = height;
        self
    }

    pub fn progress_callback<F>(mut self, callback: F) -> Self
    where
        F: Fn(&str, f32) + Send + Sync + 'static,
    {
        self.progress_callback = Some(Arc::new(callback));
        self
    }

    pub fn build(self) -> PreprocessPipeline {
        PreprocessPipeline {
            auto_rotate: self.auto_rotate,
            auto_deskew: self.auto_deskew,
            enhance_contrast: self.enhance_contrast,
            denoise: self.denoise,
            blur_sigma: self.blur_sigma,
            clahe_clip_limit: self.clahe_clip_limit,
            clahe_tile_size: self.clahe_tile_size,
            threshold: self.threshold,
            adaptive_threshold: self.adaptive_threshold,
            adaptive_window_size: self.adaptive_window_size,
            target_width: self.target_width,
            target_height: self.target_height,
            progress_callback: self.progress_callback,
        }
    }
}

impl PreprocessPipeline {
    /// Create a new pipeline builder
    pub fn builder() -> PreprocessPipelineBuilder {
        PreprocessPipelineBuilder::new()
    }

    /// Report progress if callback is set
    fn report_progress(&self, step: &str, progress: f32) {
        if let Some(callback) = &self.progress_callback {
            callback(step, progress);
        }
    }

    /// Process a single image through the complete pipeline
    ///
    /// # Pipeline steps:
    /// 1. Convert to grayscale
    /// 2. Detect and correct rotation (if enabled)
    /// 3. Detect and correct skew (if enabled)
    /// 4. Enhance contrast with CLAHE (if enabled)
    /// 5. Denoise with Gaussian blur (if enabled)
    /// 6. Apply thresholding (binary or adaptive)
    /// 7. Resize to target dimensions (if specified)
    pub fn process(&self, image: &DynamicImage) -> Result<GrayImage> {
        self.report_progress("Starting preprocessing", 0.0);

        // Step 1: Convert to grayscale
        self.report_progress("Converting to grayscale", 0.1);
        let mut gray = transforms::to_grayscale(image);

        // Step 2: Auto-rotate
        if self.auto_rotate {
            self.report_progress("Detecting rotation", 0.2);
            let angle = rotation::detect_rotation(&gray)?;

            if angle.abs() > 0.5 {
                self.report_progress("Correcting rotation", 0.25);
                gray = rotation::rotate_image(&gray, -angle)?;
            }
        }

        // Step 3: Auto-deskew
        if self.auto_deskew {
            self.report_progress("Detecting skew", 0.3);
            let angle = deskew::detect_skew_angle(&gray)?;

            if angle.abs() > 0.5 {
                self.report_progress("Correcting skew", 0.35);
                gray = deskew::deskew_image(&gray, angle)?;
            }
        }

        // Step 4: Enhance contrast
        if self.enhance_contrast {
            self.report_progress("Enhancing contrast", 0.5);
            gray = enhancement::clahe(&gray, self.clahe_clip_limit, self.clahe_tile_size)?;
        }

        // Step 5: Denoise
        if self.denoise {
            self.report_progress("Denoising", 0.6);
            gray = transforms::gaussian_blur(&gray, self.blur_sigma)?;
        }

        // Step 6: Thresholding
        self.report_progress("Applying threshold", 0.7);
        gray = if self.adaptive_threshold {
            transforms::adaptive_threshold(&gray, self.adaptive_window_size)?
        } else if let Some(threshold_val) = self.threshold {
            transforms::threshold(&gray, threshold_val)
        } else {
            // Auto Otsu threshold
            let threshold_val = transforms::otsu_threshold(&gray)?;
            transforms::threshold(&gray, threshold_val)
        };

        // Step 7: Resize
        if let (Some(width), Some(height)) = (self.target_width, self.target_height) {
            self.report_progress("Resizing", 0.9);
            gray = image::imageops::resize(
                &gray,
                width,
                height,
                image::imageops::FilterType::Lanczos3,
            );
        }

        self.report_progress("Preprocessing complete", 1.0);
        Ok(gray)
    }

    /// Process multiple images in parallel
    ///
    /// # Arguments
    /// * `images` - Vector of images to process
    ///
    /// # Returns
    /// Vector of preprocessed images in the same order
    pub fn process_batch(&self, images: Vec<DynamicImage>) -> Result<Vec<GrayImage>> {
        images
            .into_par_iter()
            .map(|img| self.process(&img))
            .collect()
    }

    /// Process image and return intermediate results from each step
    ///
    /// Useful for debugging and visualization
    pub fn process_with_intermediates(
        &self,
        image: &DynamicImage,
    ) -> Result<Vec<(String, GrayImage)>> {
        let mut results = Vec::new();

        // Step 1: Grayscale
        let mut gray = transforms::to_grayscale(image);
        results.push(("01_grayscale".to_string(), gray.clone()));

        // Step 2: Rotation
        if self.auto_rotate {
            let angle = rotation::detect_rotation(&gray)?;
            if angle.abs() > 0.5 {
                gray = rotation::rotate_image(&gray, -angle)?;
                results.push(("02_rotated".to_string(), gray.clone()));
            }
        }

        // Step 3: Deskew
        if self.auto_deskew {
            let angle = deskew::detect_skew_angle(&gray)?;
            if angle.abs() > 0.5 {
                gray = deskew::deskew_image(&gray, angle)?;
                results.push(("03_deskewed".to_string(), gray.clone()));
            }
        }

        // Step 4: Enhancement
        if self.enhance_contrast {
            gray = enhancement::clahe(&gray, self.clahe_clip_limit, self.clahe_tile_size)?;
            results.push(("04_enhanced".to_string(), gray.clone()));
        }

        // Step 5: Denoise
        if self.denoise {
            gray = transforms::gaussian_blur(&gray, self.blur_sigma)?;
            results.push(("05_denoised".to_string(), gray.clone()));
        }

        // Step 6: Threshold
        gray = if self.adaptive_threshold {
            transforms::adaptive_threshold(&gray, self.adaptive_window_size)?
        } else if let Some(threshold_val) = self.threshold {
            transforms::threshold(&gray, threshold_val)
        } else {
            let threshold_val = transforms::otsu_threshold(&gray)?;
            transforms::threshold(&gray, threshold_val)
        };
        results.push(("06_thresholded".to_string(), gray.clone()));

        // Step 7: Resize
        if let (Some(width), Some(height)) = (self.target_width, self.target_height) {
            gray = image::imageops::resize(
                &gray,
                width,
                height,
                image::imageops::FilterType::Lanczos3,
            );
            results.push(("07_resized".to_string(), gray.clone()));
        }

        Ok(results)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use image::{Rgb, RgbImage};

    fn create_test_image() -> DynamicImage {
        let mut img = RgbImage::new(100, 100);
        for y in 0..100 {
            for x in 0..100 {
                let val = ((x + y) / 2) as u8;
                img.put_pixel(x, y, Rgb([val, val, val]));
            }
        }
        DynamicImage::ImageRgb8(img)
    }

    #[test]
    fn test_pipeline_builder() {
        let pipeline = PreprocessPipeline::builder()
            .auto_rotate(false)
            .denoise(true)
            .blur_sigma(1.5)
            .build();

        assert!(!pipeline.auto_rotate);
        assert!(pipeline.denoise);
        assert!((pipeline.blur_sigma - 1.5).abs() < 0.001);
    }

    #[test]
    fn test_pipeline_process() {
        let img = create_test_image();
        let pipeline = PreprocessPipeline::builder()
            .auto_rotate(false)
            .auto_deskew(false)
            .build();

        let result = pipeline.process(&img);
        assert!(result.is_ok());

        let processed = result.unwrap();
        assert_eq!(processed.width(), 100);
        assert_eq!(processed.height(), 100);
    }

    #[test]
    fn test_pipeline_with_resize() {
        let img = create_test_image();
        let pipeline = PreprocessPipeline::builder()
            .target_size(Some(50), Some(50))
            .auto_rotate(false)
            .auto_deskew(false)
            .build();

        let result = pipeline.process(&img);
        assert!(result.is_ok());

        let processed = result.unwrap();
        assert_eq!(processed.width(), 50);
        assert_eq!(processed.height(), 50);
    }

    #[test]
    fn test_pipeline_batch_processing() {
        let images = vec![
            create_test_image(),
            create_test_image(),
            create_test_image(),
        ];

        let pipeline = PreprocessPipeline::builder()
            .auto_rotate(false)
            .auto_deskew(false)
            .build();

        let results = pipeline.process_batch(images);
        assert!(results.is_ok());

        let processed = results.unwrap();
        assert_eq!(processed.len(), 3);
    }

    #[test]
    fn test_pipeline_intermediates() {
        let img = create_test_image();
        let pipeline = PreprocessPipeline::builder()
            .auto_rotate(false)
            .auto_deskew(false)
            .enhance_contrast(true)
            .denoise(true)
            .build();

        let result = pipeline.process_with_intermediates(&img);
        assert!(result.is_ok());

        let intermediates = result.unwrap();
        assert!(!intermediates.is_empty());
        assert!(intermediates
            .iter()
            .any(|(name, _)| name.contains("grayscale")));
        assert!(intermediates
            .iter()
            .any(|(name, _)| name.contains("thresholded")));
    }

    #[test]
    fn test_progress_callback() {
        use std::sync::{Arc, Mutex};

        let progress_steps = Arc::new(Mutex::new(Vec::new()));
        let progress_clone = Arc::clone(&progress_steps);

        let pipeline = PreprocessPipeline::builder()
            .auto_rotate(false)
            .auto_deskew(false)
            .progress_callback(move |step, _progress| {
                progress_clone.lock().unwrap().push(step.to_string());
            })
            .build();

        let img = create_test_image();
        let _ = pipeline.process(&img);

        let steps = progress_steps.lock().unwrap();
        assert!(!steps.is_empty());
        assert!(steps.iter().any(|s| s.contains("Starting")));
        assert!(steps.iter().any(|s| s.contains("complete")));
    }
}