xberg 1.0.8

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

use ahash::AHashMap;
use async_trait::async_trait;
use std::borrow::Cow;
use std::cell::RefCell;
use std::panic::catch_unwind;
use std::path::Path;
use std::sync::{Arc, Mutex};

thread_local! {
    static PADDLE_TL_ACCEL: RefCell<Option<crate::core::config::acceleration::AccelerationConfig>> = const { RefCell::new(None) };
}

fn paddle_accel_builder_fn(
    builder: ort::session::builder::SessionBuilder,
) -> std::result::Result<ort::session::builder::SessionBuilder, ort::Error> {
    let accel = PADDLE_TL_ACCEL.with(|cell| cell.borrow().clone());
    crate::ort_discovery::apply_execution_providers(builder, accel.as_ref())
}

use crate::Result;
use crate::core::config::OcrConfig;
use crate::ocr::conversion::{elements_to_hocr_words, text_block_to_element};
use crate::plugins::{OcrBackend, OcrBackendType, Plugin};
use crate::table_core::{reconstruct_table, table_to_markdown};
use crate::types::{ExtractedDocument, FormatMetadata, Metadata, OcrElement, OcrMetadata, Table};

#[cfg(test)]
use super::config::DEFAULT_RECOGNITION_BATCH_SIZE;
use super::config::{MAX_RECOGNITION_BATCH_SIZE, MIN_RECOGNITION_BATCH_SIZE, PaddleOcrConfig};
use super::model_manager::{ModelManager, SharedModelPaths};
use super::{is_language_supported, language_to_script_family, map_language_code};

use xberg_paddle_ocr::OcrLite;

const ORIENTATION_CONFIDENCE_METADATA_KEY: &str = "orientation_confidence";

#[derive(Debug)]
struct RotationOutcome {
    rotated_bytes: Option<Vec<u8>>,
    processed_width: u32,
    processed_height: u32,
    orientation: Option<crate::doc_orientation::OrientationResult>,
}

impl RotationOutcome {
    fn unrotated(width: u32, height: u32) -> Self {
        Self {
            rotated_bytes: None,
            processed_width: width,
            processed_height: height,
            orientation: None,
        }
    }

    fn auto_rotated(&self) -> bool {
        self.rotated_bytes.is_some()
    }
}

fn rotate_for_detected_orientation(
    image: &image::RgbImage,
    orientation: crate::doc_orientation::OrientationResult,
) -> Result<RotationOutcome> {
    if orientation.degrees == 0 || orientation.confidence < crate::doc_orientation::MIN_CONFIDENCE {
        return Ok(RotationOutcome {
            rotated_bytes: None,
            processed_width: image.width(),
            processed_height: image.height(),
            orientation: Some(orientation),
        });
    }

    let rotated = match orientation.degrees {
        90 => image::imageops::rotate270(image),
        180 => image::imageops::rotate180(image),
        270 => image::imageops::rotate90(image),
        _ => {
            return Ok(RotationOutcome {
                rotated_bytes: None,
                processed_width: image.width(),
                processed_height: image.height(),
                orientation: Some(orientation),
            });
        }
    };
    let processed_width = rotated.width();
    let processed_height = rotated.height();
    let mut encoded = std::io::Cursor::new(Vec::new());
    rotated
        .write_to(&mut encoded, image::ImageFormat::Png)
        .map_err(|error| crate::XbergError::Ocr {
            message: format!("Failed to encode rotated PaddleOCR image: {error}"),
            source: None,
        })?;

    Ok(RotationOutcome {
        rotated_bytes: Some(encoded.into_inner()),
        processed_width,
        processed_height,
        orientation: Some(orientation),
    })
}

fn image_metadata(outcome: &RotationOutcome) -> AHashMap<Cow<'static, str>, serde_json::Value> {
    let mut additional = AHashMap::new();
    additional.insert(
        Cow::Borrowed(crate::ocr::OCR_PROCESSED_IMAGE_WIDTH_METADATA_KEY),
        serde_json::Value::Number(outcome.processed_width.into()),
    );
    additional.insert(
        Cow::Borrowed(crate::ocr::OCR_PROCESSED_IMAGE_HEIGHT_METADATA_KEY),
        serde_json::Value::Number(outcome.processed_height.into()),
    );
    if let Some(orientation) = outcome.orientation {
        additional.insert(
            Cow::Borrowed(crate::ocr::OCR_ORIENTATION_DEGREES_METADATA_KEY),
            serde_json::Value::Number(orientation.degrees.into()),
        );
        additional.insert(
            Cow::Borrowed(ORIENTATION_CONFIDENCE_METADATA_KEY),
            serde_json::json!(orientation.confidence),
        );
    }
    if outcome.auto_rotated() {
        additional.insert(
            Cow::Borrowed(crate::ocr::OCR_AUTO_ROTATED_METADATA_KEY),
            serde_json::Value::Bool(true),
        );
    }
    additional
}

/// PaddleOCR backend using ONNX Runtime.
///
/// Maintains a pool of OCR engines keyed by script family. Each family has its own
/// recognition model and character dictionary, while detection and classification
/// models are shared across all families.
///
/// # Thread Safety
///
/// The backend is `Send + Sync` and can be used across threads safely via `Arc`.
/// Each engine in the pool has its own mutex, so concurrent OCR on different
/// script families does not block.
#[cfg_attr(alef, alef(skip))]
pub struct PaddleOcrBackend {
    config: Arc<PaddleOcrConfig>,
    model_manager: ModelManager,
    /// Detection + classification model paths, lazily initialized and keyed by
    /// `"{model_version}/{model_tier}"` so a per-request `paddle_ocr_config`
    /// override loads the detection model matching its recognition model instead
    /// of the backend-default version/tier (issue #1279).
    shared_paths: Mutex<AHashMap<String, SharedModelPaths>>,
    /// Per-model OCR engines, lazily initialized. Keyed by "{tier}/{model_key}".
    /// Multiple script families may share the same engine (e.g. chinese+japanese use unified_server).
    /// OcrLite inference methods take `&self`, enabling lock-free concurrent page OCR.
    engine_pool: Mutex<AHashMap<String, Arc<OcrLite>>>,
    /// Document orientation detector, lazily initialized.
    doc_ori_detector: once_cell::sync::OnceCell<crate::doc_orientation::DocOrientationDetector>,
    /// Hardware acceleration configuration for ORT sessions (set at construction).
    /// Per-request acceleration from `OcrConfig.acceleration` takes precedence.
    acceleration: Option<crate::core::config::acceleration::AccelerationConfig>,
}

impl PaddleOcrBackend {
    /// Create a new PaddleOCR backend with default configuration.
    pub fn new() -> Result<Self> {
        Self::with_config(PaddleOcrConfig::default())
    }

    /// Create a new PaddleOCR backend with custom configuration.
    pub fn with_config(config: PaddleOcrConfig) -> Result<Self> {
        let cache_dir = config.resolve_cache_dir();
        Ok(Self {
            config: Arc::new(config),
            model_manager: ModelManager::new(cache_dir),
            shared_paths: Mutex::new(AHashMap::new()),
            engine_pool: Mutex::new(AHashMap::new()),
            doc_ori_detector: once_cell::sync::OnceCell::new(),
            acceleration: None,
        })
    }

    /// Set hardware acceleration for ORT sessions.
    pub fn with_acceleration(mut self, accel: crate::core::config::acceleration::AccelerationConfig) -> Self {
        self.acceleration = Some(accel);
        self
    }

    /// Get the current acceleration configuration, if any.
    pub fn acceleration(&self) -> Option<&crate::core::config::acceleration::AccelerationConfig> {
        self.acceleration.as_ref()
    }

    /// Resolve effective acceleration: per-request from OcrConfig takes precedence
    /// over the backend-level default.
    fn resolve_acceleration(
        &self,
        request_accel: Option<&crate::core::config::acceleration::AccelerationConfig>,
    ) -> Option<crate::core::config::acceleration::AccelerationConfig> {
        request_accel.cloned().or_else(|| self.acceleration.clone())
    }

    /// Get or initialize shared model paths (det + cls) for the given config's
    /// version and tier.
    ///
    /// Keyed by `"{model_version}/{model_tier}"` so a per-request override
    /// (`OcrConfig.paddle_ocr_config`) resolves a detection model matching its
    /// recognition model rather than the backend default (issue #1279).
    fn get_or_init_shared_paths(&self, config: &PaddleOcrConfig) -> Result<SharedModelPaths> {
        let key = format!("{}/{}", config.model_version, config.model_tier);
        let mut paths = self.shared_paths.lock().map_err(|e| crate::XbergError::Plugin {
            message: format!("Failed to acquire shared paths lock: {e}"),
            plugin_name: "paddle-ocr".to_string(),
        })?;

        if let Some(p) = paths.get(&key) {
            return Ok(p.clone());
        }

        let shared = self
            .model_manager
            .ensure_shared_models_versioned(&config.model_version, &config.model_tier)?;
        paths.insert(key, shared.clone());
        Ok(shared)
    }

    /// Get or create an OCR engine for the given script family.
    ///
    /// The engine pool is keyed by a composite `"{tier}/{model_key}/{accel}"` string.
    /// This ensures that:
    /// - Multiple families sharing the same unified model reuse one engine
    /// - Different tiers get different engines (different det model)
    /// - Different acceleration configs get separate engines (CPU vs CUDA)
    fn get_or_init_engine_for_family(
        &self,
        family: &str,
        config: &PaddleOcrConfig,
        accel: Option<&crate::core::config::acceleration::AccelerationConfig>,
    ) -> Result<Arc<OcrLite>> {
        let tier = &config.model_tier;
        let version = &config.model_version;
        let resolved = self.model_manager.resolve_rec_model_versioned(version, family, tier)?;
        let accel_key = match accel.map(|a| &a.provider) {
            Some(crate::core::config::acceleration::ExecutionProviderType::Cuda) => "cuda",
            Some(crate::core::config::acceleration::ExecutionProviderType::TensorRt) => "tensorrt",
            Some(crate::core::config::acceleration::ExecutionProviderType::CoreMl) => "coreml",
            Some(crate::core::config::acceleration::ExecutionProviderType::Auto) => "auto",
            Some(crate::core::config::acceleration::ExecutionProviderType::Cpu) | None => "cpu",
        };
        let pool_key = format!("{version}/{tier}/{}/{accel_key}", resolved.model_key);

        {
            let pool = self.engine_pool.lock().map_err(|e| crate::XbergError::Plugin {
                message: format!("Failed to acquire engine pool lock: {e}"),
                plugin_name: "paddle-ocr".to_string(),
            })?;
            if let Some(engine) = pool.get(&pool_key) {
                return Ok(Arc::clone(engine));
            }
        }

        let shared = self.get_or_init_shared_paths(config)?;

        crate::ort_discovery::ensure_ort_available();

        tracing::info!(family, model_key = %resolved.model_key, tier, "Initializing PaddleOCR engine");

        let mut ocr_lite = OcrLite::new();

        let det_model_path = Self::find_onnx_model(&shared.det_model)?;
        let cls_model_path = Self::find_onnx_model(&shared.cls_model)?;
        let rec_model_path = Self::find_onnx_model(&resolved.model_dir)?;

        let num_threads = 1;

        let dict_path = resolved.dict_file.to_str().ok_or_else(|| crate::XbergError::Ocr {
            message: "Invalid dictionary file path".to_string(),
            source: None,
        })?;

        // NOTE: The thread-local is set by `process_image` from the per-call
        let builder_fn: Option<
            fn(
                ort::session::builder::SessionBuilder,
            ) -> std::result::Result<ort::session::builder::SessionBuilder, ort::Error>,
        > = if PADDLE_TL_ACCEL.with(|cell| cell.borrow().is_some()) {
            Some(paddle_accel_builder_fn)
        } else {
            None
        };

        ocr_lite
            .init_models_with_dict_custom(
                det_model_path.to_str().ok_or_else(|| crate::XbergError::Ocr {
                    message: "Invalid detection model path".to_string(),
                    source: None,
                })?,
                cls_model_path.to_str().ok_or_else(|| crate::XbergError::Ocr {
                    message: "Invalid classification model path".to_string(),
                    source: None,
                })?,
                rec_model_path.to_str().ok_or_else(|| crate::XbergError::Ocr {
                    message: "Invalid recognition model path".to_string(),
                    source: None,
                })?,
                dict_path,
                num_threads,
                builder_fn,
            )
            .map_err(|e| crate::XbergError::Ocr {
                message: format!(
                    "Failed to initialize PaddleOCR models for {family} ({}): {e}",
                    resolved.model_key
                ),
                source: None,
            })?;

        tracing::info!(family, model_key = %resolved.model_key, "PaddleOCR engine initialized successfully");

        let engine = Arc::new(ocr_lite);

        let mut pool = self.engine_pool.lock().map_err(|e| crate::XbergError::Plugin {
            message: format!("Failed to acquire engine pool lock: {e}"),
            plugin_name: "paddle-ocr".to_string(),
        })?;

        if let Some(existing_engine) = pool.get(&pool_key) {
            return Ok(Arc::clone(existing_engine));
        }

        pool.insert(pool_key, Arc::clone(&engine));

        Ok(engine)
    }

    /// Find the ONNX model file within a model directory.
    fn find_onnx_model(model_dir: &std::path::Path) -> Result<std::path::PathBuf> {
        if model_dir.is_file() && model_dir.extension().is_some_and(|extension| extension == "onnx") {
            return Ok(model_dir.to_path_buf());
        }
        if !model_dir.exists() {
            return Err(crate::XbergError::Ocr {
                message: format!("Model directory does not exist: {:?}", model_dir),
                source: None,
            });
        }

        let standard_path = model_dir.join("model.onnx");
        if standard_path.exists() {
            return Ok(standard_path);
        }

        let entries = std::fs::read_dir(model_dir).map_err(|e| crate::XbergError::Ocr {
            message: format!("Failed to read model directory {:?}: {}", model_dir, e),
            source: None,
        })?;

        for entry in entries {
            let entry = entry.map_err(|e| crate::XbergError::Ocr {
                message: format!("Failed to read directory entry: {}", e),
                source: None,
            })?;
            let path = entry.path();
            if path.extension().is_some_and(|ext| ext == "onnx") {
                return Ok(path);
            }
        }

        Err(crate::XbergError::Ocr {
            message: format!("No ONNX model file found in directory: {:?}", model_dir),
            source: None,
        })
    }

    /// Detect document orientation and rotate if needed.
    ///
    fn detect_and_rotate(&self, image: &image::RgbImage) -> Result<RotationOutcome> {
        let detector = self.doc_ori_detector.get_or_try_init(|| {
            let cache_dir = self.config.resolve_cache_dir();
            Ok::<_, crate::XbergError>(crate::doc_orientation::DocOrientationDetector::with_acceleration(
                cache_dir,
                self.acceleration.clone(),
            ))
        })?;

        let orientation = detector.detect(image)?;
        tracing::debug!(
            degrees = orientation.degrees,
            confidence = orientation.confidence,
            "Document orientation detected for PaddleOCR"
        );
        rotate_for_detected_orientation(image, orientation)
    }

    /// Perform OCR on image bytes using the appropriate script family engine.
    async fn do_ocr(
        &self,
        image_bytes: &[u8],
        language: &str,
        effective_config: Arc<PaddleOcrConfig>,
        accel: Option<&crate::core::config::acceleration::AccelerationConfig>,
    ) -> Result<(String, Vec<OcrElement>, u32, u32)> {
        let family = language_to_script_family(language);
        let engine = self.get_or_init_engine_for_family(family, &effective_config, accel)?;

        let image_bytes_owned = image_bytes.to_vec();
        let config = effective_config;

        let (text_blocks, processed_width, processed_height) = tokio::task::spawn_blocking(move || {
            catch_unwind(std::panic::AssertUnwindSafe(|| {
                Self::perform_ocr(&image_bytes_owned, &engine, &config)
            }))
            .map_err(|_| crate::XbergError::Plugin {
                message: "PaddleOCR inference panicked (ONNX Runtime error)".to_string(),
                plugin_name: "paddle-ocr".to_string(),
            })?
        })
        .await
        .map_err(|e| crate::XbergError::Plugin {
            message: format!("PaddleOCR task panicked: {}", e),
            plugin_name: "paddle-ocr".to_string(),
        })??;

        let ocr_elements: Result<Vec<OcrElement>> = text_blocks
            .iter()
            .map(|block| text_block_to_element(block, 1))
            .filter_map(|result| result.transpose())
            .collect();

        let ocr_elements = ocr_elements?;

        let text = text_blocks
            .iter()
            .map(|block| block.text.as_str())
            .filter(|t| !t.is_empty())
            .collect::<Vec<_>>()
            .join("\n\n");

        Ok((text, ocr_elements, processed_width, processed_height))
    }

    /// Perform actual OCR inference (runs in blocking context).
    /// OcrLite::detect takes &self — no Mutex needed, enabling true parallel page OCR.
    fn effective_rec_batch_size(config: &PaddleOcrConfig) -> u32 {
        config
            .rec_batch_num
            .clamp(MIN_RECOGNITION_BATCH_SIZE, MAX_RECOGNITION_BATCH_SIZE)
    }

    fn perform_ocr(
        image_bytes: &[u8],
        ocr_engine: &Arc<OcrLite>,
        config: &PaddleOcrConfig,
    ) -> Result<(Vec<xberg_paddle_ocr::TextBlock>, u32, u32)> {
        let img = crate::extraction::image::load_image_for_ocr(image_bytes)
            .map_err(|e| crate::XbergError::Ocr {
                message: e.to_string(),
                source: None,
            })?
            .to_rgb8();
        let processed_width = img.width();
        let processed_height = img.height();

        let padding = config.padding;
        let max_side_len = config.det_limit_side_len;
        let box_score_thresh = config.det_db_box_thresh;
        let box_thresh = config.det_db_thresh;
        let un_clip_ratio = config.det_db_unclip_ratio;
        let do_angle = config.use_angle_cls;
        let most_angle = false;
        let rec_batch_size = Self::effective_rec_batch_size(config);

        let result = ocr_engine
            .detect_with_rec_batch_size(
                &img,
                padding,
                max_side_len,
                box_score_thresh,
                box_thresh,
                un_clip_ratio,
                do_angle,
                most_angle,
                rec_batch_size,
            )
            .map_err(|e| crate::XbergError::Ocr {
                message: format!("PaddleOCR detection failed: {}", e),
                source: None,
            })?;

        let drop_score = config.drop_score;
        let text_blocks: Vec<_> = result
            .text_blocks
            .into_iter()
            .filter(|block| block.text_score >= drop_score && !block.text_score.is_nan())
            .collect();

        tracing::debug!(text_block_count = text_blocks.len(), "PaddleOCR detection completed");

        Ok((text_blocks, processed_width, processed_height))
    }
}

impl Plugin for PaddleOcrBackend {
    fn name(&self) -> &str {
        "paddle-ocr"
    }

    fn version(&self) -> String {
        env!("CARGO_PKG_VERSION").to_string()
    }

    fn initialize(&self) -> Result<()> {
        Ok(())
    }

    fn shutdown(&self) -> Result<()> {
        Ok(())
    }
}

#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
impl OcrBackend for PaddleOcrBackend {
    async fn process_image(&self, image_bytes: &[u8], config: &OcrConfig) -> Result<ExtractedDocument> {
        if image_bytes.is_empty() {
            return Err(crate::XbergError::Validation {
                message: "Empty image data provided to PaddleOCR".to_string(),
                source: None,
            });
        }

        PADDLE_TL_ACCEL.with(|cell| {
            *cell.borrow_mut() = config.acceleration.clone();
        });

        let effective_config: Arc<PaddleOcrConfig> = if let Some(ref paddle_json) = config.paddle_ocr_config {
            let overridden: PaddleOcrConfig =
                serde_json::from_value(paddle_json.clone()).map_err(|e| crate::XbergError::Validation {
                    message: format!("Failed to deserialize paddle_ocr_config: {}", e),
                    source: None,
                })?;
            Arc::new(overridden)
        } else {
            Arc::clone(&self.config)
        };

        let languages = config.effective_languages();
        let (paddle_lang, language_warnings) = super::select_paddle_language(&languages);

        let mut rotation_outcome = None;
        let ocr_image_bytes: Cow<'_, [u8]> = if config.auto_rotate {
            let decoded_image = crate::extraction::image::load_image_for_ocr(image_bytes)
                .map_err(|error| crate::XbergError::Ocr {
                    message: format!("Failed to decode PaddleOCR image for orientation detection: {error}"),
                    source: None,
                })?
                .to_rgb8();
            match self.detect_and_rotate(&decoded_image) {
                Ok(outcome) => {
                    rotation_outcome = Some(outcome);
                }
                Err(e) => {
                    tracing::warn!("Doc orientation detection failed, proceeding without rotation: {e}");
                    rotation_outcome = Some(RotationOutcome::unrotated(
                        decoded_image.width(),
                        decoded_image.height(),
                    ));
                }
            }
            match rotation_outcome
                .as_ref()
                .and_then(|outcome| outcome.rotated_bytes.as_deref())
            {
                Some(rotated) => Cow::Borrowed(rotated),
                None => Cow::Borrowed(image_bytes),
            }
        } else {
            Cow::Borrowed(image_bytes)
        };

        let effective_accel = self.resolve_acceleration(config.acceleration.as_ref());

        let (text, ocr_elements, processed_width, processed_height) = self
            .do_ocr(
                &ocr_image_bytes,
                paddle_lang,
                Arc::clone(&effective_config),
                effective_accel.as_ref(),
            )
            .await?;
        let rotation_outcome =
            rotation_outcome.unwrap_or_else(|| RotationOutcome::unrotated(processed_width, processed_height));

        let text_blocks_count = ocr_elements.len();

        let ocr_doc = {
            use crate::types::extraction::BoundingBox;
            use crate::types::internal::{ElementKind, InternalDocument, InternalElement};
            use crate::types::ocr_elements::OcrElementLevel;

            let mut doc = InternalDocument::new("pdf");
            for elem in &ocr_elements {
                let (left, top, width, height) = elem.geometry.to_aabb();
                let bbox = BoundingBox {
                    x0: left as f64,
                    y0: top as f64,
                    x1: (left + width) as f64,
                    y1: (top + height) as f64,
                };
                let mut ie = InternalElement::text(
                    ElementKind::OcrText {
                        level: OcrElementLevel::Line,
                    },
                    &elem.text,
                    0,
                )
                .with_page(elem.page_number);
                ie.bbox = Some(bbox);
                ie.ocr_confidence = Some(elem.confidence.clone());
                ie.ocr_geometry = Some(elem.geometry.clone());
                doc.push_element(ie);
            }
            doc
        };

        tracing::debug!(
            text_blocks = text_blocks_count,
            ocr_elements = ocr_elements.len(),
            internal_doc_elements = ocr_doc.elements.len(),
            "PaddleOCR InternalDocument built"
        );

        let mut tables: Vec<Table> = vec![];
        let mut table_count = 0;
        let mut table_rows: Option<u32> = None;
        let mut table_cols: Option<u32> = None;

        if effective_config.enable_table_detection && !ocr_elements.is_empty() {
            let words = elements_to_hocr_words(&ocr_elements, 0.3);

            if !words.is_empty() {
                let cells = reconstruct_table(&words, 20, 0.5);

                if !cells.is_empty() {
                    table_count = 1;
                    table_rows = Some(cells.len() as u32);
                    table_cols = cells.first().map(|row| row.len() as u32);

                    let table_markdown = table_to_markdown(&cells);

                    tables.push(Table {
                        cells,
                        markdown: table_markdown,
                        page_number: 1,
                        bounding_box: None,
                        ..Default::default()
                    });
                }
            }
        }

        let metadata = Metadata {
            format: Some(FormatMetadata::Ocr(OcrMetadata {
                language: paddle_lang.to_string(),
                psm: 3,
                output_format: "text".to_string(),
                table_count,
                table_rows,
                table_cols,
            })),
            additional: image_metadata(&rotation_outcome),
            ..Default::default()
        };

        let include_elements = config.element_config.as_ref().is_some_and(|ec| ec.include_elements);

        let ocr_elements_opt = if include_elements && !ocr_elements.is_empty() {
            Some(ocr_elements)
        } else {
            None
        };

        Ok(ExtractedDocument {
            content: text,
            mime_type: Cow::Borrowed("text/plain"),
            metadata,
            tables,
            detected_languages: Some(languages),
            ocr_elements: ocr_elements_opt,
            ocr_internal_document: Some(ocr_doc),
            processing_warnings: language_warnings,
            ..Default::default()
        })
    }

    async fn process_image_file(&self, path: &Path, config: &OcrConfig) -> Result<ExtractedDocument> {
        let bytes = tokio::fs::read(path).await?;
        self.process_image(&bytes, config).await
    }

    fn supports_language(&self, lang: &str) -> bool {
        is_language_supported(lang) || map_language_code(lang).is_some()
    }

    fn backend_type(&self) -> OcrBackendType {
        OcrBackendType::PaddleOCR
    }

    fn supported_languages(&self) -> Vec<String> {
        super::SUPPORTED_LANGUAGES.iter().map(|s| s.to_string()).collect()
    }

    fn supports_table_detection(&self) -> bool {
        self.config.enable_table_detection
    }
}

impl Default for PaddleOcrBackend {
    fn default() -> Self {
        Self::with_config(PaddleOcrConfig::default())
            .unwrap_or_else(|e| panic!("Failed to create default PaddleOcrBackend: {}", e))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_paddle_ocr_backend_creation() {
        let result = PaddleOcrBackend::new();
        assert!(result.is_ok(), "Failed to create PaddleOCR backend");
    }

    #[test]
    fn test_paddle_ocr_backend_with_config() {
        let config = PaddleOcrConfig::default();
        let result = PaddleOcrBackend::with_config(config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_effective_rec_batch_size_enforces_bounds() {
        let cases = [
            (0, MIN_RECOGNITION_BATCH_SIZE),
            (PaddleOcrConfig::default().rec_batch_num, DEFAULT_RECOGNITION_BATCH_SIZE),
            (12, 12),
            (u32::MAX, MAX_RECOGNITION_BATCH_SIZE),
        ];

        for (configured, expected) in cases {
            let config = PaddleOcrConfig {
                rec_batch_num: configured,
                ..Default::default()
            };

            assert_eq!(
                PaddleOcrBackend::effective_rec_batch_size(&config),
                expected,
                "unexpected effective recognition batch size for configured value {configured}"
            );
        }
    }

    #[test]
    fn test_unrotated_image_metadata_uses_original_dimensions() {
        let image = image::RgbImage::new(3, 2);
        let outcome = rotate_for_detected_orientation(
            &image,
            crate::doc_orientation::OrientationResult {
                degrees: 0,
                confidence: 1.0,
            },
        )
        .expect("zero-degree orientation should not require a model or fail");

        assert!(outcome.rotated_bytes.is_none());
        assert_eq!((outcome.processed_width, outcome.processed_height), (3, 2));

        let metadata = image_metadata(&outcome);
        assert_eq!(
            metadata.get(crate::ocr::OCR_PROCESSED_IMAGE_WIDTH_METADATA_KEY),
            Some(&serde_json::json!(3))
        );
        assert_eq!(
            metadata.get(crate::ocr::OCR_PROCESSED_IMAGE_HEIGHT_METADATA_KEY),
            Some(&serde_json::json!(2))
        );
        assert_eq!(
            metadata.get(crate::ocr::OCR_ORIENTATION_DEGREES_METADATA_KEY),
            Some(&serde_json::json!(0))
        );
        assert!(!metadata.contains_key(crate::ocr::OCR_AUTO_ROTATED_METADATA_KEY));
    }

    #[test]
    fn test_rotated_image_metadata_and_geometry_use_corrected_space() {
        let mut image = image::RgbImage::new(3, 2);
        let marker = image::Rgb([17, 31, 47]);
        image.put_pixel(0, 0, marker);

        let outcome = rotate_for_detected_orientation(
            &image,
            crate::doc_orientation::OrientationResult {
                degrees: 90,
                confidence: 1.0,
            },
        )
        .expect("in-memory rotation should succeed");

        assert_eq!((outcome.processed_width, outcome.processed_height), (2, 3));
        let rotated = image::load_from_memory(outcome.rotated_bytes.as_deref().expect("rotation should produce bytes"))
            .expect("rotated PNG should decode")
            .to_rgb8();
        assert_eq!(rotated.dimensions(), (2, 3));
        assert_eq!(*rotated.get_pixel(0, 2), marker);

        let metadata = image_metadata(&outcome);
        assert_eq!(
            metadata.get(crate::ocr::OCR_PROCESSED_IMAGE_WIDTH_METADATA_KEY),
            Some(&serde_json::json!(2))
        );
        assert_eq!(
            metadata.get(crate::ocr::OCR_PROCESSED_IMAGE_HEIGHT_METADATA_KEY),
            Some(&serde_json::json!(3))
        );
        assert_eq!(
            metadata.get(crate::ocr::OCR_ORIENTATION_DEGREES_METADATA_KEY),
            Some(&serde_json::json!(90))
        );
        assert_eq!(
            metadata.get(crate::ocr::OCR_AUTO_ROTATED_METADATA_KEY),
            Some(&serde_json::json!(true))
        );
    }

    #[test]
    fn test_paddle_ocr_language_support_direct() {
        let backend = PaddleOcrBackend::new().unwrap();

        assert!(backend.supports_language("ch"));
        assert!(backend.supports_language("en"));
        assert!(backend.supports_language("japan"));
        assert!(backend.supports_language("korean"));
        assert!(backend.supports_language("french"));
        assert!(backend.supports_language("thai"));
        assert!(backend.supports_language("greek"));
    }

    #[test]
    fn test_paddle_ocr_language_support_mapped() {
        let backend = PaddleOcrBackend::new().unwrap();

        assert!(backend.supports_language("chi_sim"));
        assert!(backend.supports_language("eng"));
        assert!(backend.supports_language("jpn"));
        assert!(backend.supports_language("kor"));
        assert!(backend.supports_language("fra"));
        assert!(backend.supports_language("zho"));
        assert!(backend.supports_language("tha"));
        assert!(backend.supports_language("ell"));
        assert!(backend.supports_language("rus"));
    }

    #[test]
    fn test_paddle_ocr_language_unsupported() {
        let backend = PaddleOcrBackend::new().unwrap();

        assert!(!backend.supports_language("xyz"));
        assert!(!backend.supports_language("invalid"));
    }

    #[test]
    fn test_paddle_ocr_plugin_interface() {
        let backend = PaddleOcrBackend::new().unwrap();

        assert_eq!(backend.name(), "paddle-ocr");
        assert!(!backend.version().is_empty());
        assert!(backend.initialize().is_ok());
        assert!(backend.shutdown().is_ok());
    }

    #[test]
    fn test_paddle_ocr_backend_type() {
        let backend = PaddleOcrBackend::new().unwrap();
        assert_eq!(backend.backend_type(), OcrBackendType::PaddleOCR);
    }

    #[test]
    fn test_paddle_ocr_supported_languages() {
        let backend = PaddleOcrBackend::new().unwrap();
        let languages = backend.supported_languages();

        assert!(!languages.is_empty());
        assert!(languages.contains(&"ch".to_string()));
        assert!(languages.contains(&"en".to_string()));
        assert!(languages.contains(&"thai".to_string()));
        assert!(languages.contains(&"greek".to_string()));
    }

    #[test]
    fn test_paddle_ocr_table_detection_disabled_by_default() {
        let backend = PaddleOcrBackend::new().unwrap();
        assert!(!backend.supports_table_detection());
    }

    #[test]
    fn test_paddle_ocr_table_detection_enabled() {
        let config = PaddleOcrConfig::default().with_table_detection(true);
        let backend = PaddleOcrBackend::with_config(config).unwrap();
        assert!(backend.supports_table_detection());
    }

    #[test]
    fn test_paddle_ocr_default() {
        let backend = PaddleOcrBackend::default();
        assert_eq!(backend.name(), "paddle-ocr");
    }

    #[tokio::test]
    async fn test_paddle_ocr_process_empty_image() {
        let backend = PaddleOcrBackend::new().unwrap();
        let config = OcrConfig {
            backend: "paddle-ocr".to_string(),
            language: vec!["ch".to_string()],
            ..Default::default()
        };

        let result = backend.process_image(&[], &config).await;
        assert!(result.is_err(), "Should error on empty image");
    }

    #[test]
    fn test_internal_document_from_text_blocks() {
        use crate::ocr::conversion::text_block_to_element;
        use crate::types::extraction::BoundingBox;
        use crate::types::internal::{ElementKind, InternalDocument, InternalElement};
        use crate::types::ocr_elements::OcrElementLevel;

        let blocks = [
            xberg_paddle_ocr::TextBlock {
                text: "Hello World".to_string(),
                box_points: vec![
                    xberg_paddle_ocr::Point { x: 10, y: 10 },
                    xberg_paddle_ocr::Point { x: 200, y: 10 },
                    xberg_paddle_ocr::Point { x: 200, y: 50 },
                    xberg_paddle_ocr::Point { x: 10, y: 50 },
                ],
                box_score: 0.95,
                text_score: 0.92,
                angle_index: 0,
                angle_score: 0.99,
            },
            xberg_paddle_ocr::TextBlock {
                text: "Second line".to_string(),
                box_points: vec![
                    xberg_paddle_ocr::Point { x: 10, y: 60 },
                    xberg_paddle_ocr::Point { x: 300, y: 60 },
                    xberg_paddle_ocr::Point { x: 300, y: 100 },
                    xberg_paddle_ocr::Point { x: 10, y: 100 },
                ],
                box_score: 0.88,
                text_score: 0.85,
                angle_index: 0,
                angle_score: 0.97,
            },
        ];

        let ocr_elements: Vec<OcrElement> = blocks
            .iter()
            .map(|block| text_block_to_element(block, 1))
            .filter_map(|result| result.transpose())
            .collect::<crate::Result<Vec<_>>>()
            .expect("text_block_to_element should succeed");

        assert_eq!(ocr_elements.len(), 2, "Should produce 2 OcrElements");

        let mut doc = InternalDocument::new("pdf");
        for elem in &ocr_elements {
            let (left, top, width, height) = elem.geometry.to_aabb();
            let bbox = BoundingBox {
                x0: left as f64,
                y0: top as f64,
                x1: (left + width) as f64,
                y1: (top + height) as f64,
            };
            let mut ie = InternalElement::text(
                ElementKind::OcrText {
                    level: OcrElementLevel::Line,
                },
                &elem.text,
                0,
            )
            .with_page(elem.page_number);
            ie.bbox = Some(bbox);
            ie.ocr_confidence = Some(elem.confidence.clone());
            ie.ocr_geometry = Some(elem.geometry.clone());
            doc.push_element(ie);
        }

        for ie in &doc.elements {
            assert!(
                matches!(
                    ie.kind,
                    ElementKind::OcrText {
                        level: OcrElementLevel::Line
                    }
                ),
                "Element kind should be OcrText with Line level"
            );
        }

        let first_bbox = doc.elements[0].bbox.as_ref().expect("First element should have bbox");
        assert_eq!(first_bbox.x0, 10.0, "left should be min x of quad points");
        assert_eq!(first_bbox.y0, 10.0, "top should be min y of quad points");
        assert_eq!(first_bbox.x1, 200.0, "right should be left + width");
        assert_eq!(first_bbox.y1, 50.0, "bottom should be top + height");

        let second_bbox = doc.elements[1].bbox.as_ref().expect("Second element should have bbox");
        assert_eq!(second_bbox.x0, 10.0);
        assert_eq!(second_bbox.y0, 60.0);
        assert_eq!(second_bbox.x1, 300.0);
        assert_eq!(second_bbox.y1, 100.0);

        let first_conf = doc.elements[0]
            .ocr_confidence
            .as_ref()
            .expect("First element should have confidence");
        assert!(
            (first_conf.detection.unwrap() - 0.95).abs() < 1e-6,
            "Detection confidence should be ~0.95, got {}",
            first_conf.detection.unwrap()
        );
        assert!(
            (first_conf.recognition - 0.92).abs() < 1e-6,
            "Recognition confidence should be ~0.92, got {}",
            first_conf.recognition
        );

        assert_eq!(doc.elements[0].page, Some(1));
        assert_eq!(doc.elements[1].page, Some(1));
    }

    /// Regression test for #783: verifies that `process_image` sets `PADDLE_TL_ACCEL`
    /// from `OcrConfig::acceleration` so that ONNX session builders can apply the
    /// requested execution provider (e.g. CUDA).
    ///
    /// This is a unit test of the threading mechanism only — it does not create
    /// real ONNX sessions or require a GPU.
    #[test]
    fn test_paddle_accel_tl_set_from_ocr_config_acceleration() {
        use crate::core::config::AccelerationConfig;

        PADDLE_TL_ACCEL.with(|cell| {
            *cell.borrow_mut() = Some(AccelerationConfig {
                provider: crate::core::config::acceleration::ExecutionProviderType::Cpu,
                device_id: 0,
            });
        });

        let accel: Option<AccelerationConfig> = None;
        PADDLE_TL_ACCEL.with(|cell| {
            *cell.borrow_mut() = accel.clone();
        });
        let tl_value = PADDLE_TL_ACCEL.with(|cell| cell.borrow().clone());
        assert!(tl_value.is_none(), "TL should be cleared when acceleration is None");

        let cuda_accel = AccelerationConfig {
            provider: crate::core::config::acceleration::ExecutionProviderType::Cuda,
            device_id: 0,
        };
        PADDLE_TL_ACCEL.with(|cell| {
            *cell.borrow_mut() = Some(cuda_accel.clone());
        });
        let tl_value = PADDLE_TL_ACCEL.with(|cell| cell.borrow().clone());
        assert!(tl_value.is_some(), "TL should be set when acceleration is Some");
        assert_eq!(
            tl_value.unwrap().provider,
            crate::core::config::acceleration::ExecutionProviderType::Cuda,
            "TL provider should be Cuda"
        );

        PADDLE_TL_ACCEL.with(|cell| {
            *cell.borrow_mut() = None;
        });
    }
}