Skip to main content

docparser_core/
plugin.rs

1//! 能力抽象(与 Python `capability.py` 对齐):
2//! 解析能力(格式绑定)→ RawDoc;处理能力(全局共享,就地增强)。
3
4use std::fmt;
5
6use crate::error::Result;
7use crate::model::Rect;
8
9/// 解析产出的原始文本项:text + 可选 bbox。
10#[derive(Debug, Clone, Default)]
11pub struct RawTextItem {
12    pub text: String,
13    pub bbox: Option<Rect>,
14}
15
16/// 解析产出的原始图片(可携带 OCR 结果)。
17#[derive(Debug, Clone, Default)]
18pub struct RawImage {
19    pub data: Vec<u8>,
20    pub bbox: Option<Rect>,
21    pub ext: String,
22    /// 内嵌位图像素尺寸(宽, 高);装饰图过滤 < 50px 用(对齐 Python `px_size`)
23    pub px: Option<(u32, u32)>,
24    /// 嵌入图 OCR 文本(未识别为 None;与 Python `meta["ocr_text"]` 对齐)
25    pub ocr_text: Option<String>,
26}
27
28#[derive(Debug, Clone, Default)]
29pub struct RawPage {
30    pub name: Option<String>,
31    pub items: Vec<RawTextItem>,
32    pub images: Vec<RawImage>,
33    pub width: Option<f32>,
34    pub height: Option<f32>,
35    pub rotation: Option<i32>,
36    /// 解析即已得到的表格结构 rows × cells
37    pub tables: Vec<Vec<Vec<String>>>,
38}
39
40/// 解析能力的输出:尚未经过处理能力。
41#[derive(Debug, Clone, Default)]
42pub struct RawDoc {
43    pub pages: Vec<RawPage>,
44    pub meta: std::collections::HashMap<String, String>,
45    pub needs_ocr: bool,
46}
47
48/// 能力实现形态。
49#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum BackendKind {
51    Bundled,
52    External,
53    Composite,
54}
55
56impl BackendKind {
57    pub fn as_str(&self) -> &'static str {
58        match self {
59            BackendKind::Bundled => "bundled",
60            BackendKind::External => "external",
61            BackendKind::Composite => "composite",
62        }
63    }
64}
65
66impl fmt::Display for BackendKind {
67    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
68        f.write_str(self.as_str())
69    }
70}
71
72/// 解析能力:格式绑定,把文件读成 RawDoc。
73pub trait ParseCapability: Send + Sync {
74    fn id(&self) -> &str;
75    fn formats(&self) -> &[&str];
76    fn kind(&self) -> BackendKind {
77        BackendKind::Bundled
78    }
79    fn is_available(&self) -> bool {
80        true
81    }
82    fn parse(&self, path: &str) -> Result<RawDoc>;
83}
84
85/// 处理能力:全局共享,就地增强 RawDoc(OCR / layout)。
86pub trait ProcessCapability: Send + Sync {
87    fn id(&self) -> &str;
88    fn is_available(&self) -> bool {
89        true
90    }
91    fn should_apply(&self, _raw: &RawDoc) -> bool {
92        true
93    }
94    fn process(&self, raw: &mut RawDoc) -> Result<()>;
95}
96
97/// 文档插件:某文件类型的完整处理器(组装 RawDoc → IR Document)。
98pub trait FormatPlugin: Send + Sync {
99    fn id(&self) -> &str;
100    fn formats(&self) -> &[&str];
101    fn default_parse_chain(&self) -> Vec<&'static str>;
102    fn default_process_chain(&self) -> Vec<&'static str>;
103    fn assemble(&self, raw: &RawDoc) -> crate::model::Document;
104}