oar-ocr-core 0.6.3

Core types and predictors for oar-ocr
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
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
//! Dynamic batch processing logic

use super::config::{DynamicBatchConfig, PaddingStrategy, ShapeCompatibilityStrategy};
use super::types::{CompatibleBatch, CrossImageBatch, CrossImageItem};
use crate::core::OCRError;
use image::{ImageBuffer, Rgb, RgbImage};
use std::collections::HashMap;
use std::time::Instant;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
enum CompatibilityKey {
    Exact(u32, u32),
    AspectRatioBucket(i64),
    AspectRatioRatio(u32, u32),
    MaxDimensionBucket(u32),
    CustomTarget(Option<(u32, u32)>),
}

/// Enhanced trait for dynamic batching functionality
pub trait DynamicBatcher {
    /// Group images by compatible shapes for batching
    fn group_images_by_compatibility(
        &self,
        images: Vec<(usize, RgbImage)>,
        config: &DynamicBatchConfig,
    ) -> Result<Vec<CompatibleBatch>, OCRError>;

    /// Group cross-image items (e.g., text regions from multiple images)
    fn group_cross_image_items(
        &self,
        items: Vec<(usize, usize, RgbImage)>, // (source_image_idx, item_idx, image)
        config: &DynamicBatchConfig,
    ) -> Result<Vec<CrossImageBatch>, OCRError>;
}

/// Default implementation of dynamic batcher
#[derive(Debug)]
pub struct DefaultDynamicBatcher;

impl DefaultDynamicBatcher {
    /// Create a new default dynamic batcher
    pub fn new() -> Self {
        Self
    }

    /// Validate shape strategy to avoid invalid configurations (e.g., zero bucket sizes).
    fn validate_shape_strategy(strategy: &ShapeCompatibilityStrategy) -> Result<(), OCRError> {
        if let ShapeCompatibilityStrategy::MaxDimension { bucket_size } = strategy
            && *bucket_size == 0
        {
            return Err(OCRError::config_error_with_context(
                "shape_compatibility.bucket_size",
                &bucket_size.to_string(),
                "bucket_size must be greater than 0 for MaxDimension strategy",
            ));
        }
        Ok(())
    }

    /// Calculate aspect ratio of an image
    fn calculate_aspect_ratio(image: &RgbImage) -> f32 {
        let (width, height) = image.dimensions();
        width as f32 / height as f32
    }

    fn gcd_u32(mut a: u32, mut b: u32) -> u32 {
        while b != 0 {
            let remainder = a % b;
            a = b;
            b = remainder;
        }
        a
    }

    fn reduced_ratio(width: u32, height: u32) -> (u32, u32) {
        match (width, height) {
            (0, 0) => (0, 0),
            (0, _) => (0, 1),
            (_, 0) => (1, 0),
            (w, h) => {
                let gcd = Self::gcd_u32(w, h);
                (w / gcd, h / gcd)
            }
        }
    }

    fn aspect_ratio_bucket_id(image: &RgbImage, tolerance: f32) -> i64 {
        debug_assert!(tolerance.is_finite() && tolerance > 0.0);

        let (width, height) = image.dimensions();
        if height == 0 {
            return i64::MAX;
        }

        let ratio = width as f64 / height as f64;
        let scaled = ratio / tolerance as f64;

        if !scaled.is_finite() {
            return if scaled.is_sign_positive() {
                i64::MAX
            } else {
                i64::MIN
            };
        }

        scaled.floor().clamp(i64::MIN as f64, i64::MAX as f64) as i64
    }

    fn compatibility_key(
        image: &RgbImage,
        strategy: &ShapeCompatibilityStrategy,
    ) -> CompatibilityKey {
        match strategy {
            ShapeCompatibilityStrategy::Exact => {
                let (width, height) = image.dimensions();
                CompatibilityKey::Exact(width, height)
            }
            ShapeCompatibilityStrategy::AspectRatio { tolerance } => {
                if tolerance.is_finite() && *tolerance > 0.0 {
                    CompatibilityKey::AspectRatioBucket(Self::aspect_ratio_bucket_id(
                        image, *tolerance,
                    ))
                } else {
                    let (width, height) = image.dimensions();
                    let (ratio_w, ratio_h) = Self::reduced_ratio(width, height);
                    CompatibilityKey::AspectRatioRatio(ratio_w, ratio_h)
                }
            }
            ShapeCompatibilityStrategy::MaxDimension { bucket_size } => {
                let (width, height) = image.dimensions();
                let max_dimension = width.max(height);
                CompatibilityKey::MaxDimensionBucket(max_dimension / bucket_size)
            }
            ShapeCompatibilityStrategy::Custom { targets, tolerance } => {
                CompatibilityKey::CustomTarget(Self::find_best_target(image, targets, *tolerance))
            }
        }
    }

    /// Check if two images are compatible based on strategy
    fn are_images_compatible(
        img1: &RgbImage,
        img2: &RgbImage,
        strategy: &ShapeCompatibilityStrategy,
    ) -> bool {
        match strategy {
            ShapeCompatibilityStrategy::Exact => img1.dimensions() == img2.dimensions(),
            ShapeCompatibilityStrategy::AspectRatio { tolerance } => {
                let ratio1 = Self::calculate_aspect_ratio(img1);
                let ratio2 = Self::calculate_aspect_ratio(img2);
                (ratio1 - ratio2).abs() <= *tolerance
            }
            ShapeCompatibilityStrategy::MaxDimension { bucket_size } => {
                // Note: bucket_size is validated by validate_shape_strategy() before this is called
                let (w1, h1) = img1.dimensions();
                let (w2, h2) = img2.dimensions();
                let max1 = w1.max(h1);
                let max2 = w2.max(h2);
                max1 / bucket_size == max2 / bucket_size
            }
            ShapeCompatibilityStrategy::Custom { targets, tolerance } => {
                // Find the best target for each image and check if they match
                let target1 = Self::find_best_target(img1, targets, *tolerance);
                let target2 = Self::find_best_target(img2, targets, *tolerance);
                target1 == target2
            }
        }
    }

    /// Find the best target dimensions for an image
    fn find_best_target(
        image: &RgbImage,
        targets: &[(u32, u32)],
        tolerance: f32,
    ) -> Option<(u32, u32)> {
        let (width, height) = image.dimensions();
        let aspect_ratio = width as f32 / height as f32;

        targets
            .iter()
            .find(|(target_w, target_h)| {
                let target_ratio = *target_w as f32 / *target_h as f32;
                (aspect_ratio - target_ratio).abs() <= tolerance
            })
            .copied()
    }

    /// Calculate target dimensions for a batch
    fn calculate_target_dimensions<'a>(
        images: impl IntoIterator<Item = &'a RgbImage>,
        strategy: &ShapeCompatibilityStrategy,
    ) -> (u32, u32) {
        match strategy {
            ShapeCompatibilityStrategy::Exact => {
                // All images should have the same dimensions
                images
                    .into_iter()
                    .next()
                    .map(|img| img.dimensions())
                    .unwrap_or((0, 0))
            }
            _ => {
                // Calculate the maximum dimensions
                let (max_width, max_height) = images.into_iter().fold((0, 0), |acc, img| {
                    (acc.0.max(img.width()), acc.1.max(img.height()))
                });
                (max_width, max_height)
            }
        }
    }

    /// Pad an image to target dimensions
    fn pad_image(
        image: &RgbImage,
        target_dims: (u32, u32),
        strategy: &PaddingStrategy,
    ) -> Result<RgbImage, OCRError> {
        let (current_width, current_height) = image.dimensions();
        let (target_width, target_height) = target_dims;

        if current_width == target_width && current_height == target_height {
            return Ok(image.clone());
        }

        if current_width > target_width || current_height > target_height {
            return Err(OCRError::InvalidInput {
                message: format!(
                    "Image dimensions ({}, {}) exceed target dimensions ({}, {}) for padding",
                    current_width, current_height, target_width, target_height
                ),
            });
        }

        let mut padded = ImageBuffer::new(target_width, target_height);

        // Calculate offsets for centering the original image
        let x_offset = (target_width - current_width) / 2;
        let y_offset = (target_height - current_height) / 2;

        match strategy {
            PaddingStrategy::Zero => {
                // Fill with zeros (black)
                for pixel in padded.pixels_mut() {
                    *pixel = Rgb([0, 0, 0]);
                }
                // Copy the original image to the center
                Self::copy_centered_image(&mut padded, image, x_offset, y_offset);
            }
            PaddingStrategy::Center { fill_color } => {
                // Fill with specified color
                for pixel in padded.pixels_mut() {
                    *pixel = Rgb(*fill_color);
                }
                // Copy the original image to the center
                Self::copy_centered_image(&mut padded, image, x_offset, y_offset);
            }
            PaddingStrategy::Edge => {
                // Edge padding: directly compute all pixels with edge replication
                Self::apply_edge_padding(&mut padded, image, x_offset, y_offset);
            }
            PaddingStrategy::Smart => {
                // Smart padding: content-aware padding based on image analysis
                let smart_color = Self::calculate_smart_padding_color(image);
                for pixel in padded.pixels_mut() {
                    *pixel = smart_color;
                }
                // Copy the original image to the center
                Self::copy_centered_image(&mut padded, image, x_offset, y_offset);
            }
        }

        Ok(padded)
    }

    /// Copy the original image to the center of the padded image
    fn copy_centered_image(
        padded: &mut RgbImage,
        original: &RgbImage,
        x_offset: u32,
        y_offset: u32,
    ) {
        let (orig_width, orig_height) = original.dimensions();
        for y in 0..orig_height {
            for x in 0..orig_width {
                let pixel = original.get_pixel(x, y);
                padded.put_pixel(x + x_offset, y + y_offset, *pixel);
            }
        }
    }

    /// Apply edge padding using region-based approach
    ///
    /// Divides the padded image into 9 regions and processes each separately,
    /// eliminating conditional checks in inner loops.
    fn apply_edge_padding(
        padded: &mut RgbImage,
        original: &RgbImage,
        x_offset: u32,
        y_offset: u32,
    ) {
        let (padded_width, padded_height) = padded.dimensions();
        let (orig_width, orig_height) = original.dimensions();

        // Get raw buffer access for better performance
        let padded_buf = padded.as_mut();
        let original_buf: &[u8] = original.as_ref();

        // Region 1: Top-left corner
        if x_offset > 0 && y_offset > 0 {
            let corner_pixel = &original_buf[0..3];
            for y in 0..y_offset {
                let row_offset = (y * padded_width * 3) as usize;
                for x in 0..x_offset {
                    let offset = row_offset + (x * 3) as usize;
                    padded_buf[offset..offset + 3].copy_from_slice(corner_pixel);
                }
            }
        }

        // Region 2: Top edge
        if y_offset > 0 {
            for y in 0..y_offset {
                let padded_row_offset = (y * padded_width * 3) as usize;
                for x in 0..orig_width {
                    let src_offset = (x * 3) as usize;
                    let dst_offset = padded_row_offset + ((x_offset + x) * 3) as usize;
                    padded_buf[dst_offset..dst_offset + 3]
                        .copy_from_slice(&original_buf[src_offset..src_offset + 3]);
                }
            }
        }

        // Region 3: Top-right corner
        if x_offset + orig_width < padded_width && y_offset > 0 {
            let corner_pixel =
                &original_buf[(orig_width - 1) as usize * 3..(orig_width as usize * 3)];
            for y in 0..y_offset {
                let row_offset = (y * padded_width * 3) as usize;
                for x in (x_offset + orig_width)..padded_width {
                    let offset = row_offset + (x * 3) as usize;
                    padded_buf[offset..offset + 3].copy_from_slice(corner_pixel);
                }
            }
        }

        // Region 4: Left edge
        if x_offset > 0 {
            for y in 0..orig_height {
                let src_offset = (y * orig_width * 3) as usize;
                let edge_pixel = &original_buf[src_offset..src_offset + 3];
                let padded_row_offset = ((y_offset + y) * padded_width * 3) as usize;

                for x in 0..x_offset {
                    let offset = padded_row_offset + (x * 3) as usize;
                    padded_buf[offset..offset + 3].copy_from_slice(edge_pixel);
                }
            }
        }

        // Region 5: Center (original image) - bulk copy
        for y in 0..orig_height {
            let src_row_offset = (y * orig_width * 3) as usize;
            let dst_row_offset = ((y_offset + y) * padded_width + x_offset) as usize * 3;
            let row_len = (orig_width * 3) as usize;

            padded_buf[dst_row_offset..dst_row_offset + row_len]
                .copy_from_slice(&original_buf[src_row_offset..src_row_offset + row_len]);
        }

        // Region 6: Right edge
        if x_offset + orig_width < padded_width {
            for y in 0..orig_height {
                let src_offset = ((y * orig_width + orig_width - 1) * 3) as usize;
                let edge_pixel = &original_buf[src_offset..src_offset + 3];
                let padded_row_offset = ((y_offset + y) * padded_width * 3) as usize;

                for x in (x_offset + orig_width)..padded_width {
                    let offset = padded_row_offset + (x * 3) as usize;
                    padded_buf[offset..offset + 3].copy_from_slice(edge_pixel);
                }
            }
        }

        // Region 7: Bottom-left corner
        if x_offset > 0 && y_offset + orig_height < padded_height {
            let corner_offset = ((orig_height - 1) * orig_width * 3) as usize;
            let corner_pixel = &original_buf[corner_offset..corner_offset + 3];

            for y in (y_offset + orig_height)..padded_height {
                let row_offset = (y * padded_width * 3) as usize;
                for x in 0..x_offset {
                    let offset = row_offset + (x * 3) as usize;
                    padded_buf[offset..offset + 3].copy_from_slice(corner_pixel);
                }
            }
        }

        // Region 8: Bottom edge
        if y_offset + orig_height < padded_height {
            let bottom_row_offset = ((orig_height - 1) * orig_width * 3) as usize;

            for y in (y_offset + orig_height)..padded_height {
                let padded_row_offset = (y * padded_width * 3) as usize;
                for x in 0..orig_width {
                    let src_offset = bottom_row_offset + (x * 3) as usize;
                    let dst_offset = padded_row_offset + ((x_offset + x) * 3) as usize;
                    padded_buf[dst_offset..dst_offset + 3]
                        .copy_from_slice(&original_buf[src_offset..src_offset + 3]);
                }
            }
        }

        // Region 9: Bottom-right corner
        if x_offset + orig_width < padded_width && y_offset + orig_height < padded_height {
            let corner_offset = ((orig_height - 1) * orig_width + orig_width - 1) as usize * 3;
            let corner_pixel = &original_buf[corner_offset..corner_offset + 3];

            for y in (y_offset + orig_height)..padded_height {
                let row_offset = (y * padded_width * 3) as usize;
                for x in (x_offset + orig_width)..padded_width {
                    let offset = row_offset + (x * 3) as usize;
                    padded_buf[offset..offset + 3].copy_from_slice(corner_pixel);
                }
            }
        }
    }

    /// Calculate smart padding color based on image content analysis
    fn calculate_smart_padding_color(image: &RgbImage) -> Rgb<u8> {
        let (width, height) = image.dimensions();

        if width == 0 || height == 0 {
            return Rgb([0, 0, 0]); // Default to black for empty images
        }

        // Sample edge pixels to determine the most appropriate padding color
        let mut edge_pixels = Vec::new();

        // Sample top and bottom edges
        for x in 0..width {
            edge_pixels.push(*image.get_pixel(x, 0)); // Top edge
            if height > 1 {
                edge_pixels.push(*image.get_pixel(x, height - 1)); // Bottom edge
            }
        }

        // Sample left and right edges (excluding corners to avoid double counting)
        for y in 1..height.saturating_sub(1) {
            edge_pixels.push(*image.get_pixel(0, y)); // Left edge
            if width > 1 {
                edge_pixels.push(*image.get_pixel(width - 1, y)); // Right edge
            }
        }

        if edge_pixels.is_empty() {
            return Rgb([0, 0, 0]);
        }

        // Calculate the median color of edge pixels for robustness against outliers
        let mut r_values: Vec<u8> = edge_pixels.iter().map(|p| p.0[0]).collect();
        let mut g_values: Vec<u8> = edge_pixels.iter().map(|p| p.0[1]).collect();
        let mut b_values: Vec<u8> = edge_pixels.iter().map(|p| p.0[2]).collect();

        r_values.sort_unstable();
        g_values.sort_unstable();
        b_values.sort_unstable();

        let len = r_values.len();
        let median_r = r_values[len / 2];
        let median_g = g_values[len / 2];
        let median_b = b_values[len / 2];

        // Apply some heuristics to improve the padding color choice
        // If the median color is very bright, slightly darken it to avoid harsh contrast
        // If the median color is very dark, slightly brighten it for better visibility
        let adjusted_r = Self::adjust_padding_component(median_r);
        let adjusted_g = Self::adjust_padding_component(median_g);
        let adjusted_b = Self::adjust_padding_component(median_b);

        Rgb([adjusted_r, adjusted_g, adjusted_b])
    }

    /// Adjust a color component for better padding appearance
    fn adjust_padding_component(component: u8) -> u8 {
        match component {
            // Very dark colors (0-63): brighten slightly
            0..=63 => (component as u16 + 16).min(255) as u8,
            // Very bright colors (192-255): darken slightly
            192..=255 => (component as i16 - 16).max(0) as u8,
            // Medium colors (64-191): use as-is
            _ => component,
        }
    }

    /// Generate a batch ID based on target dimensions
    fn generate_batch_id(target_dims: (u32, u32), batch_index: usize) -> String {
        format!("{}x{}_{}", target_dims.0, target_dims.1, batch_index)
    }
}

impl Default for DefaultDynamicBatcher {
    fn default() -> Self {
        Self::new()
    }
}

impl DynamicBatcher for DefaultDynamicBatcher {
    fn group_images_by_compatibility(
        &self,
        images: Vec<(usize, RgbImage)>,
        config: &DynamicBatchConfig,
    ) -> Result<Vec<CompatibleBatch>, OCRError> {
        Self::validate_shape_strategy(&config.shape_compatibility)?;
        let _start_time = Instant::now();
        let mut batches = Vec::new();
        let mut batch_counter = 0;

        // Group images by compatibility
        let mut compatibility_groups: HashMap<CompatibilityKey, Vec<(usize, RgbImage)>> =
            HashMap::new();

        for (index, image) in images {
            let group_key = match &config.shape_compatibility {
                ShapeCompatibilityStrategy::AspectRatio { tolerance }
                    if tolerance.is_finite() && *tolerance > 0.0 =>
                {
                    let bucket = Self::aspect_ratio_bucket_id(&image, *tolerance);
                    let candidate_buckets =
                        [bucket, bucket.saturating_sub(1), bucket.saturating_add(1)];

                    let mut selected_key = None;
                    for candidate_bucket in candidate_buckets {
                        let candidate_key = CompatibilityKey::AspectRatioBucket(candidate_bucket);
                        if let Some(group_images) = compatibility_groups.get(&candidate_key)
                            && let Some((_, first_image)) = group_images.first()
                            && Self::are_images_compatible(
                                &image,
                                first_image,
                                &config.shape_compatibility,
                            )
                        {
                            selected_key = Some(candidate_key);
                            break;
                        }
                    }

                    selected_key.unwrap_or(CompatibilityKey::AspectRatioBucket(bucket))
                }
                _ => Self::compatibility_key(&image, &config.shape_compatibility),
            };

            compatibility_groups
                .entry(group_key)
                .or_default()
                .push((index, image));
        }

        // Convert groups to batches
        for (_, group_images) in compatibility_groups {
            if group_images.len() < config.min_batch_size {
                // Process small groups as individual batches
                for (index, image) in group_images {
                    let target_dims = image.dimensions();
                    let batch_id = Self::generate_batch_id(target_dims, batch_counter);
                    let mut batch = CompatibleBatch::new(batch_id, target_dims);
                    batch.add_image(image, index);
                    batches.push(batch);
                    batch_counter += 1;
                }
            } else {
                // Split large groups into appropriately sized batches
                let max_batch_size = config.max_detection_batch_size;
                let target_dims = Self::calculate_target_dimensions(
                    group_images.iter().map(|(_, img)| img),
                    &config.shape_compatibility,
                );

                let mut group_iter = group_images.into_iter();
                loop {
                    let batch_id = Self::generate_batch_id(target_dims, batch_counter);
                    let mut batch = CompatibleBatch::new(batch_id, target_dims);

                    for _ in 0..max_batch_size {
                        let Some((index, image)) = group_iter.next() else {
                            break;
                        };
                        // Pad image to target dimensions if needed
                        let padded_image = if image.dimensions() == target_dims {
                            image
                        } else {
                            Self::pad_image(&image, target_dims, &config.padding_strategy)?
                        };
                        batch.add_image(padded_image, index);
                    }

                    if batch.is_empty() {
                        break;
                    }

                    batches.push(batch);
                    batch_counter += 1;
                }
            }
        }

        Ok(batches)
    }

    fn group_cross_image_items(
        &self,
        items: Vec<(usize, usize, RgbImage)>,
        config: &DynamicBatchConfig,
    ) -> Result<Vec<CrossImageBatch>, OCRError> {
        Self::validate_shape_strategy(&config.shape_compatibility)?;
        let mut batches = Vec::new();
        let mut batch_counter = 0;

        // Group by compatibility
        let mut compatibility_groups: HashMap<CompatibilityKey, Vec<CrossImageItem>> =
            HashMap::new();

        for (source_idx, item_idx, image) in items {
            let item = CrossImageItem::new(source_idx, item_idx, image);
            let group_key = match &config.shape_compatibility {
                ShapeCompatibilityStrategy::AspectRatio { tolerance }
                    if tolerance.is_finite() && *tolerance > 0.0 =>
                {
                    let bucket = Self::aspect_ratio_bucket_id(&item.image, *tolerance);
                    let candidate_buckets =
                        [bucket, bucket.saturating_sub(1), bucket.saturating_add(1)];

                    let mut selected_key = None;
                    for candidate_bucket in candidate_buckets {
                        let candidate_key = CompatibilityKey::AspectRatioBucket(candidate_bucket);
                        if let Some(group_items) = compatibility_groups.get(&candidate_key)
                            && let Some(first_item) = group_items.first()
                            && Self::are_images_compatible(
                                &item.image,
                                &first_item.image,
                                &config.shape_compatibility,
                            )
                        {
                            selected_key = Some(candidate_key);
                            break;
                        }
                    }

                    selected_key.unwrap_or(CompatibilityKey::AspectRatioBucket(bucket))
                }
                _ => Self::compatibility_key(&item.image, &config.shape_compatibility),
            };

            compatibility_groups
                .entry(group_key)
                .or_default()
                .push(item);
        }

        // Convert groups to batches
        for (_, group_items) in compatibility_groups {
            if group_items.len() < config.min_batch_size {
                // Process small groups individually
                for item in group_items {
                    let target_dims = item.dimensions();
                    let batch_id = Self::generate_batch_id(target_dims, batch_counter);
                    let mut batch = CrossImageBatch::new(batch_id, target_dims);
                    batch.add_item(item);
                    batches.push(batch);
                    batch_counter += 1;
                }
            } else {
                // Split large groups into appropriately sized batches
                let max_batch_size = config.max_recognition_batch_size;
                let target_dims = Self::calculate_target_dimensions(
                    group_items.iter().map(|item| &item.image),
                    &config.shape_compatibility,
                );

                let mut group_iter = group_items.into_iter();
                loop {
                    let batch_id = Self::generate_batch_id(target_dims, batch_counter);
                    let mut batch = CrossImageBatch::new(batch_id, target_dims);

                    for _ in 0..max_batch_size {
                        let Some(item) = group_iter.next() else {
                            break;
                        };
                        let CrossImageItem {
                            source_image_index,
                            item_index,
                            image,
                            metadata,
                        } = item;

                        // Pad image to target dimensions if needed
                        let padded_image = if image.dimensions() == target_dims {
                            image
                        } else {
                            Self::pad_image(&image, target_dims, &config.padding_strategy)?
                        };
                        let mut padded_item =
                            CrossImageItem::new(source_image_index, item_index, padded_image);
                        padded_item.metadata = metadata;
                        batch.add_item(padded_item);
                    }

                    if batch.items.is_empty() {
                        break;
                    }

                    batches.push(batch);
                    batch_counter += 1;
                }
            }
        }

        Ok(batches)
    }
}

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

    /// Helper function to create a test image with a specific pattern
    fn create_test_image(width: u32, height: u32, pattern: &str) -> RgbImage {
        let mut image = ImageBuffer::new(width, height);

        match pattern {
            "solid_red" => {
                for pixel in image.pixels_mut() {
                    *pixel = Rgb([255, 0, 0]);
                }
            }
            "gradient" => {
                for (x, y, pixel) in image.enumerate_pixels_mut() {
                    let r = (x * 255 / width.max(1)) as u8;
                    let g = (y * 255 / height.max(1)) as u8;
                    *pixel = Rgb([r, g, 128]);
                }
            }
            "border" => {
                // Create an image with distinct border colors
                for (x, y, pixel) in image.enumerate_pixels_mut() {
                    if x == 0 {
                        *pixel = Rgb([255, 0, 0]); // Red left edge
                    } else if x == width - 1 {
                        *pixel = Rgb([0, 255, 0]); // Green right edge
                    } else if y == 0 {
                        *pixel = Rgb([0, 0, 255]); // Blue top edge
                    } else if y == height - 1 {
                        *pixel = Rgb([255, 255, 0]); // Yellow bottom edge
                    } else {
                        *pixel = Rgb([128, 128, 128]); // Gray center
                    }
                }
            }
            _ => {
                // Default: black image
                for pixel in image.pixels_mut() {
                    *pixel = Rgb([0, 0, 0]);
                }
            }
        }

        image
    }

    #[test]
    fn test_pad_image_zero_strategy() -> Result<(), OCRError> {
        let image = create_test_image(10, 10, "solid_red");
        let strategy = PaddingStrategy::Zero;
        let result = DefaultDynamicBatcher::pad_image(&image, (20, 20), &strategy)?;

        assert_eq!(result.dimensions(), (20, 20));

        // Check that padding areas are black (zero)
        assert_eq!(*result.get_pixel(0, 0), Rgb([0, 0, 0])); // Top-left corner
        assert_eq!(*result.get_pixel(19, 19), Rgb([0, 0, 0])); // Bottom-right corner

        // Check that the original image is centered
        assert_eq!(*result.get_pixel(10, 10), Rgb([255, 0, 0])); // Center of original
        Ok(())
    }

    #[test]
    fn test_pad_image_center_strategy() -> Result<(), OCRError> {
        let image = create_test_image(10, 10, "solid_red");
        let strategy = PaddingStrategy::Center {
            fill_color: [0, 255, 0],
        }; // Green padding
        let result = DefaultDynamicBatcher::pad_image(&image, (20, 20), &strategy)?;

        assert_eq!(result.dimensions(), (20, 20));

        // Check that padding areas are green
        assert_eq!(*result.get_pixel(0, 0), Rgb([0, 255, 0])); // Top-left corner
        assert_eq!(*result.get_pixel(19, 19), Rgb([0, 255, 0])); // Bottom-right corner

        // Check that the original image is centered
        assert_eq!(*result.get_pixel(10, 10), Rgb([255, 0, 0])); // Center of original
        Ok(())
    }

    #[test]
    fn test_pad_image_edge_strategy() -> Result<(), OCRError> {
        let image = create_test_image(6, 6, "border");
        let strategy = PaddingStrategy::Edge;
        let result = DefaultDynamicBatcher::pad_image(&image, (12, 12), &strategy)?;

        assert_eq!(result.dimensions(), (12, 12));

        // Check edge replication
        // Left padding should replicate the left edge (red)
        assert_eq!(*result.get_pixel(0, 6), Rgb([255, 0, 0])); // Left edge replication

        // Right padding should replicate the right edge (green)
        assert_eq!(*result.get_pixel(11, 6), Rgb([0, 255, 0])); // Right edge replication

        // Top padding should replicate the top edge (blue)
        assert_eq!(*result.get_pixel(6, 0), Rgb([0, 0, 255])); // Top edge replication

        // Bottom padding should replicate the bottom edge (yellow)
        assert_eq!(*result.get_pixel(6, 11), Rgb([255, 255, 0])); // Bottom edge replication

        // Check that the original image content is preserved
        assert_eq!(*result.get_pixel(6, 6), Rgb([128, 128, 128])); // Center of original
        Ok(())
    }

    #[test]
    fn test_pad_image_smart_strategy() -> Result<(), OCRError> {
        let image = create_test_image(10, 10, "border");
        let strategy = PaddingStrategy::Smart;
        let result = DefaultDynamicBatcher::pad_image(&image, (20, 20), &strategy)?;

        assert_eq!(result.dimensions(), (20, 20));

        // The smart strategy should calculate a color based on edge analysis
        // We can't predict the exact color, but we can verify it's not the default placeholder
        let padding_pixel = *result.get_pixel(0, 0);
        assert_ne!(padding_pixel, Rgb([64, 64, 64])); // Should not be the old placeholder

        // Check that the original image is centered and preserved
        // The original image is 10x10, centered in 20x20, so it starts at (5,5)
        assert_eq!(*result.get_pixel(10, 10), Rgb([128, 128, 128])); // Center of original (5+5, 5+5)
        Ok(())
    }

    #[test]
    fn test_pad_image_no_padding_needed() -> Result<(), OCRError> {
        let image = create_test_image(10, 10, "solid_red");
        let strategy = PaddingStrategy::Zero;
        let result = DefaultDynamicBatcher::pad_image(&image, (10, 10), &strategy)?;

        // Should return a clone of the original image
        assert_eq!(result.dimensions(), (10, 10));
        assert_eq!(*result.get_pixel(5, 5), Rgb([255, 0, 0]));
        Ok(())
    }

    #[test]
    fn test_pad_image_error_on_oversized_image() {
        let image = create_test_image(20, 20, "solid_red");
        let strategy = PaddingStrategy::Zero;
        let result = DefaultDynamicBatcher::pad_image(&image, (10, 10), &strategy);

        // Should return an error when trying to pad to smaller dimensions
        assert!(result.is_err());
    }

    #[test]
    fn test_calculate_smart_padding_color() {
        // Test with a uniform color image
        let uniform_image = create_test_image(10, 10, "solid_red");
        let smart_color = DefaultDynamicBatcher::calculate_smart_padding_color(&uniform_image);

        // For a uniform red image, the smart color should be close to red but adjusted
        assert!(smart_color.0[0] > 200); // Should still be predominantly red
        assert!(smart_color.0[1] < 50); // Should have low green
        assert!(smart_color.0[2] < 50); // Should have low blue

        // Test with a gradient image
        let gradient_image = create_test_image(10, 10, "gradient");
        let gradient_smart_color =
            DefaultDynamicBatcher::calculate_smart_padding_color(&gradient_image);

        // Should return a reasonable color (not extreme values)
        assert!(gradient_smart_color.0[0] < 255);
        assert!(gradient_smart_color.0[1] < 255);
        assert!(gradient_smart_color.0[2] < 255);
    }

    #[test]
    fn test_adjust_padding_component() {
        // Test dark color adjustment (should brighten)
        assert!(DefaultDynamicBatcher::adjust_padding_component(30) > 30);

        // Test bright color adjustment (should darken)
        assert!(DefaultDynamicBatcher::adjust_padding_component(220) < 220);

        // Test medium color (should remain unchanged)
        assert_eq!(DefaultDynamicBatcher::adjust_padding_component(128), 128);

        // Test edge cases
        assert_eq!(DefaultDynamicBatcher::adjust_padding_component(0), 16);
        assert_eq!(DefaultDynamicBatcher::adjust_padding_component(255), 239);
    }
}