rusto-rs 0.2.3

RustO! - Pure Rust OCR library based on RapidOCR with PaddleOCR engine
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
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

#[cfg(feature = "use-opencv")]
use opencv::{
    core::{Mat, Point2f},
    prelude::MatTraitConst,
};

#[cfg(not(feature = "use-opencv"))]
use crate::image_impl::{Mat, Point2f};

use crate::cal_rec_boxes::CalRecBoxes;
use crate::config::InitializeConfig;
use crate::det::TextDetector;
use crate::engine::EngineError;
use crate::geometry::{
    apply_vertical_padding, get_rotate_crop_image, map_boxes_to_original,
    resize_image_within_bounds, OpRecord,
};
use crate::orient::{OrientClassifier, Orientation};
use crate::rec::{TextRecOutput, TextRecognizer};
use crate::types::GlobalConfig;

#[derive(Clone, Copy, Debug, Default, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum OutputGranularity {
    #[default]
    Lines,
    Words,
    Spatial,
}
#[derive(Clone, Debug, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OcrRunOptions {
    #[serde(default)]
    pub output: OutputGranularity,
    pub line_y_threshold: Option<f32>,
    pub word_x_threshold: Option<f32>,
    pub text_score: Option<f32>,
    pub classification: Option<bool>,
    pub orientation: Option<bool>,
}

/// Image input accepted by the canonical `RustO::detect_text` API.
#[derive(Clone, Debug)]
pub enum ImageSource {
    Path(PathBuf),
    Bytes(Vec<u8>),
}

/// Result returned by the canonical `RustO::detect_text` API.
#[derive(Clone, Debug, PartialEq)]
pub enum DetectTextResult {
    Structured(Vec<crate::TextResult>),
    Spatial(String),
}

#[allow(dead_code)]
pub(crate) struct RustOOutput {
    pub boxes: Vec<[Point2f; 4]>,
    pub txts: Vec<String>,
    pub scores: Vec<f32>,
    /// Aligned words for each recognized detection box. Each inner vector is
    /// one recognizer line; its element boundaries include explicit whitespace.
    pub word_results: Vec<Vec<(String, f32, [Point2f; 4])>>,
    pub orientation: Option<Orientation>,
    pub elapse_det: f64,
    pub elapse_rec: f64,
    pub elapse_orient: f64,
    /// Debug: Orientation-corrected image (if orientation was detected)
    pub debug_oriented_image: Option<Mat>,
    pub y_threshold_multiplier: Option<f32>,
    pub x_threshold_multiplier: Option<f32>,
}

pub struct RustO {
    pub det: TextDetector,
    pub rec: TextRecognizer,
    pub global: GlobalConfig,
    pub cal_rec_boxes: CalRecBoxes,
    pub orient: Option<OrientClassifier>,
    pub cls: Option<OrientClassifier>,
}

impl RustO {
    /// Initialize an OCR engine with static model/session configuration.
    pub fn initialize(config: InitializeConfig) -> Result<Self, EngineError> {
        let det = TextDetector::new(config.det.clone())?;
        let rec = TextRecognizer::new(config.rec.clone())?;
        let cal_rec_boxes = CalRecBoxes::new();

        // Initialize orient classifier if provided
        let orient = if let Some(orient_cfg) = config.orient {
            Some(OrientClassifier::new(orient_cfg)?)
        } else {
            None
        };

        // Initialize CLS (text line orientation) if provided
        let cls = if let Some(cls_cfg) = config.cls {
            // Convert ClsConfig to OrientConfig for reuse
            let orient_cfg = crate::types::OrientConfig {
                engine_type: cls_cfg.engine_type,
                model_type: cls_cfg.model_type,
                task_type: cls_cfg.task_type,
                model_path: cls_cfg.model_path,
                orient_image_shape: cls_cfg.cls_image_shape,
                mean: [0.5, 0.5, 0.5],
                std: [0.5, 0.5, 0.5],
                confidence_threshold: cls_cfg.cls_thresh,
                orient_batch_num: cls_cfg.cls_batch_num,
                orient_thresh: cls_cfg.cls_thresh,
                engine_cfg: cls_cfg.engine_cfg,
            };
            Some(OrientClassifier::new(orient_cfg)?)
        } else {
            None
        };

        Ok(Self {
            det,
            rec,
            global: config.global,
            cal_rec_boxes,
            orient,
            cls,
        })
    }

    /// Detect text from a file path or in-memory image bytes.
    ///
    /// `lines` and `words` produce structured results; `spatial` produces
    /// formatted spatial text. Request options never mutate this engine.
    pub fn detect_text(
        &mut self,
        source: &ImageSource,
        options: &OcrRunOptions,
    ) -> Result<DetectTextResult, EngineError> {
        let output = match source {
            ImageSource::Path(path) => self.run_with_options(path, options)?,
            ImageSource::Bytes(bytes) => {
                #[cfg(not(feature = "use-opencv"))]
                {
                    let image = image::load_from_memory(bytes)
                        .map_err(|error| EngineError::ImageError(error.to_string()))?;
                    self.run_on_mat_with_options(&Mat::new(image), options)?
                }
                #[cfg(feature = "use-opencv")]
                {
                    return Err(EngineError::ImageError(
                        "in-memory image sources require the pure Rust image backend".into(),
                    ));
                }
            }
        };
        match options.output {
            OutputGranularity::Spatial => Ok(DetectTextResult::Spatial(
                output.to_spatial_text(options.line_y_threshold, options.word_x_threshold),
            )),
            OutputGranularity::Lines | OutputGranularity::Words => Ok(
                DetectTextResult::Structured(output.to_text_results_with_options(options)),
            ),
        }
    }

    pub(crate) fn run_with_options<P: AsRef<Path>>(
        &mut self,
        image_path: P,
        options: &OcrRunOptions,
    ) -> Result<RustOOutput, EngineError> {
        use crate::image_impl::imread;
        let img = imread(image_path)?;
        self.run_on_mat_with_options(&img, options)
    }
    pub(crate) fn run_on_mat_with_options(
        &mut self,
        img: &Mat,
        options: &OcrRunOptions,
    ) -> Result<RustOOutput, EngineError> {
        let mut effective = self.global.clone();
        effective.return_word_box = options.output == OutputGranularity::Words;
        effective.return_single_char_box = false;
        effective.use_cls = options.classification.unwrap_or(false) && self.cls.is_some();
        effective.use_orient = options.orientation.unwrap_or(false) && self.orient.is_some();
        effective.use_unwarp = false;
        if let Some(value) = options.text_score {
            effective.text_score = value;
        }
        self.run_on_mat_with_global(img, &effective)
    }


    fn run_on_mat_with_global(
        &mut self,
        img: &Mat,
        global: &GlobalConfig,
    ) -> Result<RustOOutput, EngineError> {
        let size = img.size()?;
        let ori_h = size.height;
        let ori_w = size.width;

        let mut elapse_orient = 0.0;
        let mut orientation = None;
        let mut debug_oriented_image = None;

        // Step 1: Orientation classification and correction (if enabled)
        // Apply to ENTIRE image before detection
        let mut working_img = img.clone();
        if global.use_orient && self.orient.is_some() {
            if let Some(orient_classifier) = &mut self.orient {
                let orient_result = orient_classifier.classify(img)?;
                elapse_orient = orient_result.elapse;

                // Apply rotation for internal processing if orientation detected
                if orient_result.orientation.degrees() != 0 {
                    let rotated = orient_result.orientation.rotate_image(&working_img)?;
                    if global.debug_images {
                        debug_oriented_image = Some(rotated.clone());
                    }
                    working_img = rotated;

                    // Only report orientation if confidence meets threshold
                    if orient_result.confidence >= orient_classifier.config.confidence_threshold {
                        orientation = Some(orient_result.orientation);
                    }
                } else {
                    orientation = Some(orient_result.orientation);
                }
            }
        }

        let mut op_record: OpRecord = OpRecord::new();

        // Step 2: Global resize within bounds (use corrected image)
        let (resized, ratio_h, ratio_w) =
            resize_image_within_bounds(&working_img, global.min_side_len, global.max_side_len)?;
        let mut m = std::collections::BTreeMap::new();
        m.insert("ratio_h".to_string(), ratio_h);
        m.insert("ratio_w".to_string(), ratio_w);
        op_record.insert("preprocess".to_string(), m);

        // Vertical padding
        let (padded, op_record) = apply_vertical_padding(
            &resized,
            op_record,
            global.width_height_ratio,
            global.min_height,
        )?;

        // Detection (boxes are in padded-image coordinates here)
        // IMPORTANT: Pass padded image dimensions, not original!
        let det_res = self.det.run(&padded)?;
        let padded_boxes = match det_res.boxes {
            Some(b) if !b.is_empty() => b,
            _ => {
                return Ok(RustOOutput {
                    boxes: Vec::new(),
                    txts: Vec::new(),
                    scores: Vec::new(),
                    word_results: Vec::new(),
                    orientation,
                    elapse_det: det_res.elapse,
                    elapse_rec: 0.0,
                    elapse_orient,
                    debug_oriented_image,
                    y_threshold_multiplier: global.y_threshold_multiplier,
                    x_threshold_multiplier: global.x_threshold_multiplier,
                });
            }
        };

        // Step 4: Crop text regions from padded image
        let mut crop_imgs: Vec<Mat> = Vec::with_capacity(padded_boxes.len());
        for b in &padded_boxes {
            let crop = get_rotate_crop_image(&padded, b)?;
            crop_imgs.push(crop);
        }

        // Step 4.5: Text Line Orientation Classification (CLS) on cropped images
        // If enabled, classify each crop and rotate if needed (0 vs 180 degrees)
        if global.use_cls && self.cls.is_some() {
            if let Some(cls_classifier) = &mut self.cls {
                for crop in &mut crop_imgs {
                    if let Ok(cls_result) = cls_classifier.classify(crop) {
                        // Only rotate if orientation is 180 degrees and confidence is high
                        if cls_result.orientation == Orientation::Rotate180
                            && cls_result.confidence >= cls_classifier.config.confidence_threshold
                        {
                            // Rotate crop 180 degrees
                            if let Ok(rotated) = cls_result.orientation.rotate_image(crop) {
                                *crop = rotated;
                            }
                        }
                    }
                }
            }
        }

        // Map boxes back to original image coords for final output and word boxes
        let mut boxes = padded_boxes.clone();
        map_boxes_to_original(&mut boxes, &op_record, ori_h, ori_w);

        // Recognition
        let rec_res: TextRecOutput = self.rec.run(&crop_imgs, global.return_word_box)?;

        // Optional word boxes (computed before we move fields out of rec_res)
        let word_results_all: Vec<Vec<(String, f32, [Point2f; 4])>> = if global.return_word_box {
            self.cal_rec_boxes
                .calc_word_boxes(&boxes, &rec_res, global.return_single_char_box)
        } else {
            vec![Vec::new(); boxes.len()]
        };

        let mut txts = rec_res.txts;
        let mut scores = rec_res.scores;

        // Filter by text_score
        let mut f_boxes = Vec::new();
        let mut f_txts = Vec::new();
        let mut f_scores = Vec::new();
        let mut f_word_results: Vec<Vec<(String, f32, [Point2f; 4])>> = Vec::new();

        for (idx, (b, (t, s))) in boxes
            .into_iter()
            .zip(txts.drain(..).zip(scores.drain(..)))
            .enumerate()
        {
            if s < global.text_score {
                continue;
            }
            f_boxes.push(b);
            f_txts.push(t);
            f_scores.push(s);

            if idx < word_results_all.len() {
                f_word_results.push(word_results_all[idx].clone());
            } else {
                f_word_results.push(Vec::new());
            }
        }

        Ok(RustOOutput {
            boxes: f_boxes,
            txts: f_txts,
            scores: f_scores,
            word_results: f_word_results,
            orientation,
            elapse_det: det_res.elapse,
            elapse_rec: rec_res.elapse,
            elapse_orient,
            debug_oriented_image,
            y_threshold_multiplier: global.y_threshold_multiplier,
            x_threshold_multiplier: global.x_threshold_multiplier,
        })
    }

}

struct AlignedWord {
    result: crate::TextResult,
    /// Recognizer emitted whitespace before this entry. Spatial merging must
    /// never cross this boundary.
    whitespace_before: bool,
}

fn group_words(
    word_lines: Vec<Vec<crate::TextResult>>,
    line_y_threshold: f32,
    word_x_threshold: f32,
) -> Vec<crate::TextResult> {
    let mut words: Vec<AlignedWord> = word_lines
        .into_iter()
        .flat_map(|line| {
            line.into_iter()
                .enumerate()
                .map(|(index, result)| AlignedWord {
                    result,
                    whitespace_before: index > 0,
                })
        })
        .collect();
    if words.is_empty() {
        return Vec::new();
    }
    let mut heights: Vec<f32> = words.iter().map(|word| word.result.frame.height).collect();
    heights.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
    let line_tolerance = heights[heights.len() / 2] * line_y_threshold;
    words.sort_by(|a, b| {
        a.result
            .frame
            .top
            .partial_cmp(&b.result.frame.top)
            .unwrap_or(std::cmp::Ordering::Equal)
            .then(
                a.result
                    .frame
                    .left
                    .partial_cmp(&b.result.frame.left)
                    .unwrap_or(std::cmp::Ordering::Equal),
            )
    });
    let mut lines: Vec<Vec<AlignedWord>> = Vec::new();
    for word in words {
        if let Some(line) = lines.last_mut() {
            let center = line
                .iter()
                .map(|item| item.result.frame.top + item.result.frame.height / 2.0)
                .sum::<f32>()
                / line.len() as f32;
            if ((word.result.frame.top + word.result.frame.height / 2.0) - center).abs()
                <= line_tolerance
            {
                line.push(word);
                continue;
            }
        }
        lines.push(vec![word]);
    }
    lines
        .into_iter()
        .flat_map(|mut line| {
            line.sort_by(|a, b| {
                a.result
                    .frame
                    .left
                    .partial_cmp(&b.result.frame.left)
                    .unwrap_or(std::cmp::Ordering::Equal)
            });
            let mut grouped: Vec<Vec<crate::TextResult>> = Vec::new();
            for word in line {
                let char_width = (word.result.frame.width
                    / word.result.text.chars().count().max(1) as f32)
                    .max(1e-6);
                if !word.whitespace_before {
                    if let Some(current) = grouped.last_mut() {
                        let previous = current.last().expect("non-empty word group");
                        let gap =
                            word.result.frame.left - (previous.frame.left + previous.frame.width);
                        if gap <= char_width * word_x_threshold {
                            current.push(word.result);
                            continue;
                        }
                    }
                }
                grouped.push(vec![word.result]);
            }
            grouped
                .into_iter()
                .map(|group| merge_text_results(group, ""))
        })
        .collect()
}

fn merge_text_results(mut entries: Vec<crate::TextResult>, separator: &str) -> crate::TextResult {
    entries.sort_by(|a, b| {
        a.frame
            .left
            .partial_cmp(&b.frame.left)
            .unwrap_or(std::cmp::Ordering::Equal)
    });
    let text = entries
        .iter()
        .map(|item| item.text.as_str())
        .collect::<Vec<_>>()
        .join(separator);
    let score = entries.iter().map(|item| item.score).fold(1.0, f32::min);
    let left = entries
        .iter()
        .map(|item| item.frame.left)
        .fold(f32::INFINITY, f32::min);
    let top = entries
        .iter()
        .map(|item| item.frame.top)
        .fold(f32::INFINITY, f32::min);
    let right = entries
        .iter()
        .map(|item| item.frame.left + item.frame.width)
        .fold(f32::NEG_INFINITY, f32::max);
    let bottom = entries
        .iter()
        .map(|item| item.frame.top + item.frame.height)
        .fold(f32::NEG_INFINITY, f32::max);
    let box_points = [(left, top), (right, top), (right, bottom), (left, bottom)];
    crate::TextResult {
        text,
        score,
        box_points,
        frame: crate::Frame::from_points(&box_points),
    }
}

#[allow(dead_code)]
impl RustOOutput {
    /// Convert output into a list of TextResult with bounding box and frame
    pub(crate) fn to_text_results(&self) -> Vec<crate::TextResult> {
        let mut results = Vec::with_capacity(self.boxes.len());
        for (i, bbox) in self.boxes.iter().enumerate() {
            if i >= self.txts.len() || i >= self.scores.len() {
                break;
            }
            let box_points = [
                (bbox[0].x, bbox[0].y),
                (bbox[1].x, bbox[1].y),
                (bbox[2].x, bbox[2].y),
                (bbox[3].x, bbox[3].y),
            ];
            let frame = crate::Frame::from_points(&box_points);
            results.push(crate::TextResult {
                text: self.txts[i].clone(),
                score: self.scores[i],
                box_points,
                frame,
            });
        }
        results
    }

    pub(crate) fn to_text_results_with_options(&self, options: &OcrRunOptions) -> Vec<crate::TextResult> {
        if options.output == OutputGranularity::Words {
            let word_lines: Vec<Vec<crate::TextResult>> = self
                .word_results
                .iter()
                .map(|words| {
                    words
                        .iter()
                        .map(|(text, score, quad)| {
                            let box_points = [
                                (quad[0].x, quad[0].y),
                                (quad[1].x, quad[1].y),
                                (quad[2].x, quad[2].y),
                                (quad[3].x, quad[3].y),
                            ];
                            crate::TextResult {
                                text: text.clone(),
                                score: *score,
                                box_points,
                                frame: crate::Frame::from_points(&box_points),
                            }
                        })
                        .collect()
                })
                .collect();
            return group_words(
                word_lines,
                options.line_y_threshold.unwrap_or(0.5),
                options.word_x_threshold.unwrap_or(0.4),
            );
        }
        let mut entries = self.to_text_results();
        if entries.is_empty() {
            return entries;
        }
        let mut heights: Vec<f32> = entries.iter().map(|entry| entry.frame.height).collect();
        heights.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
        let tolerance = heights[heights.len() / 2] * options.line_y_threshold.unwrap_or(0.5);
        entries.sort_by(|a, b| {
            a.frame
                .top
                .partial_cmp(&b.frame.top)
                .unwrap_or(std::cmp::Ordering::Equal)
                .then(
                    a.frame
                        .left
                        .partial_cmp(&b.frame.left)
                        .unwrap_or(std::cmp::Ordering::Equal),
                )
        });
        let mut lines: Vec<Vec<crate::TextResult>> = Vec::new();
        for entry in entries {
            if let Some(line) = lines.last_mut() {
                let y = line
                    .iter()
                    .map(|item| item.frame.top + item.frame.height / 2.0)
                    .sum::<f32>()
                    / line.len() as f32;
                if ((entry.frame.top + entry.frame.height / 2.0) - y).abs() <= tolerance {
                    line.push(entry);
                    continue;
                }
            }
            lines.push(vec![entry]);
        }
        lines
            .into_iter()
            .map(|mut line| {
                line.sort_by(|a, b| {
                    a.frame
                        .left
                        .partial_cmp(&b.frame.left)
                        .unwrap_or(std::cmp::Ordering::Equal)
                });
                let text = line
                    .iter()
                    .map(|item| item.text.as_str())
                    .collect::<Vec<_>>()
                    .join(" ");
                let score = line.iter().map(|item| item.score).fold(1.0, f32::min);
                let left = line
                    .iter()
                    .map(|item| item.frame.left)
                    .fold(f32::INFINITY, f32::min);
                let top = line
                    .iter()
                    .map(|item| item.frame.top)
                    .fold(f32::INFINITY, f32::min);
                let right = line
                    .iter()
                    .map(|item| item.frame.left + item.frame.width)
                    .fold(f32::NEG_INFINITY, f32::max);
                let bottom = line
                    .iter()
                    .map(|item| item.frame.top + item.frame.height)
                    .fold(f32::NEG_INFINITY, f32::max);
                let box_points = [(left, top), (right, top), (right, bottom), (left, bottom)];
                crate::TextResult {
                    text,
                    score,
                    box_points,
                    frame: crate::Frame::from_points(&box_points),
                }
            })
            .collect()
    }

    /// Export raw OCR results as ASCII format
    /// Format: [x,y] confidence% text
    /// X,Y are from top-left point of bounding box
    /// Sorted by Y position first, then X position (follows raw_to_csv.py)
    pub(crate) fn to_raw(&self) -> String {
        if self.boxes.is_empty() {
            return String::new();
        }

        // Collect all entries with coordinates
        let mut entries: Vec<(f32, f32, String, f32)> = self
            .boxes
            .iter()
            .zip(self.txts.iter())
            .zip(self.scores.iter())
            .map(|((bbox, text), &score)| {
                let x = bbox[0].x;
                let y = bbox[0].y;
                (y, x, text.clone(), score)
            })
            .collect();

        // Sort by Y first, then by X (like raw_to_csv.py)
        entries.sort_by(|a, b| {
            a.0.partial_cmp(&b.0)
                .unwrap()
                .then(a.1.partial_cmp(&b.1).unwrap())
        });

        let mut result = String::new();
        for (y, x, text, score) in entries {
            result.push_str(&format!(
                "[{:.0},{:.0}] {:.2}% {}\n",
                x,
                y,
                score * 100.0,
                text
            ));
        }
        result
    }

    /// Export OCR results as CSV format
    /// Format: line_id,column_id,text
    /// Groups text by Y position into lines, then by X gaps into columns
    pub(crate) fn to_csv(&self) -> String {
        if self.boxes.is_empty() {
            return "line_id,column_id,text\n".to_string();
        }

        #[derive(Debug, Clone)]
        struct Token {
            x: f32,
            y: f32,
            text: String,
        }

        // Create tokens from boxes (use top-left point)
        let mut tokens: Vec<Token> = self
            .boxes
            .iter()
            .zip(self.txts.iter())
            .map(|(bbox, text)| Token {
                x: bbox[0].x,
                y: bbox[0].y,
                text: text.clone(),
            })
            .collect();

        // Sort by Y first
        tokens.sort_by(|a, b| a.y.partial_cmp(&b.y).unwrap());

        // Calculate typical Y diff for line grouping
        let y_diffs: Vec<f32> = tokens
            .windows(2)
            .map(|w| w[1].y - w[0].y)
            .filter(|&d| d > 0.0)
            .collect();
        let typical_y_diff = if !y_diffs.is_empty() {
            let mut sorted = y_diffs.clone();
            sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
            sorted[sorted.len() / 2]
        } else {
            10.0
        };
        let y_tolerance = typical_y_diff * 0.6;

        // Group into lines
        let mut lines: Vec<Vec<Token>> = Vec::new();
        let mut current_line: Vec<Token> = Vec::new();
        let mut current_y: Option<f32> = None;

        for token in tokens {
            if let Some(cy) = current_y {
                if (token.y - cy).abs() <= y_tolerance {
                    current_line.push(token.clone());
                    current_y = Some(
                        (cy * (current_line.len() - 1) as f32 + token.y)
                            / current_line.len() as f32,
                    );
                } else {
                    lines.push(current_line.clone());
                    current_line = vec![token.clone()];
                    current_y = Some(token.y);
                }
            } else {
                current_line = vec![token.clone()];
                current_y = Some(token.y);
            }
        }
        if !current_line.is_empty() {
            lines.push(current_line);
        }

        // Sort each line by X and segment into columns
        let mut csv_rows = Vec::new();
        for (line_id, mut line) in lines.into_iter().enumerate() {
            line.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap());

            if line.len() == 1 {
                csv_rows.push((line_id, 0, line[0].text.clone()));
                continue;
            }

            // Calculate X gaps for column segmentation
            let x_gaps: Vec<f32> = line.windows(2).map(|w| w[1].x - w[0].x).collect();
            let median_gap = if !x_gaps.is_empty() {
                let mut sorted = x_gaps.clone();
                sorted.sort_by(|a, b| a.partial_cmp(b).unwrap());
                sorted[sorted.len() / 2].max(1.0)
            } else {
                1.0
            };
            let gap_threshold = median_gap * 1.3;

            // Segment into columns
            let mut columns: Vec<Vec<Token>> = Vec::new();
            let mut current_col = vec![line[0].clone()];
            for i in 1..line.len() {
                let gap = line[i].x - line[i - 1].x;
                if gap > gap_threshold {
                    columns.push(current_col.clone());
                    current_col = vec![line[i].clone()];
                } else {
                    current_col.push(line[i].clone());
                }
            }
            columns.push(current_col);

            // Add to CSV rows
            for (col_id, col) in columns.into_iter().enumerate() {
                let text = col
                    .iter()
                    .map(|t| t.text.as_str())
                    .collect::<Vec<_>>()
                    .join(" ");
                csv_rows.push((line_id, col_id, text));
            }
        }

        // Format as CSV
        let mut result = String::from("line_id,column_id,text\n");
        for (line_id, col_id, text) in csv_rows {
            let safe_text = text.replace('"', "\"\"");
            result.push_str(&format!("{},{},\"{}\"\n", line_id, col_id, safe_text));
        }
        result
    }

    /// Export results as plain text with position info
    pub(crate) fn to_text_with_position(&self) -> String {
        let mut result = String::new();

        // Sort by position
        let mut indexed: Vec<(&[Point2f; 4], &String, f32)> = self
            .boxes
            .iter()
            .zip(self.txts.iter())
            .zip(self.scores.iter())
            .map(|((b, t), &s)| (b, t, s))
            .collect();

        indexed.sort_by(|a, b| {
            let ay = (a.0[0].y + a.0[2].y) / 2.0;
            let by = (b.0[0].y + b.0[2].y) / 2.0;
            let ax = (a.0[0].x + a.0[2].x) / 2.0;
            let bx = (b.0[0].x + b.0[2].x) / 2.0;

            if (ay - by).abs() < 20.0 {
                ax.partial_cmp(&bx).unwrap()
            } else {
                ay.partial_cmp(&by).unwrap()
            }
        });

        for (bbox, text, score) in &indexed {
            let x = (bbox[0].x + bbox[2].x) / 2.0;
            let y = (bbox[0].y + bbox[2].y) / 2.0;
            result.push_str(&format!(
                "[{:.0},{:.0}] {:.2}% {}\n",
                x,
                y,
                score * 100.0,
                text
            ));
        }

        result
    }

    /// Export OCR results as spatial text with intelligent spacing and line breaks
    ///
    /// This method formats text based on the spatial position of bounding boxes,
    /// constructing lines by mapping spatial coordinates to character positions.
    /// It ensures that all separate bounding boxes are separated by at least one space.
    ///
    /// # Parameters
    ///
    /// * `y_threshold_multiplier` - Multiplier for average box height to determine line breaks.
    ///   Default is 0.5. Higher values create fewer line breaks.
    /// * `x_threshold_multiplier` - Unused in this new algorithm (kept for API compatibility).
    ///   Spacing is now determined by exact spatial mapping + minimum separation.
    ///
    /// # Returns
    ///
    /// Formatted text string with spaces and newlines inserted based on spatial positioning.
    pub(crate) fn to_spatial_text(
        &self,
        y_threshold_multiplier: Option<f32>,
        x_threshold_multiplier: Option<f32>,
    ) -> String {
        if self.boxes.is_empty() {
            return String::new();
        }

        let y_mult = y_threshold_multiplier
            .or(self.y_threshold_multiplier)
            .unwrap_or(0.5);
        let x_mult = x_threshold_multiplier
            .or(self.x_threshold_multiplier)
            .unwrap_or(0.4);

        #[derive(Debug, Clone)]
        struct Token {
            x: f32,
            y: f32,
            width: f32,
            height: f32,
            text: String,
        }

        // Create tokens from boxes and calculate dimensions
        let mut tokens: Vec<Token> = self
            .boxes
            .iter()
            .zip(self.txts.iter())
            .map(|(bbox, text)| {
                let x = bbox[0].x;
                let y = bbox[0].y;
                let width = (bbox[1].x - bbox[0].x)
                    .abs()
                    .max((bbox[2].x - bbox[3].x).abs());
                let height = (bbox[3].y - bbox[0].y)
                    .abs()
                    .max((bbox[2].y - bbox[1].y).abs());
                Token {
                    x,
                    y,
                    width,
                    height,
                    text: text.clone(),
                }
            })
            .collect();

        // Calculate median height
        let median_height = if !tokens.is_empty() {
            let mut heights: Vec<f32> = tokens.iter().map(|t| t.height).collect();
            heights.sort_by(|a, b| a.partial_cmp(b).unwrap());
            heights[heights.len() / 2]
        } else {
            10.0
        };

        // Calculate average character width
        let avg_char_width = if !tokens.is_empty() {
            let total_chars: usize = tokens.iter().map(|t| t.text.len()).sum();
            let total_width: f32 = tokens.iter().map(|t| t.width).sum();
            if total_chars > 0 {
                total_width / total_chars as f32
            } else {
                median_height * 0.5
            }
        } else {
            10.0
        };

        let x_gap_threshold = avg_char_width * x_mult;
        let y_tolerance = median_height * y_mult; // Tolerance for Top-Y alignment

        // Sort by Top Y first, then by X
        tokens.sort_by(|a, b| {
            a.y.partial_cmp(&b.y)
                .unwrap()
                .then(a.x.partial_cmp(&b.x).unwrap())
        });

        // Group into lines based on Top Y alignment
        let mut lines: Vec<Vec<Token>> = Vec::new();
        let mut current_line: Vec<Token> = Vec::new();
        let mut current_line_y_sum: f32 = 0.0;

        for token in tokens {
            if !current_line.is_empty() {
                let current_line_avg_y = current_line_y_sum / current_line.len() as f32;

                if (token.y - current_line_avg_y).abs() <= y_tolerance {
                    current_line.push(token.clone());
                    current_line_y_sum += token.y;
                } else {
                    lines.push(current_line);
                    current_line = vec![token.clone()];
                    current_line_y_sum = token.y;
                }
            } else {
                current_line = vec![token.clone()];
                current_line_y_sum = token.y;
            }
        }
        if !current_line.is_empty() {
            lines.push(current_line);
        }

        // Build output using cursor-based approach
        // Note: Need to verify if `prev_line_avg_y` below needs update to `prev_line_avg_cy` logic.
        // In the existing code block below this chunk, `prev_line_avg_y` uses `t.y`.
        // I should leave `t.y` logic for blank lines or update it?
        // The chunk ends before that logic, so I'm safe, but I should check the subsequent context.

        // Build output using cursor-based approach
        let mut result = String::new();
        let mut prev_line_avg_y: Option<f32> = None;

        // Determine the global min_x to avoid huge left padding
        let min_x = if !lines.is_empty() {
            lines
                .iter()
                .flatten()
                .map(|t| t.x)
                .fold(f32::INFINITY, f32::min)
        } else {
            0.0
        };

        for line in lines {
            if line.is_empty() {
                continue;
            }

            // Vertical spacing logic
            let current_line_avg_y = line.iter().map(|t| t.y).sum::<f32>() / line.len() as f32;
            if let Some(prev_y) = prev_line_avg_y {
                let vertical_gap = current_line_avg_y - prev_y;
                // If gap is significantly larger than 1 line height, add blank lines
                if vertical_gap > median_height * 1.5 {
                    let num_blank_lines =
                        ((vertical_gap - median_height) / median_height).round() as usize;
                    for _ in 0..num_blank_lines.max(1) - 1 {
                        result.push('\n');
                    }
                }
            }
            prev_line_avg_y = Some(current_line_avg_y);

            // Sort line by X position
            let mut line_sorted = line.clone();
            line_sorted.sort_by(|a, b| a.x.partial_cmp(&b.x).unwrap());

            // Render line
            let mut current_char_pos: f32 = 0.0;
            let mut prev_token_end_x: f32 = min_x;

            for (i, token) in line_sorted.iter().enumerate() {
                // Determine target position in characters relative to min_x
                // But we don't want strict grid alignment for the *start* of the line,
                // just relative spacing. Or do we want indentation?
                // Let's preserve indentation relative to min_x.
                let target_char_pos = (token.x - min_x) / avg_char_width;

                // Calculate spaces to add
                let spaces_needed = if i == 0 {
                    // For first item, just indentation (can be 0)
                    target_char_pos.max(0.0)
                } else {
                    // For subsequent items, check physical gap
                    let physical_gap = token.x - prev_token_end_x;

                    if physical_gap < x_gap_threshold {
                        // Compact spacing for small gaps (standard word separation)
                        1.0
                    } else {
                        // Spatial spacing for large gaps
                        target_char_pos - current_char_pos
                    }
                };

                // Enforce minimum 1 space separation for subsequent items
                let spaces_to_insert = if i > 0 {
                    spaces_needed.round().max(1.0) as usize
                } else {
                    // Indentation
                    spaces_needed.round() as usize
                };

                for _ in 0..spaces_to_insert {
                    result.push(' ');
                }

                result.push_str(&token.text);

                // Update cursor position:
                current_char_pos += spaces_to_insert as f32 + token.text.len() as f32;
                prev_token_end_x = token.x + token.width;
            }
            result.push('\n');
        }

        result
    }
}