Skip to content

A fast, helpful, and open-source document parser

nit

Logan Markewich618030265425
diff --git a/crates/liteparse/README.md b/crates/liteparse/README.md
index a0ca9af..0d6f168 100644
--- a/crates/liteparse/README.md
+++ b/crates/liteparse/README.md
@@ -161,10 +161,28 @@ let parser = LiteParse::new(LiteParseConfig::default())
# Ok::<(), Box<dyn std::error::Error>>(())
```
-For opt-in model downloads, enable `oar-ocr-auto-download` and pass registered
-bare file names to the same constructor. On first use, `oar-ocr` downloads the
-files from ModelScope, verifies their SHA-256 digests, and caches them under
-`$OAR_HOME` (default `~/.oar`):
+For opt-in model downloads, enable `oar-ocr-auto-download` and use a preset. On
+first use, `oar-ocr` downloads the detection model, recognition model, and
+matching dictionary from ModelScope, verifies their SHA-256 digests, and caches
+them under `$OAR_HOME` (default `~/.oar`):
+
+```rust,no_run
+use liteparse::ocr::oar::OarOcrEngine;
+
+// Smallest / fastest PP-OCRv6 configuration.
+let engine = OarOcrEngine::ppocr_v6_tiny()?;
+# Ok::<(), Box<dyn std::error::Error>>(())
+```
+
+Presets cover the current and previous PP-OCR generations, from fastest to most
+accurate: `ppocr_v6_tiny`, `ppocr_v6_small`, and `ppocr_v6_medium`. Each wires the correct
+detector/recognizer/dictionary trio. For PP-OCRv4, a language-specific
+recognizer, or a custom mix, use `from_models` with a matching dictionary.
+
+To mix a detector, recognizer, and dictionary yourself, pass registered bare
+file names to `from_models`. Pair the recognizer with its matching dictionary —
+the tiny recognizer needs `ppocrv6_tiny_dict.txt`, while the larger models use
+`ppocrv6_dict.txt`; a mismatched dictionary silently produces garbled text:
```rust,no_run
use liteparse::ocr::oar::OarOcrEngine;
@@ -177,14 +195,16 @@ let engine = OarOcrEngine::from_models(
# Ok::<(), Box<dyn std::error::Error>>(())
```
-The three artifacts stay explicit because detectors, recognizers, and
-dictionaries can be mixed independently. Use `OAROCRBuilder` with
-`OarOcrEngine::from_builder` for model-specific settings or optional orientation
-and rectification models. Both constructors use conservative batch sizes and
+All three artifacts also accept in-memory bytes, so the whole pipeline can be
+embedded with `include_bytes!` rather than shipped as files. Use `OAROCRBuilder`
+with `OarOcrEngine::from_builder` for model-specific settings or optional
+orientation and rectification models. The fallible constructors return
+`liteparse::LiteParseError`. All constructors use conservative batch sizes and
serialize page inference to avoid multiplying inference memory across
concurrently scheduled pages.
`OcrOptions::language` is not interpreted: the recognition model and character
-dictionary define the supported languages.
+dictionary define the supported languages, and a configured `ocr_language`
+triggers a one-time warning to make that explicit.
## Features
diff --git a/crates/liteparse/src/ocr/oar.rs b/crates/liteparse/src/ocr/oar.rs
index 1fa46ce..6461503 100644
--- a/crates/liteparse/src/ocr/oar.rs
+++ b/crates/liteparse/src/ocr/oar.rs
@@ -6,14 +6,82 @@
//! Model selection and licensing remain explicit application decisions.
use std::io;
+use std::path::{Path, PathBuf};
use std::pin::Pin;
-use std::sync::Mutex;
+use std::sync::{Mutex, Once};
pub use oar_ocr::core::ModelSource;
pub use oar_ocr::core::OCRError;
pub use oar_ocr::oarocr::{OAROCR, OAROCRBuilder};
use super::{OcrEngine, OcrOptions, OcrResult};
+use crate::error::LiteParseError;
+
+/// Surface `oar-ocr`'s error type as a LiteParse error so the fallible
+/// constructors return `LiteParseError` like the rest of the crate.
+impl From<OCRError> for LiteParseError {
+ fn from(err: OCRError) -> Self {
+ LiteParseError::Ocr(err.to_string())
+ }
+}
+
+/// Source for the recognition character dictionary: a filesystem path or
+/// in-memory bytes.
+pub enum DictSource {
+ /// A path to a character dictionary file. May be a bare registered file
+ /// name when the `oar-ocr-auto-download` feature is enabled.
+ Path(PathBuf),
+ /// In-memory dictionary bytes, decoded as UTF-8 when the engine is built.
+ Content(Vec<u8>),
+}
+
+impl DictSource {
+ /// The path handed to `OAROCRBuilder::new`. For [`DictSource::Content`] this
+ /// is an empty placeholder: `character_dict_content` takes precedence in
+ /// `oar-ocr`, so the path is never read.
+ fn builder_path(&self) -> PathBuf {
+ match self {
+ DictSource::Path(path) => path.clone(),
+ DictSource::Content(_) => PathBuf::new(),
+ }
+ }
+}
+
+impl From<PathBuf> for DictSource {
+ fn from(path: PathBuf) -> Self {
+ DictSource::Path(path)
+ }
+}
+
+impl From<&Path> for DictSource {
+ fn from(path: &Path) -> Self {
+ DictSource::Path(path.to_path_buf())
+ }
+}
+
+impl From<String> for DictSource {
+ fn from(path: String) -> Self {
+ DictSource::Path(PathBuf::from(path))
+ }
+}
+
+impl From<&str> for DictSource {
+ fn from(path: &str) -> Self {
+ DictSource::Path(PathBuf::from(path))
+ }
+}
+
+impl From<Vec<u8>> for DictSource {
+ fn from(bytes: Vec<u8>) -> Self {
+ DictSource::Content(bytes)
+ }
+}
+
+impl From<&[u8]> for DictSource {
+ fn from(bytes: &[u8]) -> Self {
+ DictSource::Content(bytes.to_vec())
+ }
+}
/// Native ONNX OCR adapter for LiteParse.
///
@@ -30,23 +98,75 @@ pub struct OarOcrEngine {
}
impl OarOcrEngine {
- /// Build an engine from detection, recognition, and dictionary models.
+ /// Build an engine from detection, recognition, and dictionary artifacts.
+ ///
+ /// All three arguments accept local paths or in-memory bytes (models as
+ /// [`ModelSource`], the dictionary as [`DictSource`]), so the whole pipeline
+ /// can be embedded in the binary or loaded from disk. A dictionary path can
+ /// be a bare registered file name when the `oar-ocr-auto-download` feature
+ /// is enabled. Use [`from_builder`](Self::from_builder) to configure optional
+ /// orientation, rectification, or model-specific settings.
///
- /// Model arguments accept local paths or in-memory ONNX bytes. The
- /// dictionary is a path; it can be a bare registered file name when the
- /// `oar-ocr-auto-download` feature is enabled. Use
- /// [`from_builder`](Self::from_builder) to configure optional orientation,
- /// rectification, or model-specific settings.
+ /// The recognizer and dictionary must match: a mismatched dictionary
+ /// silently produces garbled text rather than an error. Prefer a preset such
+ /// as [`ppocr_v6_tiny`](Self::ppocr_v6_tiny) when you want a known-good trio.
pub fn from_models(
text_detection_model: impl Into<ModelSource>,
text_recognition_model: impl Into<ModelSource>,
- character_dict_path: impl Into<std::path::PathBuf>,
- ) -> Result<Self, OCRError> {
- Self::from_builder(OAROCRBuilder::new(
+ character_dict: impl Into<DictSource>,
+ ) -> Result<Self, LiteParseError> {
+ let dict = character_dict.into();
+ let mut builder = OAROCRBuilder::new(
text_detection_model,
text_recognition_model,
- character_dict_path,
- ))
+ dict.builder_path(),
+ );
+ if let DictSource::Content(bytes) = dict {
+ let content = String::from_utf8(bytes).map_err(|err| {
+ LiteParseError::Ocr(format!("character dictionary is not valid UTF-8: {err}"))
+ })?;
+ builder = builder.character_dict_content(content);
+ }
+ Self::from_builder(builder)
+ }
+
+ /// Build the PP-OCRv6 Tiny pipeline, downloading the detection model,
+ /// recognition model, and matching dictionary on first use.
+ #[cfg(feature = "oar-ocr-auto-download")]
+ pub fn ppocr_v6_tiny() -> Result<Self, LiteParseError> {
+ Self::from_models(
+ "pp-ocrv6_tiny_det.onnx",
+ "pp-ocrv6_tiny_rec.onnx",
+ "ppocrv6_tiny_dict.txt",
+ )
+ }
+
+ /// Build the PP-OCRv6 **small** pipeline via auto-download.
+ ///
+ /// Requires the `oar-ocr-auto-download` feature. Trades throughput for
+ /// higher accuracy than [`ppocr_v6_tiny`](Self::ppocr_v6_tiny); the small
+ /// recognizer uses the full `ppocrv6_dict.txt`.
+ #[cfg(feature = "oar-ocr-auto-download")]
+ pub fn ppocr_v6_small() -> Result<Self, LiteParseError> {
+ Self::from_models(
+ "pp-ocrv6_small_det.onnx",
+ "pp-ocrv6_small_rec.onnx",
+ "ppocrv6_dict.txt",
+ )
+ }
+
+ /// Build the PP-OCRv6 **medium** pipeline via auto-download.
+ ///
+ /// Requires the `oar-ocr-auto-download` feature. The most accurate (and
+ /// heaviest) PP-OCRv6 configuration; like [`ppocr_v6_small`](Self::ppocr_v6_small)
+ /// it uses the full `ppocrv6_dict.txt`.
+ #[cfg(feature = "oar-ocr-auto-download")]
+ pub fn ppocr_v6_medium() -> Result<Self, LiteParseError> {
+ Self::from_models(
+ "pp-ocrv6_medium_det.onnx",
+ "pp-ocrv6_medium_rec.onnx",
+ "ppocrv6_dict.txt",
+ )
}
/// Build an engine with conservative batch defaults from a caller-configured
@@ -56,7 +176,7 @@ impl OarOcrEngine {
/// LiteParse invokes the backend with one rendered page at a time, so image
/// batching does not improve throughput here. A region batch of one avoids
/// multiplying temporary recognition tensors on dense pages.
- pub fn from_builder(builder: OAROCRBuilder) -> Result<Self, OCRError> {
+ pub fn from_builder(builder: OAROCRBuilder) -> Result<Self, LiteParseError> {
let runtime = builder.image_batch_size(1).region_batch_size(1).build()?;
Ok(Self::from_runtime(runtime))
}
@@ -106,7 +226,7 @@ impl OcrEngine for OarOcrEngine {
image_data: &'c [u8],
width: u32,
height: u32,
- _options: &'b OcrOptions,
+ options: &'b OcrOptions,
) -> Pin<
Box<
dyn Future<Output = Result<Vec<OcrResult>, Box<dyn std::error::Error + Send + Sync>>>
@@ -114,12 +234,27 @@ impl OcrEngine for OarOcrEngine {
+ '_,
>,
> {
+ warn_language_ignored_once(&options.language);
// `ocr_and_merge_rendered` polls this future on a blocking worker, so
// synchronous ONNX inference does not occupy an async runtime worker.
Box::pin(async move { self.recognize_sync(image_data, width, height) })
}
}
+static LANGUAGE_IGNORED_WARNING: Once = Once::new();
+
+/// Warn once per process that this backend ignores `OcrOptions::language`.
+fn warn_language_ignored_once(language: &str) {
+ if language.is_empty() {
+ return;
+ }
+ LANGUAGE_IGNORED_WARNING.call_once(|| {
+ eprintln!(
+ "[oar-ocr] ignoring OcrOptions::language ({language:?}); recognition language is fixed by the model and character dictionary"
+ );
+ });
+}
+
fn rgb_image(image_data: &[u8], width: u32, height: u32) -> Result<image::RgbImage, io::Error> {
if width == 0 || height == 0 {
return Err(io::Error::new(
@@ -235,6 +370,21 @@ mod tests {
);
}
+ #[test]
+ fn dict_source_paths_vs_bytes() {
+ // String/path inputs are dictionary paths and reach the builder verbatim.
+ assert!(matches!(DictSource::from("dict.txt"), DictSource::Path(_)));
+ assert_eq!(
+ DictSource::from(PathBuf::from("dict.txt")).builder_path(),
+ PathBuf::from("dict.txt")
+ );
+ // Byte inputs are in-memory content; the builder path is an unused
+ // placeholder because `character_dict_content` takes precedence.
+ let content = DictSource::from(b"a\nb\n".to_vec());
+ assert!(matches!(content, DictSource::Content(_)));
+ assert_eq!(content.builder_path(), PathBuf::new());
+ }
+
#[test]
fn drops_unrecognized_or_invalid_regions() {
let box_ = BoundingBox::from_coords(0.0, 0.0, 10.0, 10.0);