ocr 0.1.1

A pure Rust CLI OCR tool for printed text extraction
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
//! Text processing utilities for OCR API

use crate::api::error::{ApiError, ApiResult};
use crate::core::text::{BoundingBox, TextResult};
use serde::{Deserialize, Serialize};

/// Text processing operations
pub struct TextProcessor;

impl TextProcessor {
    /// Clean and normalize text
    pub fn clean_text(text: &str) -> String {
        text.trim()
            .lines()
            .map(|line| line.trim())
            .filter(|line| !line.is_empty())
            .collect::<Vec<_>>()
            .join("\n")
    }

    /// Extract text from result
    pub fn extract_text(result: &TextResult) -> String {
        result.text.clone()
    }

    /// Extract text with confidence filtering
    pub fn extract_text_with_confidence(result: &TextResult, min_confidence: f32) -> String {
        result
            .characters
            .iter()
            .filter(|c| c.confidence >= min_confidence)
            .map(|c| c.character)
            .collect()
    }

    /// Get text statistics
    pub fn get_text_statistics(result: &TextResult) -> TextStatistics {
        let character_count = result.characters.len();
        let word_count = result.words.len();
        let line_count = result.lines.len();

        let avg_character_confidence = if character_count > 0 {
            result.characters.iter().map(|c| c.confidence).sum::<f32>() / character_count as f32
        } else {
            0.0
        };

        let avg_word_confidence = if word_count > 0 {
            result.words.iter().map(|w| w.confidence).sum::<f32>() / word_count as f32
        } else {
            0.0
        };

        let avg_line_confidence = if line_count > 0 {
            result.lines.iter().map(|l| l.confidence).sum::<f32>() / line_count as f32
        } else {
            0.0
        };

        TextStatistics {
            character_count,
            word_count,
            line_count,
            avg_character_confidence,
            avg_word_confidence,
            avg_line_confidence,
            overall_confidence: result.confidence,
        }
    }

    /// Filter results by confidence
    pub fn filter_by_confidence(result: &TextResult, min_confidence: f32) -> TextResult {
        let mut filtered = result.clone();

        // Filter characters
        filtered
            .characters
            .retain(|c| c.confidence >= min_confidence);

        // Filter words
        filtered.words.retain(|w| w.confidence >= min_confidence);

        // Filter lines
        filtered.lines.retain(|l| l.confidence >= min_confidence);

        // Rebuild text from filtered characters if we have character-level results
        // Otherwise, preserve the original text if overall confidence meets threshold
        if !filtered.characters.is_empty() {
            filtered.text = filtered.characters.iter().map(|c| c.character).collect();
        } else if result.confidence < min_confidence {
            // If overall confidence is below threshold and no characters, clear text
            filtered.text = String::new();
        }
        // Otherwise, keep the original text (no character-level filtering needed)

        filtered
    }

    /// Merge multiple text results
    pub fn merge_results(results: &[TextResult]) -> TextResult {
        if results.is_empty() {
            return TextResult::new(String::new(), 0.0, BoundingBox::new(0, 0, 0, 0));
        }

        let mut merged = results[0].clone();

        for result in &results[1..] {
            merged.text.push_str(&result.text);
            merged.characters.extend(result.characters.clone());
            merged.words.extend(result.words.clone());
            merged.lines.extend(result.lines.clone());
        }

        // Recalculate confidence
        let total_confidence: f32 = results.iter().map(|r| r.confidence).sum();
        merged.confidence = total_confidence / results.len() as f32;

        merged
    }

    /// Split text into lines
    pub fn split_into_lines(text: &str) -> Vec<String> {
        text.lines()
            .map(|line| line.trim().to_string())
            .filter(|line| !line.is_empty())
            .collect()
    }

    /// Split text into words
    pub fn split_into_words(text: &str) -> Vec<String> {
        text.split_whitespace()
            .map(|word| word.trim().to_string())
            .filter(|word| !word.is_empty())
            .collect()
    }

    /// Calculate text similarity
    pub fn calculate_similarity(text1: &str, text2: &str) -> f32 {
        // Simple Levenshtein distance-based similarity
        let distance = Self::levenshtein_distance(text1, text2);
        let max_len = text1.len().max(text2.len());

        if max_len == 0 {
            1.0
        } else {
            1.0 - (distance as f32 / max_len as f32)
        }
    }

    /// Calculate Levenshtein distance
    fn levenshtein_distance(s1: &str, s2: &str) -> usize {
        let s1_chars: Vec<char> = s1.chars().collect();
        let s2_chars: Vec<char> = s2.chars().collect();
        let s1_len = s1_chars.len();
        let s2_len = s2_chars.len();

        if s1_len == 0 {
            return s2_len;
        }
        if s2_len == 0 {
            return s1_len;
        }

        let mut matrix = vec![vec![0; s2_len + 1]; s1_len + 1];

        for i in 0..=s1_len {
            matrix[i][0] = i;
        }

        for j in 0..=s2_len {
            matrix[0][j] = j;
        }

        for i in 1..=s1_len {
            for j in 1..=s2_len {
                let cost = if s1_chars[i - 1] == s2_chars[j - 1] {
                    0
                } else {
                    1
                };
                matrix[i][j] = (matrix[i - 1][j] + 1)
                    .min(matrix[i][j - 1] + 1)
                    .min(matrix[i - 1][j - 1] + cost);
            }
        }

        matrix[s1_len][s2_len]
    }
}

/// Text statistics
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextStatistics {
    /// Number of characters
    pub character_count: usize,
    /// Number of words
    pub word_count: usize,
    /// Number of lines
    pub line_count: usize,
    /// Average character confidence
    pub avg_character_confidence: f32,
    /// Average word confidence
    pub avg_word_confidence: f32,
    /// Average line confidence
    pub avg_line_confidence: f32,
    /// Overall confidence
    pub overall_confidence: f32,
}

/// Text post-processing pipeline
pub struct TextPostProcessor {
    /// Post-processing configuration
    config: TextPostProcessingConfig,
}

/// Text post-processing configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TextPostProcessingConfig {
    /// Enable spell checking
    pub enable_spell_checking: bool,
    /// Enable grammar correction
    pub enable_grammar_correction: bool,
    /// Enable punctuation correction
    pub enable_punctuation_correction: bool,
    /// Enable case correction
    pub enable_case_correction: bool,
    /// Minimum confidence threshold
    pub min_confidence_threshold: f32,
    /// Language for corrections
    pub language: String,
}

impl Default for TextPostProcessingConfig {
    fn default() -> Self {
        Self {
            enable_spell_checking: true,
            enable_grammar_correction: false,
            enable_punctuation_correction: true,
            enable_case_correction: true,
            min_confidence_threshold: 0.5,
            language: "en".to_string(),
        }
    }
}

impl TextPostProcessor {
    /// Create a new text post-processor
    pub fn new(config: TextPostProcessingConfig) -> Self {
        Self { config }
    }

    /// Process text result
    pub fn process(&self, result: &TextResult) -> ApiResult<TextResult> {
        let mut processed = result.clone();

        // Filter by confidence
        if self.config.min_confidence_threshold > 0.0 {
            processed = TextProcessor::filter_by_confidence(
                &processed,
                self.config.min_confidence_threshold,
            );
        }

        // Apply spell checking
        if self.config.enable_spell_checking {
            processed = self.apply_spell_checking(processed)?;
        }

        // Apply grammar correction
        if self.config.enable_grammar_correction {
            processed = self.apply_grammar_correction(processed)?;
        }

        // Apply punctuation correction
        if self.config.enable_punctuation_correction {
            processed = self.apply_punctuation_correction(processed)?;
        }

        // Apply case correction
        if self.config.enable_case_correction {
            processed = self.apply_case_correction(processed)?;
        }

        Ok(processed)
    }

    /// Apply spell checking
    fn apply_spell_checking(&self, result: TextResult) -> ApiResult<TextResult> {
        // TODO: Implement spell checking
        // This would typically use a dictionary or spell checking library
        Ok(result)
    }

    /// Apply grammar correction
    fn apply_grammar_correction(&self, result: TextResult) -> ApiResult<TextResult> {
        // TODO: Implement grammar correction
        // This would typically use a grammar checking library
        Ok(result)
    }

    /// Apply punctuation correction
    fn apply_punctuation_correction(&self, mut result: TextResult) -> ApiResult<TextResult> {
        // Basic punctuation correction
        result.text = result
            .text
            .replace("  ", " ") // Remove double spaces
            .replace(" .", ".") // Fix space before period
            .replace(" ,", ",") // Fix space before comma
            .replace(" !", "!") // Fix space before exclamation
            .replace(" ?", "?") // Fix space before question mark
            .replace(" :", ":") // Fix space before colon
            .replace(" ;", ";"); // Fix space before semicolon

        Ok(result)
    }

    /// Apply case correction
    fn apply_case_correction(&self, mut result: TextResult) -> ApiResult<TextResult> {
        // Basic case correction
        let words: Vec<&str> = result.text.split_whitespace().collect();
        let corrected_words: Vec<String> = words
            .iter()
            .enumerate()
            .map(|(i, word)| {
                if i == 0 {
                    // Capitalize first word
                    Self::capitalize_first_letter(word)
                } else if word.ends_with('.') || word.ends_with('!') || word.ends_with('?') {
                    // Capitalize after sentence endings
                    Self::capitalize_first_letter(word)
                } else {
                    word.to_string()
                }
            })
            .collect();

        result.text = corrected_words.join(" ");
        Ok(result)
    }

    /// Capitalize first letter of a word
    fn capitalize_first_letter(word: &str) -> String {
        if word.is_empty() {
            return String::new();
        }

        let mut chars: Vec<char> = word.chars().collect();
        if let Some(first_char) = chars.first_mut() {
            *first_char = first_char.to_uppercase().next().unwrap_or(*first_char);
        }
        chars.into_iter().collect()
    }
}

/// Text export formats
pub enum TextExportFormat {
    /// Plain text
    PlainText,
    /// JSON
    Json,
    /// XML
    Xml,
    /// CSV
    Csv,
    /// Markdown
    Markdown,
}

/// Text exporter
pub struct TextExporter;

impl TextExporter {
    /// Export text result to string
    pub fn export_to_string(result: &TextResult, format: TextExportFormat) -> ApiResult<String> {
        match format {
            TextExportFormat::PlainText => Ok(result.text.clone()),
            TextExportFormat::Json => {
                serde_json::to_string_pretty(result).map_err(|e| ApiError::Serialization(e))
            }
            TextExportFormat::Xml => Self::export_to_xml(result),
            TextExportFormat::Csv => Self::export_to_csv(result),
            TextExportFormat::Markdown => Self::export_to_markdown(result),
        }
    }

    /// Export to XML
    fn export_to_xml(result: &TextResult) -> ApiResult<String> {
        let mut xml = String::new();
        xml.push_str("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        xml.push_str("<ocr_result>\n");
        xml.push_str(&format!(
            "  <text>{}</text>\n",
            Self::escape_xml(&result.text)
        ));
        xml.push_str(&format!(
            "  <confidence>{}</confidence>\n",
            result.confidence
        ));
        xml.push_str("</ocr_result>\n");
        Ok(xml)
    }

    /// Export to CSV
    fn export_to_csv(result: &TextResult) -> ApiResult<String> {
        let mut csv = String::new();
        csv.push_str("text,confidence,character_count,word_count,line_count\n");
        csv.push_str(&format!(
            "{},{},{},{},{}\n",
            Self::escape_csv(&result.text),
            result.confidence,
            result.characters.len(),
            result.words.len(),
            result.lines.len()
        ));
        Ok(csv)
    }

    /// Export to Markdown
    fn export_to_markdown(result: &TextResult) -> ApiResult<String> {
        let mut md = String::new();
        md.push_str("# OCR Result\n\n");
        md.push_str(&format!(
            "**Confidence:** {:.2}%\n\n",
            result.confidence * 100.0
        ));
        md.push_str(&format!("**Text:**\n\n{}\n\n", result.text));
        md.push_str(&format!("**Statistics:**\n"));
        md.push_str(&format!("- Characters: {}\n", result.characters.len()));
        md.push_str(&format!("- Words: {}\n", result.words.len()));
        md.push_str(&format!("- Lines: {}\n", result.lines.len()));
        Ok(md)
    }

    /// Escape XML special characters
    fn escape_xml(text: &str) -> String {
        text.replace('&', "&amp;")
            .replace('<', "&lt;")
            .replace('>', "&gt;")
            .replace('"', "&quot;")
            .replace('\'', "&apos;")
    }

    /// Escape CSV special characters
    fn escape_csv(text: &str) -> String {
        if text.contains(',') || text.contains('"') || text.contains('\n') {
            format!("\"{}\"", text.replace('"', "\"\""))
        } else {
            text.to_string()
        }
    }
}