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
//! Productive and safe Rust bindings/wrappers for Leptonica and Tesseract.
//!
//! Overview
//! --------
//!
//! It comes with a high level wrapper [LepTess](struct.LepTess.html) focusing on productivity and
//! memory safty:
//!
//! ```rust,no_run
//! let mut lt = leptess::LepTess::new(Some("./tests/tessdata"), "eng").unwrap();
//! lt.set_image("./tests/di.png");
//! println!("{}", lt.get_utf8_text().unwrap());
//! ```
//!
//! It also exposes low level bindings to for flexibitliy and close mirroring of upstream C APIs:
//!
//! ```rust,no_run
//! use std::path::Path;
//! let mut api = leptess::tesseract::TessApi::new(Some("./tests/tessdata"), "eng").unwrap();
//! let mut pix = leptess::leptonica::pix_read(Path::new("./tests/di.png")).unwrap();
//! api.set_image(&pix);
//!
//! let text = api.get_utf8_text();
//! println!("{}", text.unwrap());
//! ```
//!
//! Raw unsafe C API [bindings](capi/index.html) are auto-generated using bindgen at compile time.
//!
//! Build dependencies
//! ------------------
//!
//! Make sure you have Leptonica and Tesseract installed.
//!
//! For Ubuntu user:
//!
//! ```bash
//! sudo apt-get install libleptonica-dev libtesseract-dev clang
//! ```
//!
//! You will also need to install tesseract language data based on your OCR needs:
//!
//! ```bash
//! sudo apt-get install tesseract-ocr-eng
//! ```

extern crate thiserror;

pub mod capi;
pub mod leptonica;
pub mod tesseract;

use std::path::Path;

/// High level wrapper for Tesseract and Leptonica
///
/// # Examples
///
/// ## Full page OCR
///
/// ```
/// let mut lt = leptess::LepTess::new(Some("./tests/tessdata"), "eng").unwrap();
/// lt.set_image("./tests/di.png");
/// println!("{}", lt.get_utf8_text().unwrap());
/// ```
///
/// ## OCR on a specific region of the image
///
/// ```
/// # let mut lt = leptess::LepTess::new(Some("./tests/tessdata"), "eng").unwrap();
/// # lt.set_image("./tests/di.png");
/// lt.set_rectangle(&leptess::leptonica::Box::new(
///     10, 10, 200, 60,
/// ).unwrap());
/// println!("{}", lt.get_utf8_text().unwrap());
/// ```
///
/// ## Iterate bounding boxes for each recognized word
///
/// ```
/// # let mut lt = leptess::LepTess::new(Some("./tests/tessdata"), "eng").unwrap();
/// # lt.set_image("./tests/di.png");
/// let boxes = lt.get_component_boxes(
///     leptess::capi::TessPageIteratorLevel_RIL_WORD,
///     true,
/// ).unwrap();
///
/// for b in &boxes {
///     println!("{:?}", b.get_val());
/// }
/// ```

pub struct LepTess {
    tess_api: tesseract::TessApi,
}

impl LepTess {
    pub fn new(data_path: Option<&str>, lang: &str) -> Result<LepTess, tesseract::TessInitError> {
        Ok(LepTess {
            tess_api: tesseract::TessApi::new(data_path, lang)?,
        })
    }

    /// Set image to use for OCR.
    pub fn set_image(&mut self, img_uri: impl AsRef<Path>) -> Result<(), leptonica::PixError> {
        // TODO: support more uri scheme, default to file://
        let pix = leptonica::pix_read(img_uri.as_ref())?;
        self.tess_api.set_image(&pix);
        Ok(())
    }

    pub fn set_image_from_mem(&mut self, img: &[u8]) -> Result<(), leptonica::PixError> {
        let pix = leptonica::pix_read_mem(img)?;
        self.tess_api.set_image(&pix);
        Ok(())
    }

    pub fn get_source_y_resolution(&mut self) -> i32 {
        self.tess_api.get_source_y_resolution()
    }

    pub fn get_image_dimensions(&self) -> Option<(u32, u32)> {
        self.tess_api.get_image_dimensions()
    }

    /// Override image resolution.
    /// Can be used to suppress "Warning: Invalid resolution 0 dpi." output.
    pub fn set_source_resolution(&mut self, res: i32) {
        self.tess_api.set_source_resolution(res)
    }

    /// Override image resolution if not detected
    pub fn set_fallback_source_resolution(&mut self, res: i32) {
        let resolution = self.get_source_y_resolution();
        if resolution < tesseract::MIN_CREDIBLE_RESOLUTION
            || resolution > tesseract::MAX_CREDIBLE_RESOLUTION
        {
            self.tess_api.set_source_resolution(res)
        }
    }

    pub fn recognize(&self) -> i32 {
        self.tess_api.recognize()
    }

    /// Restrict OCR to a specific region of the image.
    pub fn set_rectangle(&mut self, b: &leptonica::Box) {
        self.tess_api.set_rectangle(b)
    }

    /// Extract text from current selected region of the image. By default, it is the full page.
    /// But it can be changed through [set_rectangle](struct.LepTess.html#method.set_rectangle)
    /// api.
    ///
    /// # Example
    ///
    /// ```no_run
    /// let mut lt = leptess::LepTess::new(None, "eng").unwrap();
    /// lt.set_image("./tests/di.png");
    /// println!("{}", lt.get_utf8_text().unwrap());
    /// ```
    pub fn get_utf8_text(&self) -> Result<String, std::str::Utf8Error> {
        self.tess_api.get_utf8_text()
    }

    pub fn mean_text_conf(&self) -> i32 {
        self.tess_api.mean_text_conf()
    }

    pub fn get_regions(&self) -> Option<leptonica::Boxa> {
        self.tess_api.get_regions()
    }

    /// Get the given level kind of components (block, textline, word etc.) as a leptonica-style
    /// Boxa, in reading order.If text_only is true, then only text components are returned.
    ///
    /// # Example
    ///
    /// ## Get word bounding boxes
    ///
    /// ```no_run
    /// let mut lt = leptess::LepTess::new(None, "eng").unwrap();
    /// lt.set_image("./tests/di.png");
    /// let boxes = lt.get_component_boxes(
    ///     leptess::capi::TessPageIteratorLevel_RIL_WORD,
    ///     true,
    /// ).unwrap();
    ///
    /// for b in &boxes {
    ///     println!("{:?}", b.get_val());
    /// }
    /// ```
    pub fn get_component_boxes(
        &self,
        level: capi::TessPageIteratorLevel,
        text_only: bool,
    ) -> Option<leptonica::Boxa> {
        self.tess_api.get_component_images(level, text_only)
    }
}