Skip to main content

easypdf_markdown/ocr/
config.rs

1//! OCR 配置与触发策略。
2
3/// OCR 处理器配置。
4///
5/// 控制渲染 DPI、OCR 触发条件和质量阈值。
6///
7/// # Examples
8///
9/// ```
10/// use easypdf_markdown::ocr::{OcrConfig, OcrTrigger};
11///
12/// let config = OcrConfig {
13///     render_dpi: 300,
14///     trigger: OcrTrigger::Always,
15///     min_confidence: 0.8,
16///     ..OcrConfig::default()
17/// };
18/// assert_eq!(config.render_dpi, 300);
19/// ```
20#[derive(Debug, Clone)]
21pub struct OcrConfig {
22    /// 页面转图像的渲染 DPI。默认值:200。
23    ///
24    /// 值越高 OCR 准确度越好,但内存占用和处理时间也越大。
25    /// 200 DPI 对大多数文档是较好的平衡点。
26    pub render_dpi: u32,
27
28    /// OCR 触发条件。默认值:[`OcrTrigger::OnEmptyPage`]。
29    pub trigger: OcrTrigger,
30
31    /// 从 OCR 结果中保留的最小文本长度。默认值:0(全部保留)。
32    ///
33    /// 短于此阈值的 OCR 结果将被视为噪声而丢弃。
34    pub min_text_length: usize,
35
36    /// 最小置信度阈值。默认值:0.5。
37    ///
38    /// 置信度低于此值的 OCR 结果将生成警告。
39    pub min_confidence: f32,
40}
41
42impl Default for OcrConfig {
43    fn default() -> Self {
44        Self {
45            render_dpi: 200,
46            trigger: OcrTrigger::OnEmptyPage,
47            min_text_length: 0,
48            min_confidence: 0.5,
49        }
50    }
51}
52
53/// OCR 触发条件。
54///
55/// # Examples
56///
57/// ```
58/// use easypdf_markdown::ocr::OcrTrigger;
59///
60/// let trigger = OcrTrigger::WhenTextSparse { threshold: 0.3 };
61/// assert!(matches!(trigger, OcrTrigger::WhenTextSparse { threshold } if threshold == 0.3));
62/// ```
63#[derive(Debug, Clone, Copy, PartialEq, Default)]
64#[non_exhaustive]
65pub enum OcrTrigger {
66    /// 始终对每一页执行 OCR。
67    Always,
68
69    /// 仅在页面缺少可提取的原生文本块时执行 OCR。
70    ///
71    /// 这是默认值,也是主要用例:扫描件 PDF 中文本提取器返回空页面时触发。
72    #[default]
73    OnEmptyPage,
74
75    /// 当文本块占总块数的比例低于阈值时执行 OCR。
76    ///
77    /// `threshold` 取值范围为 `0.0..=1.0`。当
78    /// `(text_block_count / total_block_count) < threshold` 时视为文本稀疏。
79    WhenTextSparse {
80        /// 文本块与总块数的比例阈值(0.0 到 1.0)。
81        threshold: f32,
82    },
83}