docparser-core 0.1.0

docparser 独立解析核心:IR / 统一错误 / 能力 trait / Registry / Router / Policy(零 native 依赖)
Documentation
//! 能力抽象(与 Python `capability.py` 对齐):
//! 解析能力(格式绑定)→ RawDoc;处理能力(全局共享,就地增强)。

use std::fmt;

use crate::error::Result;
use crate::model::Rect;

/// 解析产出的原始文本项:text + 可选 bbox。
#[derive(Debug, Clone, Default)]
pub struct RawTextItem {
    pub text: String,
    pub bbox: Option<Rect>,
}

/// 解析产出的原始图片(可携带 OCR 结果)。
#[derive(Debug, Clone, Default)]
pub struct RawImage {
    pub data: Vec<u8>,
    pub bbox: Option<Rect>,
    pub ext: String,
    /// 内嵌位图像素尺寸(宽, 高);装饰图过滤 < 50px 用(对齐 Python `px_size`)
    pub px: Option<(u32, u32)>,
    /// 嵌入图 OCR 文本(未识别为 None;与 Python `meta["ocr_text"]` 对齐)
    pub ocr_text: Option<String>,
}

#[derive(Debug, Clone, Default)]
pub struct RawPage {
    pub name: Option<String>,
    pub items: Vec<RawTextItem>,
    pub images: Vec<RawImage>,
    pub width: Option<f32>,
    pub height: Option<f32>,
    pub rotation: Option<i32>,
    /// 解析即已得到的表格结构 rows × cells
    pub tables: Vec<Vec<Vec<String>>>,
}

/// 解析能力的输出:尚未经过处理能力。
#[derive(Debug, Clone, Default)]
pub struct RawDoc {
    pub pages: Vec<RawPage>,
    pub meta: std::collections::HashMap<String, String>,
    pub needs_ocr: bool,
}

/// 能力实现形态。
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BackendKind {
    Bundled,
    External,
    Composite,
}

impl BackendKind {
    pub fn as_str(&self) -> &'static str {
        match self {
            BackendKind::Bundled => "bundled",
            BackendKind::External => "external",
            BackendKind::Composite => "composite",
        }
    }
}

impl fmt::Display for BackendKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(self.as_str())
    }
}

/// 解析能力:格式绑定,把文件读成 RawDoc。
pub trait ParseCapability: Send + Sync {
    fn id(&self) -> &str;
    fn formats(&self) -> &[&str];
    fn kind(&self) -> BackendKind {
        BackendKind::Bundled
    }
    fn is_available(&self) -> bool {
        true
    }
    fn parse(&self, path: &str) -> Result<RawDoc>;
}

/// 处理能力:全局共享,就地增强 RawDoc(OCR / layout)。
pub trait ProcessCapability: Send + Sync {
    fn id(&self) -> &str;
    fn is_available(&self) -> bool {
        true
    }
    fn should_apply(&self, _raw: &RawDoc) -> bool {
        true
    }
    fn process(&self, raw: &mut RawDoc) -> Result<()>;
}

/// 文档插件:某文件类型的完整处理器(组装 RawDoc → IR Document)。
pub trait FormatPlugin: Send + Sync {
    fn id(&self) -> &str;
    fn formats(&self) -> &[&str];
    fn default_parse_chain(&self) -> Vec<&'static str>;
    fn default_process_chain(&self) -> Vec<&'static str>;
    fn assemble(&self, raw: &RawDoc) -> crate::model::Document;
}